This example shows a fake database session with a rollback fixture. The first test adds data, which is rolled back after the test. The second test confirms the data is empty, showing rollback worked.
C. Rollback is called before yield, so changes are undone before test runs
D. Rollback_db should be called twice for safety
Solution
Step 1: Check order of setup, yield, and rollback
Rollback must happen after yield to undo changes after test runs.
Step 2: Identify error in fixture code
Rollback is called before yield, so changes are undone before test, not after.
Final Answer:
Rollback is called before yield, so changes are undone before test runs -> Option C
Quick Check:
Rollback after yield for cleanup [OK]
Hint: Rollback must be after yield to undo test changes [OK]
Common Mistakes:
Calling rollback before yield
Forgetting yield entirely
Calling setup after yield
5. You want to write a pytest fixture that starts a database transaction before each test and rolls it back after, ensuring tests run fast and isolated. Which fixture code correctly achieves this behavior?
hard
A. @pytest.fixture
def db_transaction():
yield
start_transaction()
rollback_transaction()
B. @pytest.fixture
def db_transaction():
start_transaction()
yield
rollback_transaction()
C. @pytest.fixture
def db_transaction():
start_transaction()
rollback_transaction()
yield
D. @pytest.fixture
def db_transaction():
rollback_transaction()
start_transaction()
yield
Solution
Step 1: Understand transaction lifecycle in fixtures
Start transaction before yield to begin test with transaction active.
Step 2: Rollback after yield to undo changes after test
Rollback must happen after yield to clean up changes made during test.
Final Answer:
@pytest.fixture\ndef db_transaction():\n start_transaction()\n yield\n rollback_transaction() -> Option B
Quick Check:
Start before yield, rollback after yield [OK]
Hint: Start transaction before yield, rollback after yield [OK]
Common Mistakes:
Calling rollback before yield
Calling start_transaction after yield
Not using yield to separate setup and cleanup
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.