Skip to content

Commit a44e21a

Browse files
committed
tests: add the defer fixture
to ease the resource management in some complex tests. See the defer docstring in conftest.py for more details. Signed-off-by: Gaëtan Lehmann <gaetan.lehmann@vates.tech>
1 parent b2b7612 commit a44e21a

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

conftest.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import lib.config as global_config
1414
from lib import pxe
1515
from lib.common import (
16+
Defer,
1617
DiskDevName,
1718
HostAddress,
1819
callable_marker,
@@ -766,3 +767,36 @@ def cifs_iso_sr(host: Host, cifs_iso_device_config: dict[str, Any]) -> Generator
766767
yield sr
767768
# teardown
768769
sr.forget()
770+
771+
@pytest.fixture()
772+
def defer(request: pytest.FixtureRequest) -> Defer:
773+
"""
774+
A Go-inspired cleanup fixture that registers functions to be executed
775+
after the test completes.
776+
777+
This fixture provides a functional alternative to 'yield' fixtures and
778+
'try...finally' blocks. It is particularly useful for managing resources
779+
that must remain 'alive' during post-mortem debugging (e.g., --pdb), as
780+
registered finalizers only execute after the debugger session exits.
781+
782+
Execution Order:
783+
Finalizers are executed in LIFO (Last-In, First-Out) order. The last
784+
function deferred will be the first one executed during teardown.
785+
786+
Usage:
787+
def test_example(defer):
788+
resource = create_resource()
789+
defer(lambda: resource.cleanup())
790+
791+
# If an assertion fails here, 'resource' is still available
792+
# for inspection in --pdb.
793+
assert resource.is_valid()
794+
795+
Args:
796+
request: The internal pytest request object used to register finalizers.
797+
798+
Returns:
799+
The 'request.addfinalizer' method, allowing for immediate registration
800+
of teardown logic.
801+
"""
802+
return request.addfinalizer

lib/common.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444

4545
HostAddress: TypeAlias = str
4646
DiskDevName: TypeAlias = str
47+
Defer: TypeAlias = Callable[[Callable[[], object]], None]
4748

4849
class PackageManagerEnum(Enum):
4950
UNKNOWN = 1

0 commit comments

Comments
 (0)