Usefixtures example

Let’s go back to our basic example, but explore the use of usefixtures.

usefixtures is a marker that accepts a list of fixture names as strings, and applies it to something.

You can use it on an individual test. However, it’d be pretty silly as named parameters are easier.

However, this is what it’d look like to mark individual tests:

# test_usefixtures.py
import pytest

@pytest.fixture()
def before():
    print('\nbefore each test')

@pytest.mark.usefixtures("before") 
def test_1():
    ...

@pytest.mark.usefixtures("before") 
def test_2():
    ...

And it also works for test methods:

class Test:
    @pytest.mark.usefixtures("before")
    def test_1(self):
        ...

    @pytest.mark.usefixtures("before")
    def test_2(self):
        ...

usefixtures to apply fixtures to class methods

One handy place to use usefixtures is if you want a set of fixtures to apply to all the tests of a class:

@pytest.mark.usefixtures("before")
class TestSomething:
    def test_1(self):
        ...

    def test_2(self):
        ...

usefixtures to apply fixtures to all tests in a file

You can do this for all tests in a file also with pytestmark.

import pytest

pytestmark = pytest.mark.usefixtures("before")

@pytest.fixture()
def before():
    print('\nbefore each test')

def test_1():
    ...

def test_2():
    ...

If you’re defining a fixture in the same test file, this is less common, as you can just use autouse.

However, fixtures can be defined in conftest.py files also, and in plugins.
In those cases, it totally might make sense to use usefixtures for all tests in a file.