File: wait_callback.rst

package info (click to toggle)
pytest-qt 4.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 644 kB
  • sloc: python: 4,144; makefile: 139
file content (57 lines) | stat: -rw-r--r-- 1,951 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
waitCallback: Waiting for methods taking a callback
===================================================

.. versionadded:: 3.1

Some methods in Qt (especially ``QtWebEngine``) take a callback as argument,
which gets called by Qt once a given operation is done.

To test such code, you can use :meth:`qtbot.waitCallback <pytestqt.plugin.QtBot.waitCallback>`
which waits until the callback has been called or a timeout is reached.

The ``qtbot.waitCallback()`` method returns a callback which is callable
directly.

For example:

.. code-block:: python

   def test_js(qtbot):
       page = QWebEnginePage()
       with qtbot.waitCallback() as cb:
           page.runJavaScript("1 + 1", cb)
       cb.assert_called_with(2)  # result of the last js statement

Anything following the ``with`` block will be run only after the callback has been called.

If the callback doesn't get called during the given timeout,
:class:`qtbot.TimeoutError <pytestqt.exceptions.TimeoutError>` is raised. If it is called more than once,
:class:`qtbot.CallbackCalledTwiceError <pytestqt.wait_signal.CallbackCalledTwiceError>` is raised.

raising parameter
-----------------

Similarly to ``qtbot.waitSignal``, you can pass a ``raising=False`` parameter
(or set the ``qt_default_raising`` ini option) to avoid raising an exception on
timeouts. See :doc:`signals` for details.

Getting arguments the callback was called with
----------------------------------------------

After the callback is called, the arguments and keyword arguments passed to it
are available via ``.args`` (as a list) and ``.kwargs`` (as a dict),
respectively.

In the example above, we could check the result via:

.. code-block:: python

       assert cb.args == [2]
       assert cb.kwargs == {}

Instead of checking the arguments by hand, you can use ``.assert_called_with()``
to make sure the callback was called with the given arguments:

.. code-block:: python

       cb.assert_called_with(2)