Fixtures help you prepare things once and use them many times in your tests. This saves time and keeps tests clean.
Why fixtures provide reusable test setup in PyTest
import pytest @pytest.fixture def resource(): # setup code resource_object = [] yield resource_object # teardown code
Use @pytest.fixture to mark a function as a fixture.
The yield keyword separates setup and teardown parts.
import pytest @pytest.fixture def sample_data(): data = [1, 2, 3] return data
import pytest @pytest.fixture def open_file(): f = open('test.txt', 'w') yield f f.close()
This example shows a fixture number_list that sets up a list for tests. The setup message prints once before tests, and the teardown message prints after tests finish.
import pytest @pytest.fixture(scope="module") def number_list(): print('Setup: Creating list') data = [10, 20, 30] yield data print('Teardown: Cleaning up') def test_sum(number_list): assert sum(number_list) == 60 def test_len(number_list): assert len(number_list) == 3
Fixtures run before the test that uses them and can clean up after with yield.
Using fixtures avoids repeating setup code in every test function.
Fixtures can be shared across many tests for consistency.
Fixtures prepare reusable test setup to keep tests simple and clean.
They help avoid repeating the same setup code in multiple tests.
Fixtures can also handle cleanup after tests automatically.
Practice
Solution
Step 1: Understand the purpose of fixtures in pytest
Fixtures are designed to prepare setup code that can be reused by many tests, avoiding repetition.Step 2: Compare options with fixture purpose
Only They provide reusable setup code that multiple tests can share correctly states that fixtures provide reusable setup code. Other options describe unrelated features.Final Answer:
They provide reusable setup code that multiple tests can share -> Option BQuick Check:
Reusable setup = fixtures help keep tests clean [OK]
- Thinking fixtures generate test data automatically
- Confusing fixtures with test runners
- Believing fixtures replace assertions
Solution
Step 1: Identify correct fixture decorator syntax
Pytest fixtures require the decorator @pytest.fixture above the function.Step 2: Check each option's decorator
@pytest.fixture def setup_data(): return {'key': 'value'} uses @pytest.fixture correctly. def setup_data(): return {'key': 'value'} misses decorator, A uses wrong decorator @pytest.test, D uses incomplete decorator @fixture without pytest prefix.Final Answer:
@pytest.fixture\ndef setup_data():\n return {'key': 'value'} -> Option CQuick Check:
@pytest.fixture decorator is required [OK]
- Omitting the @pytest.fixture decorator
- Using incorrect decorators like @pytest.test
- Using @fixture without pytest prefix
test_example?
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3]
def test_example(sample_data):
assert sum(sample_data) == 6
print('Test passed')Solution
Step 1: Understand fixture usage in test
The fixture sample_data returns [1, 2, 3]. The test asserts sum is 6, which is correct.Step 2: Check test behavior
Since assertion passes, test passes. Pytest captures stdout by default and does not show print output for passing tests (use -s to show). Thus, no 'Test passed' is printed.Final Answer:
No output because print is ignored -> Option AQuick Check:
Fixture provides data, assertion correct, test passes [OK]
- Thinking print output is shown by default
- Thinking fixture is missing causing error
- Believing sum is incorrect
import pytest
@pytest.fixture
def resource():
return open('file.txt', 'r')
def test_read(resource):
data = resource.read()
assert data != ''
resource.close()Solution
Step 1: Analyze resource fixture and test
The fixture opens a file but does not close it. The test closes it manually.Step 2: Understand best practice for cleanup
Fixtures should handle cleanup automatically using yield or finalizers to avoid resource leaks if test fails before close.Final Answer:
The fixture should close the file after test automatically -> Option AQuick Check:
Fixtures manage setup and cleanup [OK]
- Not closing resources in fixtures
- Closing resources only in tests
- Ignoring cleanup causing leaks
@pytest.fixture
def db_connection():
conn = connect_to_db()
return connSolution
Step 1: Understand fixture cleanup with yield
Using yield in a fixture allows setup before yield and cleanup after yield, ensuring resource is closed after test.Step 2: Evaluate options for proper cleanup
Use yield in fixture and close connection after yield@pytest.fixture def db_connection(): conn = connect_to_db() yield conn conn.close()correctly uses yield and closes connection after test. Add a try-except block inside the fixture to catch errors does not guarantee cleanup. Call conn.close() before returning conn closes before returning, breaking connection. Remove the fixture and open connection inside each test removes fixture benefits.Final Answer:
Use yield in fixture and close connection after yield -> Option DQuick Check:
Yield fixtures handle setup and cleanup [OK]
- Closing resource before returning it
- Not cleaning up resources after tests
- Avoiding fixtures and duplicating code
Ready to prove it?
Pass the test and this pattern moves unknown
