Concept Explanation
In basic testing, you might find yourself writing the same "setup" code over and over—like connecting to a database or creating a test user. If you have 100 tests, and you copy-paste that setup code 100 times, your test suite becomes a nightmare to maintain.
Fixtures are PyTest's solution. A fixture is a function that runs before your test to provide the "environment" or "data" the test needs. They are reusable, modular, and much cleaner than traditional setup methods.
Syntax or Core Structure
Defining a Fixture
You use the @pytest.fixture decorator. To use a fixture in a test, just list it as an argument!
import pytest
# 1. Define the fixture
@pytest.fixture
def sample_data():
return {"id": 1, "name": "Test Item"}
# 2. Use it in a test
def test_with_fixture(sample_data):
assert sample_data["id"] == 1
assert sample_data["name"] == "Test Item"
Code Example #1 (Basic)
Using fixtures for Setup and Teardown (Cleanup).
import pytest
import os
@pytest.fixture
def temporary_file():
# SETUP: Create a file
with open("test.txt", "w") as f:
f.write("test data")
yield "test.txt" # This is what the test receives
# TEARDOWN: Delete the file after the test finishes
if os.path.exists("test.txt"):
os.remove("test.txt")
def test_file_reading(temporary_file):
with open(temporary_file, "r") as f:
assert f.read() == "test data"
Code Example #2 (Intermediate)
Parameterized Tests: Running the same test with different inputs.
import pytest
def add(a, b):
return a + b
# Run this test 3 times with different values
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
(10, 20, 30),
(-1, 1, 0)
])
def test_addition(a, b, expected):
assert add(a, b) == expected
Real World Example
Database Integration Testing: Creating a temporary database in memory that is wiped clean after every test.
import pytest
import sqlite3
@pytest.fixture
def db_conn():
conn = sqlite3.connect(":memory:") # Temp database in RAM
cursor = conn.cursor()
cursor.execute("CREATE TABLE users (name TEXT)")
yield conn
conn.close()
def test_insert_user(db_conn):
cursor = db_conn.cursor()
cursor.execute("INSERT INTO users VALUES ('Harsh')")
cursor.execute("SELECT * FROM users")
assert cursor.fetchone()[0] == "Harsh"
Common Mistakes
- Forgetting to list the fixture: You define a fixture but forget to put its name in the test function's parentheses. PyTest will try to run the test and fail because the variable is missing.
- Using
asserton non-boolean values: Beginners often forget thatassertneeds a True/False comparison.assert my_listworks (checks if not empty), but it's better to be explicit:assert len(my_list) > 0. - Heavily Overlapping Fixtures: Making one giant fixture that does everything. Keep your fixtures small and "chain" them instead (one fixture can use another fixture!).
Best Practices
- Conftest.py: If you have fixtures that many different test files need, put them in a file named
conftest.py. PyTest finds them automatically without you needing to import them. - Use Descriptive Names: Instead of
data1(), usevalid_user_profile(). It makes your tests read like a story. - Test for Errors: Don't just test if things work. Use
with pytest.raises(ValueError):to verify that your code crashes correctly when it should.
Practice Exercises
- The Calculator Fixture: Create a fixture that returns a custom
Calculatorobject. Write tests for Add, Subtract, and Multiply using that fixture. - The Error Catcher: Write a function that divides two numbers. Write a PyTest test that uses
pytest.raisesto check that dividing by zero raises aZeroDivisionError. - Parametrized Palindrome: Write a function that checks if a string is a palindrome. Use
@pytest.mark.parametrizeto test it with 5 different strings (some true, some false).