0
0
PyTesttesting~5 mins

Fixture as function argument in PyTest

Choose your learning style9 modes available
Introduction

Fixtures help prepare things your tests need. Passing them as function arguments makes tests simple and clean.

When you need to set up a database connection before running tests.
When you want to create a temporary file for testing and clean it up after.
When you want to share common test data across multiple test functions.
When you want to initialize a web browser session before testing a website.
Syntax
PyTest
def test_function(fixture_name):
    # use fixture_name inside the test
    assert something

Just add the fixture name as a parameter to your test function.

pytest will automatically run the fixture and pass its result to your test.

Examples
This test uses the sample_data fixture to get a list and checks its sum.
PyTest
import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3]

def test_sum(sample_data):
    assert sum(sample_data) == 6
The fixture number provides a value to the test function.
PyTest
import pytest

@pytest.fixture
def number():
    return 10

def test_double(number):
    assert number * 2 == 20
Sample Program

This test uses the greeting fixture to get a string and checks if the message is correct. It also prints the message.

PyTest
import pytest

@pytest.fixture
def greeting():
    return "Hello"

def test_greeting_message(greeting):
    message = f"{greeting}, world!"
    assert message == "Hello, world!"
    print(message)
OutputSuccess
Important Notes

Fixtures run before the test function automatically.

You can use multiple fixtures by adding more arguments to the test function.

If a fixture returns a value, you can use it directly inside your test.

Summary

Fixtures provide setup data or state for tests.

Pass fixtures as function arguments to use them in tests.

pytest handles running fixtures and passing their results automatically.