The @pytest.fixture decorator helps create reusable setup code for tests. It makes tests cleaner and avoids repeating the same preparation steps.
@pytest.fixture decorator
@pytest.fixture def fixture_name(): # setup code yield resource # teardown code (optional)
The function decorated with @pytest.fixture can return or yield a resource.
Using yield allows you to run cleanup code after the test finishes.
@pytest.fixture def sample_data(): return [1, 2, 3]
@pytest.fixture def open_file(): f = open('test.txt', 'w') yield f f.close()
This test script uses the numbers fixture to provide a list to two tests. Both tests use the same data without repeating setup code.
import pytest @pytest.fixture def numbers(): return [10, 20, 30] def test_sum(numbers): assert sum(numbers) == 60 def test_max(numbers): assert max(numbers) == 30
Fixtures improve test readability and reduce duplicated setup code.
You can use fixtures inside other fixtures to build complex setups.
Fixtures can have scopes like function, module, or session to control how often they run.
@pytest.fixture creates reusable setup code for tests.
Fixtures help keep tests clean and avoid repeating preparation steps.
Use yield in fixtures to add cleanup after tests run.
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
