pytest-dev / pytest-qt

pytest plugin for Qt (PyQt5/PyQt6 and PySide2/PySide6) application testing
https://pytest-qt.readthedocs.io
MIT License
409 stars 70 forks source link

Unable to consecutively test Combo box #431

Closed Arinomo closed 2 years ago

Arinomo commented 2 years ago

I have following example simple.py

from PyQt5 import QtWidgets
import sys

class MWE(QtWidgets.QWidget):

    def __init__(self):
        super().__init__()
        self.combo = QtWidgets.QComboBox(self)
        self.combo.addItem('one')
        self.combo.addItem('two')
        self.combo.addItem('three')
        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.addWidget(self.combo)

def main():
    app = QtWidgets.QApplication(sys.argv)
    widget = MWE()
    widget.show()
    app.exec_()

if __name__ == "__main__":
    main()

and a test file test_simple.py

import pytest
from simple import MWE

@pytest.fixture
def app(qtbot):
    mwe = MWE()
    qtbot.addWidget(mwe)

    return mwe

def test_combo_1(app, qtbot):
    qtbot.keyClicks(app.combo, 't')
    assert(app.combo.currentText() == 'two')

def test_combo_2(app, qtbot):
    qtbot.keyClicks(app.combo, 'th')
    assert(app.combo.currentText() == 'three')
    qtbot.keyClicks(app.combo, 'o')
    assert(app.combo.currentText() == 'one')

that always failed at test_combo_2 because it seems the second key clicks qtbot.keyClicks(app.combo, 'o') does not do anything to the combo box.

is there a way to test each item in combo box?

nicoddemus commented 2 years ago

Not sure why that does not work. Possibly you need to first clear the current text? Otherwise it is writing tho.

However, in general I suggest to just call the appropriate methods in the widgets instead of trying to emulate the exact user actions. For example instead of trying to type text into a combo box to select an item, just call combo.setCurrentText to select the desired item. This will call the appropriate signals, and then we can ensure our application is handling it appropriately.

We don't need to test ourselves that actually clicking on a combo box (or typing text on it) will behave as we expect, we can assume Qt itself is tested and works. Trying to emulate exactly the same events as an user would is hard to write, maintain, and makes for brittle tests.

Closing this for now, feel free to follow up with further questions.