Skip to content

Commit 7378f35

Browse files
Update fixtures.rst w/ finalizer order
Co-authored-by: Bruno Oliveira <[email protected]>
1 parent b6eaf31 commit 7378f35

File tree

1 file changed

+75
-2
lines changed

1 file changed

+75
-2
lines changed

doc/en/how-to/fixtures.rst

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -735,8 +735,81 @@ does offer some nuances for when you're in a pinch.
735735
.. code-block:: pytest
736736
737737
$ pytest -q test_emaillib.py
738-
. [100%]
739-
1 passed in 0.12s
738+
. [100%]
739+
1 passed in 0.12s
740+
741+
Note on finalizer order
742+
""""""""""""""""""""""""
743+
744+
Finalizers are executed in a first-in-last-out order.
745+
For yield fixtures, the first teardown code to run is from the right-most fixture, i.e. the last test parameter.
746+
747+
.. regendoc:wipe
748+
749+
.. code-block:: python
750+
751+
import pytest
752+
753+
754+
def test_bar(fix_w_yield1, fix_w_yield2):
755+
print("test_bar")
756+
757+
758+
@pytest.fixture
759+
def fix_w_yield1():
760+
yield
761+
print("after_yield_1")
762+
763+
764+
@pytest.fixture
765+
def fix_w_yield2():
766+
yield
767+
print("after_yield_2")
768+
769+
770+
.. code-block:: pytest
771+
772+
$ pytest test_module.py
773+
=========================== test session starts ============================
774+
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
775+
collected 1 item
776+
777+
test_module.py test_bar
778+
.after_yield_2
779+
after_yield_1
780+
781+
782+
783+
For finalizers, the first fixture to run is last call to `request.addfinalizer`.
784+
785+
.. code-block:: python
786+
787+
import pytest
788+
789+
790+
@pytest.fixture
791+
def fix_w_finalizers(request):
792+
request.addfinalizer(partial(print, "finalizer_2"))
793+
request.addfinalizer(partial(print, "finalizer_1"))
794+
795+
796+
def test_bar(fix_w_finalizers):
797+
print("test_bar")
798+
799+
800+
.. code-block:: pytest
801+
802+
$ pytest test_module.py
803+
=========================== test session starts ============================
804+
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
805+
collected 1 item
806+
807+
test_module.py test_bar
808+
.finalizer_1
809+
finalizer_2
810+
811+
This is so because yield fixtures use `addfinalizer` behind the scenes: when the fixture executes, `addfinalizer` registers a function that resumes the generator, which in turn calls the teardown code.
812+
740813

741814
.. _`safe teardowns`:
742815

0 commit comments

Comments
 (0)