Database fixture patterns help set up and clean test data before and after tests run. This keeps tests reliable and repeatable.
When you need to prepare test data in a database before running tests.
When you want to clean up database changes after tests to avoid side effects.
When multiple tests share the same database setup to save time.
When you want to isolate tests so they don't affect each other's data.
Syntax
PyTest
import pytest
@pytest.fixture(scope='function')
def db_setup():
# Connect to database# Insert test datayield# Clean up test data# Close connection
Use @pytest.fixture to create a fixture function.
The scope controls how often the fixture runs (e.g., per function, module).
Examples
This fixture inserts user data before each test and deletes it after.
PyTest
import pytest
@pytest.fixture(scope='function')
def setup_user():
print('Insert user data')
yieldprint('Delete user data')
This fixture connects to the database once per module and disconnects after all tests finish.
PyTest
import pytest
@pytest.fixture(scope='module')
def setup_db():
print('Connect to DB')
yieldprint('Disconnect from DB')
Sample Program
This test uses the db_setup fixture to prepare and clean test data around the test.
PyTest
import pytest
@pytest.fixture(scope='function')
def db_setup():
print('Setup: Insert test data')
yieldprint('Teardown: Remove test data')
def test_example(db_setup):
print('Running test')
assertTrue
OutputSuccess
Important Notes
Always clean up test data to keep tests independent.
Use yield in fixtures to separate setup and teardown steps.
Choose fixture scope wisely to balance speed and isolation.
Summary
Database fixtures prepare and clean test data automatically.
Fixtures use @pytest.fixture and yield for setup and teardown.
Proper fixture use makes tests reliable and easy to maintain.
Practice
(1/5)
1. What is the main purpose of using database fixtures in pytest?
easy
A. To speed up the database server
B. To write SQL queries inside test functions
C. To prepare and clean test data automatically before and after tests
D. To replace the need for assertions in tests
Solution
Step 1: Understand what fixtures do
Fixtures in pytest are used to set up and tear down resources needed for tests, such as database data.
Step 2: Identify the role of database fixtures
Database fixtures specifically prepare test data before tests run and clean it up after tests finish, ensuring tests run reliably.
Final Answer:
To prepare and clean test data automatically before and after tests -> Option C
Quick Check:
Database fixtures = setup and cleanup [OK]
Hint: Fixtures handle setup and cleanup automatically [OK]
Common Mistakes:
Thinking fixtures run SQL queries inside tests
Believing fixtures speed up the database server
Confusing fixtures with assertions
2. Which of the following is the correct way to write a pytest fixture that sets up a database connection and tears it down after the test using yield?
easy
A. def db():
conn = connect()
yield conn
conn.close()
B. def db():
conn = connect()
conn.close()
yield conn
C. def db():
yield connect()
conn.close()
D. def db():
conn = connect()
return conn
conn.close()
Solution
Step 1: Understand yield usage in fixtures
Using yield in a fixture splits setup (before yield) and teardown (after yield).
Step 2: Check each option's order
def db():
conn = connect()
yield conn
conn.close() sets up connection, yields it, then closes connection after test. Others close before yield or have unreachable code.
A. The cleanup code after return is never executed
B. The fixture should use yield instead of return for cleanup
C. The table creation SQL is incorrect
D. The fixture is missing the @pytest.mark decorator
Solution
Step 1: Check the fixture structure
Code after return statement is unreachable and will never run.
Step 2: Understand cleanup execution
Cleanup code must run after test, so it should be placed after yield or before return, but not after return.
Final Answer:
The cleanup code after return is never executed -> Option A
Quick Check:
Code after return is unreachable [OK]
Hint: Code after return in fixture won't run [OK]
Common Mistakes:
Thinking return allows cleanup after it
Confusing yield and return usage
Ignoring unreachable code warnings
5. You want to create a pytest fixture that sets up a test database with multiple tables and ensures all tables are dropped after tests, even if a test fails. Which pattern best achieves this?
hard
A. Create tables once globally without cleanup to speed up tests
B. Create tables inside each test and drop them at the end of each test
C. Use return in fixture to return connection, then drop tables in a separate teardown function
D. Use a fixture with yield: create tables before yield, drop tables after yield
Solution
Step 1: Understand reliable setup and teardown
Using yield in fixtures allows setup before tests and guaranteed cleanup after, even if tests fail.
Step 2: Evaluate options for cleanup guarantee
Use a fixture with yield: create tables before yield, drop tables after yield uses yield to create tables before tests and drop them after, ensuring cleanup always runs.
Final Answer:
Use a fixture with yield: create tables before yield, drop tables after yield -> Option D
Quick Check:
Yield fixture ensures setup and guaranteed teardown [OK]
Hint: Yield fixtures guarantee cleanup after tests [OK]
Common Mistakes:
Skipping cleanup causing leftover tables
Relying on test code for cleanup
Avoiding yield and missing teardown
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.