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

George Shuklin
OpsOps
1 min readApr 20, 2023

--

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:

  1. Move all functions required the fixture into a class (make them class methods)
  2. Mark the fixture as scope=”class”
  3. 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.

--

--

George Shuklin
OpsOps

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.