What if you could write setup code once and have it magically ready for all your tests?
Why @pytest.fixture decorator? - Purpose & Use Cases
Imagine you have many tests that need the same setup, like creating a user account or connecting to a database. You write the setup steps inside each test manually.
This manual way is slow and boring. If you want to change the setup, you must edit every test. It's easy to forget one and get wrong results. It also makes your test code messy and hard to read.
The @pytest.fixture decorator lets you write the setup code once and share it with many tests. It runs the setup automatically before tests that need it, keeping your tests clean and easy to change.
def test_a(): user = create_user() assert user.is_active def test_b(): user = create_user() assert user.name == 'test'
import pytest @pytest.fixture def user(): return create_user() def test_a(user): assert user.is_active def test_b(user): assert user.name == 'test'
You can write simpler, cleaner tests that share setup code easily and stay correct even when things change.
When testing a website, many tests need a logged-in user. Using @pytest.fixture, you create the user once and reuse it in all tests without repeating code.
Manual setup in each test is slow and error-prone.
@pytest.fixture shares setup code cleanly.
Tests become easier to write, read, and maintain.
Practice
@pytest.fixture decorator in pytest?Solution
Step 1: Understand what
The@pytest.fixturedoes@pytest.fixturedecorator is used to create setup code that can be reused in many tests to avoid repetition.Step 2: Compare options with the fixture purpose
Options A, B, and C describe other pytest features, not fixtures.Final Answer:
To create reusable setup code that can be shared across multiple tests -> Option CQuick Check:
Fixture = reusable setup code [OK]
- Confusing fixtures with test skipping or marking
- Thinking fixtures run tests themselves
- Believing fixtures are only for cleanup
db_connection in pytest?Solution
Step 1: Identify correct decorator usage
The correct decorator for fixtures is@pytest.fixture, fully qualified with the pytest module.Step 2: Check each option
@pytest.fixture def db_connection(): pass uses@pytest.fixturecorrectly. def db_connection(): pass misses the decorator. @fixture def db_connection(): pass uses@fixturewithout importing. @pytest.test def db_connection(): pass uses@pytest.testwhich is invalid.Final Answer:
@pytest.fixture def db_connection(): pass -> Option BQuick Check:
Use@pytest.fixturebefore function [OK]
- Omitting the @pytest.fixture decorator
- Using @fixture without importing pytest
- Confusing @pytest.test with fixture decorator
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3]
def test_sum(sample_data):
assert sum(sample_data) == 6
print('Test passed')Solution
Step 1: Understand fixture usage
The fixturesample_datareturns a list [1, 2, 3]. The test receives this list as argument.Step 2: Check assertion and print
The sum of [1, 2, 3] is 6, so the assertion passes. The print statement runs and outputs 'Test passed'.Final Answer:
Test passed printed and test passes -> Option DQuick Check:
Fixture provides data, assertion true, print runs [OK]
- Assuming fixture causes syntax error
- Thinking print won't show during test run
- Believing assertion fails with correct sum
import pytest
@pytest.fixture
def resource():
setup = open('file.txt')
yield setup
setup.close()Solution
Step 1: Analyze fixture code
The fixture opens a file and yields the file object, then closes it after test.Step 2: Identify potential runtime issue
If 'file.txt' does not exist, open() will raise an error before yield. This is a runtime error, not syntax.Final Answer:
File 'file.txt' may not exist causing runtime error -> Option AQuick Check:
File open can fail if file missing [OK]
- Thinking yield needs parentheses
- Believing fixtures cannot use yield
- Ignoring file existence errors
import pytest
@pytest.fixture
def temp_file():
f = open('temp.txt', 'w')
yield f
f.close()Solution
Step 1: Understand fixture cleanup with yield
Using yield in fixtures allows code after yield to run as cleanup after the test finishes.Step 2: Ensure cleanup runs even if test fails
Wrapping yield with try-finally ensures the cleanup code (file close) runs no matter what happens in the test.Final Answer:
Use try-finally inside the fixture around yield -> Option AQuick Check:
try-finally ensures cleanup after yield [OK]
- Replacing yield with return loses cleanup
- Closing file before yield stops test using it
- Adding separate test for cleanup is incorrect
Ready to prove it?
Pass the test and this pattern moves unknown
