Complete the code to define a pytest fixture that rolls back database changes after each test.
import pytest @pytest.fixture def db_session(): session = create_session() yield session session.[1]()
The rollback() method undoes all changes made during the test, ensuring a clean state for the next test.
Complete the code to use the fixture in a test function that queries the database.
def test_user_count(db_session): count = db_session.query(User).count() assert count [1] 0
The test asserts that the user count is exactly zero, assuming a clean database state after rollback.
Fix the error in the fixture to ensure the session is properly closed after rollback.
@pytest.fixture def db_session(): session = create_session() yield session session.rollback() session.[1]
Calling close() after rollback properly releases database resources.
Fill both blanks to create a fixture that starts a transaction and rolls it back after the test.
@pytest.fixture def transactional_db(): connection = engine.connect() transaction = connection.[1]() session = Session(bind=connection) yield session session.[2]() transaction.rollback() connection.close()
The transaction is started with begin() and the session commits changes before rollback to ensure proper cleanup.
Fill all three blanks to implement a fixture that uses savepoint for nested rollback.
@pytest.fixture def savepoint_db(): connection = engine.connect() transaction = connection.begin() savepoint = connection.[1]() session = Session(bind=connection) yield session session.[2]() savepoint.[3]() transaction.rollback() connection.close()
The savepoint is created with begin_nested(). The session commits changes, then the savepoint rolls back, and finally the transaction rolls back to clean up.