@@ -418,16 +418,10 @@ close all resources created by a fixture even if one of them fails to be created
418
418
@pytest.fixture
419
419
def equipments ():
420
420
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" )]
427
422
428
423
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.
431
425
432
426
Note that if an exception happens during the *setup * code (before the ``yield `` keyword), the
433
427
*teardown * code (after the ``yield ``) will not be called.
@@ -464,6 +458,7 @@ Here's the ``equipments`` fixture changed to use ``addfinalizer`` for cleanup:
464
458
# content of test_yield3.py
465
459
466
460
import contextlib
461
+ import functools
467
462
468
463
import pytest
469
464
@@ -474,14 +469,17 @@ Here's the ``equipments`` fixture changed to use ``addfinalizer`` for cleanup:
474
469
def equipments (request ):
475
470
r = []
476
471
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 ))
479
475
r.append(equip)
480
476
return r
481
477
482
478
483
479
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
+
485
483
486
484
.. _`request-context` :
487
485
0 commit comments