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


class Ui_Dialog(object):
    def setupUi(self, dialog):
        pass


class DlgSqlWindow(QtWidgets.QWidget, Ui_Dialog):
    def _getSqlQuery(self):
        pass

    def parseSQL(self):
        return "SELECT * FROM test"


def init(self, *args):
    QtWidgets.QWidget.__init__(self)
    # self.setupUi(self)


class TestPyQgs(unittest.TestCase):
    def test_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"