|
| 1 | +.. _invocation_scoped_fixture: |
| 2 | + |
| 3 | +Invocation-scoped fixtures |
| 4 | +========================== |
| 5 | + |
| 6 | +.. versionadded:: 3.0 |
| 7 | + |
| 8 | +.. note:: |
| 9 | + This feature is experimental, so if decided that it brings too much problems |
| 10 | + or considered too complicated it might be removed in pytest ``3.1``. |
| 11 | + |
| 12 | + ``tmpdir`` and ``monkeypatch`` might become ``invocation`` scoped |
| 13 | + fixtures in the future if decided to keep invocation-scoped fixtures. |
| 14 | + |
| 15 | +Fixtures can be defined with ``invocation`` scope, meaning that the fixture |
| 16 | +can be requested by fixtures from any scope, but when they do they assume |
| 17 | +the same scope as the fixture requesting it. |
| 18 | + |
| 19 | +An ``invocation``-scoped fixture can be requested from different scopes |
| 20 | +in the same test session, in which case each scope will have its own copy. |
| 21 | + |
| 22 | +Example |
| 23 | +------- |
| 24 | + |
| 25 | +Consider a fixture which manages external process execution: |
| 26 | +this fixture provides auxiliary methods for tests and fixtures to start external |
| 27 | +processes while making sure the |
| 28 | +processes terminate at the appropriate time. Because it makes sense |
| 29 | +to start a webserver for the entire session and also to execute a numerical |
| 30 | +simulation for a single test function, the ``process_manager`` |
| 31 | +fixture can be declared as ``invocation``, so each scope gets its own |
| 32 | +value and can manage processes which will live for the duration of the scope. |
| 33 | + |
| 34 | +.. code-block:: python |
| 35 | +
|
| 36 | + import pytest |
| 37 | +
|
| 38 | + @pytest.fixture(scope='invocation') |
| 39 | + def process_manager(): |
| 40 | + m = ProcessManager() |
| 41 | + yield m |
| 42 | + m.shutdown_all() |
| 43 | +
|
| 44 | +
|
| 45 | + @pytest.fixture(scope='session') |
| 46 | + def server(process_manager): |
| 47 | + process_manager.start(sys.executable, 'server.py') |
| 48 | +
|
| 49 | +
|
| 50 | + @pytest.fixture(scope='function') |
| 51 | + def start_simulation(process_manager): |
| 52 | + import functools |
| 53 | + return functools.partial(process_manager.start, |
| 54 | + sys.executable, 'simulator.py') |
| 55 | +
|
| 56 | +
|
| 57 | +In the above code, simulators started using ``start_simulation`` will be |
| 58 | +terminated when the test function exits, while the server will be kept |
| 59 | +active for the entire simulation run, being terminated when the test session |
| 60 | +finishes. |
| 61 | + |
0 commit comments