Skip to content

Commit 88fc45b

Browse files
aizpurua23apytestbot
authored andcommitted
[7.1.x] Update fixtures.rst w/ finalizer order
1 parent d0b53d6 commit 88fc45b

File tree

1 file changed

+75
-2
lines changed

1 file changed

+75
-2
lines changed

doc/en/how-to/fixtures.rst

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

739812
.. _`safe teardowns`:
740813

0 commit comments

Comments
 (0)