Skip to content Skip to sidebar Skip to footer

Mock A Pyqt Method

I have an existing class which inherits from the PyQT5 classes QWidget and Ui_Dialog. I want to use some functionality of the class which is not at all related to the GUI. I have t

Solution 1:

One possible solution is to just call the super QWidget who doesn't have much logic:

import unittest
from unittest.mock import patch

from PyQt5 import QtWidgets


classUi_Dialog(object):
    defsetupUi(self, dialog):
        passclassDlgSqlWindow(QtWidgets.QWidget, Ui_Dialog):
    def_getSqlQuery(self):
        passdefparseSQL(self):
        return"SELECT * FROM test"definit(self, *args):
    QtWidgets.QWidget.__init__(self)
    # self.setupUi(self)classTestPyQgs(unittest.TestCase):
    deftest_comment_parsing(self):
        app = QtWidgets.QApplication([])
        query = "SELECT * FROM test"with patch.object(DlgSqlWindow, "__init__", init):
            with patch.object(DlgSqlWindow, "_getSqlQuery", return_value=query):
                a = DlgSqlWindow(None, None)
                self.assertEqual(a.parseSQL(), query)


if __name__ == "__main__":
    unittest.main()

But as you point out, the optimal solution is to refactor your code since it seems that you are mixing business logic with the GUI which, as you can see, causes several inconveniences and is not maintainable.

Post a Comment for "Mock A Pyqt Method"