Last active
December 11, 2015 22:49
-
-
Save pelme/4671923 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytest | |
from contextlib import contextmanager | |
from functools import wraps | |
# TODO: Make it possible to pass standard pytest.fixture args here too, like scope, params etc.. | |
def pytest_contextfixture(fn): | |
ctxmgr = contextmanager(fn) | |
@pytest.fixture | |
@wraps(fn) | |
def actual_fixture(request, scope='function'): | |
ctxinst = ctxmgr() | |
# TODO: Proper exception propagation? | |
request.addfinalizer(lambda: ctxinst.__exit__(None, None, None)) | |
return ctxinst.__enter__() | |
return actual_fixture | |
@pytest_contextfixture | |
def my_fixture(): | |
# Test setup with possibly nested with-blocks can be performed here | |
yield 1234 | |
# Teardown is possible here. | |
def test_something(my_fixture): | |
assert my_fixture == 1234 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@hpk42 No, the teardown/exit executes in the right order. I have packaged this gist up at https://github.com/pelme/pytest-contextfixture with tests that prove this too!
Yes, using context managers like this breaks fixture ordering, but in my use case I am not really concerned about that.
To give a more concrete example: The context managers I am using are mostly mock patchers, where I only use function scope.
i.e.
Today, I am doing something like this (which indeed works, but it feels a bit awkward):
Those mocks is not really suitable for re-use as standalone fixtures, and most of these fixtures are defined in the local test modules themselves.
For more general fixtures, they should be defined as modular fixtures themselves.
There might be a better solution all together, but I hope this shows my reasoning. :)