41

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?

1

3 Answers 3

38

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.).

Sign up to request clarification or add additional context in comments.

6 Comments

Link does not appear to work. Maybe this is the same?
@djvg Both links no longer work. Is there another link?
@a-hendry: Sorry, I wouldn't know, mine was already a guess.
The content of original the link can be found here thanks to the Wayback Machine.
The code in the ref. page is available here: https://github.com/jmcgeheeiv/pyqttestexample
|
14

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!"

Comments

2

There is perfect tutorial where they use pytest-qt:

https://www.youtube.com/watch?v=WjctCBjHvmA&ab_channel=AdamBemski https://github.com/adambemski/blog/tree/master/006_pytest_qt_GUI_testing

It is really simple, there is a code from the tutorial:

import pytest

from PyQt5 import QtCore

import example_app


@pytest.fixture
def app(qtbot):
    test_hello_app = example_app.MyApp()
    qtbot.addWidget(test_hello_app)

    return test_hello_app


def test_label(app):
    assert app.text_label.text() == "Hello World!"


def test_label_after_click(app, qtbot):
    qtbot.mouseClick(app.button, QtCore.Qt.LeftButton)
    assert app.text_label.text() == "Changed!"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.