Concise use of class-scoped fixtures
How to use class-scoped fixtures only for a single class without specifying it in each test method signature
I found another gem in Pytest idioms.
The problem: There is a slow setup/teardown fixture I need to call once before large group of tests. There are other tests in the module which do not need this fixture. I don’t want to type fixture name into each test function.
The solution:
- Move all functions required the fixture into a class (make them class methods)
- Mark the fixture as
scope=”class”
- Use
@pytest.mark.usefixtures
on the class (not on the functions!) to use the fixture.
Code example:
import pytest
@pytest.fixture(scope="class")
def bar():
print("fxiture setup")
yield
print("fxiture teardown")
@pytest.mark.usefixtures('bar')
class TestFoo():
@pytest.mark.parametrize("foo", [1,2])
def test1(self, foo):
assert foo
@pytest.mark.parametrize("foo", [11,22])
def test2(self, foo):
assert foo
class TestBaz():
def test3(self):
pass
In this code TestFoo.test1
and TestFoo.test2
are called after ‘fixture setup’, and ‘fixture teardown’ is performed after the last test in TestFoo
.
TestBaz.test3
does not get the fixture foo
.
Note, that each test1
and test2
don’t need to specify bar
fixture in their signature.