Function Scope Fixture in pytest: What It Is and How It Works
function scope fixture is a setup function that runs once for each test function that uses it. It helps prepare test data or state fresh for every test, ensuring tests do not affect each other.How It Works
A function scope fixture in pytest runs before each test function that requests it, and it cleans up after that test finishes. Think of it like preparing a fresh workspace for every single task you do, then cleaning it up before starting the next one. This ensures each test starts with a clean state, avoiding leftover data or side effects from previous tests.
When you mark a fixture with @pytest.fixture(scope='function') (which is the default), pytest calls this fixture once per test function. This is useful when tests need isolated environments or fresh data to run correctly. After the test ends, pytest can also run any cleanup code you define in the fixture.
Example
import pytest @pytest.fixture(scope='function') def fresh_list(): return [] def test_append_one(fresh_list): fresh_list.append(1) assert fresh_list == [1] def test_append_two(fresh_list): fresh_list.append(2) assert fresh_list == [2]
When to Use
Use function scope fixtures when you want to ensure each test runs independently with a clean setup. This is important when tests modify shared data or state, and you want to avoid tests affecting each other.
For example, if you test functions that change a database, a function scope fixture can reset the database state before each test. Or if you test code that modifies a list or file, the fixture can provide a fresh copy every time.
Key Points
- Function scope is the default fixture scope in pytest.
- Fixtures run once per test function, ensuring isolation.
- Useful for setup and cleanup that must be fresh for every test.
- Helps avoid flaky tests caused by shared state.