How Do You Pass Parameters to Fixtures in Pytest?

Better Stack Team
Updated on August 14, 2024

In pytest, passing parameters to fixtures instead of directly to test functions can enhance code reusability and simplify test setups.

For example, if you're testing file handling, you might pass file paths directly to your test functions. This approach requires you to create an instance of the FileReader class in each test, as shown:

 
import pytest

class FileReader:
    def __init__(self, file_path):
        self.file_path = file_path

    def read_content(self):
        with open(self.file_path, 'r') as file:
            return file.read()

class TestFileReader:
    @pytest.mark.parametrize('file_path', ['file1.txt', 'file2.txt'])
    def test_read_content(self, file_path):
        reader = FileReader(file_path)
        content = reader.read_content()
        assert content == "Expected content"

In this example, each test function creates a FileReader instance.

However, a more elegant solution involves using pytest fixtures with indirect=True. This approach allows you to create a fixture that handles the initialization of the FileReader object, which can then be injected into your tests:

 
import pytest

class FileReader:
    def __init__(self, file_path):
        self.file_path = file_path

    def read_content(self):
        with open(self.file_path, 'r') as file:
            return file.read()

@pytest.fixture
def file_reader(request):
    return FileReader(request.param)

class TestFileReader:
    @pytest.mark.parametrize('file_reader', ['file1.txt', 'file2.txt'], indirect=True)
    def test_read_content(self, file_reader):
        content = file_reader.read_content()
        assert content == "Expected content"

Here, the file_reader fixture constructs the FileReader instance. The indirect=True parameter in @pytest.mark.parametrize instructs pytest to pass the parameters to the fixture rather than directly to the test function. This method centralizes object creation and allows the tests to focus on verifying behaviour, which is especially beneficial for complex setups or when reusing setups across multiple tests.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.