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

Problem when testing QHttpServer #509

Closed wiktor-k closed 1 year ago

wiktor-k commented 1 year ago

Hi,

I've got a fairly standard PySide6 window which starts a QHttpServer on a button press. It works well when I manually run it but I when running under pytest-qt the server never replies (as if the event loop is stuck).

I don't know if it's something I could easily adjust or maybe I'm just holding it wrong.

I wrote a simple project for reproducing it:

Thanks for this great library! I'm using it to great extent in other scenarios and it works very well :clap:

nicoddemus commented 1 year ago

Hi @wiktor-k,

Thanks for the reproducer (I couldn't run it because QHttpServer was not available in PySide6 on Windows for some reason).

The problem is that this call:

resp = conn.getresponse()

Is blocking, so it is blocking the event loop and not letting the QHttpServer process the request.

You will need to execute that in a thread, something like this (untested);


def test_start_server(qtbot):
    window = Window()
    qtbot.addWidget(window)
    qtbot.mouseClick(window.button, QtCore.Qt.MouseButton.LeftButton)

    conn = HTTPConnection("127.0.0.1", 19841)

    conn.request("GET", "/")

    # conn.getresponse() is blocking,
    # so we execute it in a thread.
    resp = None

    def get_response_in_thread():
        nonlocal resp
        resp = conn.getresponse()

    t = threading.Thread(target=get_response_in_thread)
    t.start()

    # waitUntil() waits for the response to arrive,
    # while keeping the Qt event loop running.
    qtbot.waitUntil(lambda: resp is not None)
    assert resp.status == 200
wiktor-k commented 1 year ago

Excellent response. Thanks a lot @nicoddemus!

I've adjusted your code to fix minor things (thread target, waitUntil lambda) and overall I'm very happy.

I've pushed working code example in a separate commit, just in case someone has a similar problem: https://github.com/wiktor-k/qhttp-test/commit/f2617ba57f9664bf4e3962a58b57c07211d0fa1d

And, I guess this is all so I'm closing the issue. Once again: thank you :pray:

(QHttpServer not being available on Windows is kind of annoying... I thought I'll have cross-platform portability, oh well :/)

nicoddemus commented 1 year ago

Thanks, I edited my post to fix the mistakes in case others stumble on it.

wiktor-k commented 11 months ago

Thanks for the reproducer (I couldn't run it because QHttpServer was not available in PySide6 on Windows for some reason).

Just in case someone stumbles upon this I've reported the issue to Qt (PYSIDE-2402) and they fixed it and it seems to be working in version 6.6.

See ya! :wave: