38

I heard Unit Testing is a great method to keep code working correctly.

The unit testing usually puts a simple input to a function, and check its simple output. But how do I test a UI?

My program is written in PyQt. Should I choose PyUnit, or Qt's built-in QTest?

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
比尔盖子
  • 2,693
  • 5
  • 37
  • 53
  • http://stackoverflow.com/questions/11145583/unit-and-functional-testing-a-pyside-based-application – eric Mar 25 '15 at 01:16

2 Answers2

37

There's a good tutorial about using Python's unit testing framework with QTest here (old link that does not work anymore. From the WayBackMachine, the page is displayed here).

It isn't about choosing one or the other. Instead, it's about using them together. The purpose of QTest is only to simulate keystrokes, mouse clicks, and mouse movement. Python's unit testing framework handles the rest (setup, teardown, launching tests, gathering results, etc.).

Nav
  • 19,885
  • 27
  • 92
  • 135
WLin
  • 1,394
  • 10
  • 14
  • 1
    Link does not appear to work. Maybe [this](http://johnnado.com/pyqt-qtest-example/) is the same? – djvg Jul 27 '17 at 14:49
  • @djvg Both links no longer work. Is there another link? – adam.hendry Aug 07 '21 at 01:19
  • @a-hendry: Sorry, I wouldn't know, mine was already a guess. – djvg Aug 07 '21 at 17:05
  • 1
    The content of original the link can be found [here](https://web.archive.org/web/20130903012954/http://www.voom.net/pyqt-qtest-example) thanks to the Wayback Machine. – Ray B Sep 29 '21 at 20:29
  • 2
    The code in the ref. page is available here: [https://github.com/jmcgeheeiv/pyqttestexample](https://github.com/jmcgeheeiv/pyqttestexample) – tonyjosi Dec 17 '21 at 07:03
  • I am the author. The `johnnado.com` / `voom.net` blog article has been merged into the example code https://github.com/jmcgeheeiv/pyqttestexample to make a unified open source project. Contributors wanted! – John McGehee May 20 '23 at 17:58
11

As another option there is also pytest-qt if you prefer working with pytest:

https://pytest-qt.readthedocs.io/en/latest/intro.html

It lets you test pyqt and pyside applications and allows the simulation of user interaction. Here is a small example from its documentation:

def test_hello(qtbot):
    widget = HelloWidget()
    qtbot.addWidget(widget)

    # click in the Greet button and make sure it updates the appropriate label
    qtbot.mouseClick(widget.button_greet, QtCore.Qt.LeftButton)

    assert widget.greet_label.text() == "Hello!"

rayon
  • 490
  • 7
  • 16