Py.test - how to use context manager in funcarg / fixture

Closely related: In python there is a good idiom for using context managers in setting / disabling .


I have a context manager that is used in tests to fix the time / time zone. I want it to be in pytest funcarg (or fixture, we use pytest2.2.3, but I can translate back). I could just do this:

def pytest_funcarg__fixedTimezone(request):
    # fix timezone to match Qld, no DST to worry about and matches all
    # Eastern states in winter.
    fixedTime = offsetTime.DisplacedRealTime(tz=' Australia/Brisbane')

    def setup():
        fixedTime.__enter__()
        return fixedTime

    def teardown(fixedTime):
        # this seems rather odd?
        fixedTime.__exit__(None, None, None)

... but it's a little bad. The linked Q jsbueno states: the problem is that your code does not have the right to call the method correctly __exit__if an exception occurs.

. pytest, - , . , pytest-y ? -, runtest hooks?

+5
2

2.4, py.test yield. with .

@pytest.yield_fixture
def passwd():
    with open("/etc/passwd") as f:
        yield f.readlines()

3.0, py.test @pytest.yield_fixture. @pytest.fixture .

@pytest.fixture
def passwd():
    with open("/etc/passwd") as f:
        yield f.readlines()
+9

, . , :

import contextlib, pytest

@contextlib.contextmanager
def manager():
    print 'manager enter'
    yield 42
    print 'manager exit'

@pytest.fixture
def fix(request):
    m = manager()
    request.addfinalizer(lambda: m.__exit__(None, None, None))
    return m.__enter__()

def test_foo(fix):
    print fix
    raise Exception('oops')

pytest -s, , __exit__().

0

All Articles