Skip to content

Commit a96710d

Browse files
committed
demonstrate ExitStack assuming connect returns a context manager
1 parent c224c4f commit a96710d

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

doc/en/fixture.rst

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -418,16 +418,10 @@ close all resources created by a fixture even if one of them fails to be created
418418
@pytest.fixture
419419
def equipments():
420420
with contextlib.ExitStack() as stack:
421-
r = []
422-
for port in ("C1", "C3", "C28"):
423-
equip = connect(port)
424-
stack.callback(equip.disconnect)
425-
r.append(equip)
426-
yield r
421+
yield [stack.enter_context(connect(port)) for port in ("C1", "C3", "C28")]
427422
428423
In the example above, if ``"C28"`` fails with an exception, ``"C1"`` and ``"C3"`` will still
429-
be properly closed. Of course, if an exception happens before the finalize function is
430-
registered then it will not be executed.
424+
be properly closed.
431425

432426
Note that if an exception happens during the *setup* code (before the ``yield`` keyword), the
433427
*teardown* code (after the ``yield``) will not be called.
@@ -464,6 +458,7 @@ Here's the ``equipments`` fixture changed to use ``addfinalizer`` for cleanup:
464458
# content of test_yield3.py
465459
466460
import contextlib
461+
import functools
467462
468463
import pytest
469464
@@ -474,14 +469,17 @@ Here's the ``equipments`` fixture changed to use ``addfinalizer`` for cleanup:
474469
def equipments(request):
475470
r = []
476471
for port in ("C1", "C3", "C28"):
477-
equip = connect(port)
478-
request.addfinalizer(equip.disconnect)
472+
cm = connect(port)
473+
equip = cm.__enter__()
474+
request.addfinalizer(functools.partial(cm.__exit__, None, None, None))
479475
r.append(equip)
480476
return r
481477
482478
483479
Both ``yield`` and ``addfinalizer`` methods work similarly by calling their code after the test
484-
ends.
480+
ends. Of course, if an exception happens before the finalize function is registered then it
481+
will not be executed.
482+
485483

486484
.. _`request-context`:
487485

0 commit comments

Comments
 (0)