0
0
PyTesttesting~5 mins

Database rollback fixtures in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of a database rollback fixture in pytest?
A database rollback fixture ensures that any changes made to the database during a test are undone after the test finishes. This keeps the database clean and consistent for other tests.
Click to reveal answer
beginner
How does a rollback fixture help maintain test isolation?
By rolling back database changes after each test, the fixture prevents one test's data from affecting another test, ensuring tests run independently and reliably.
Click to reveal answer
intermediate
Which pytest fixture scope is commonly used for database rollback fixtures and why?
The 'function' scope is commonly used because it rolls back changes after each test function, ensuring a fresh database state for every test.
Click to reveal answer
intermediate
Example snippet: How do you start a transaction and rollback after a test using pytest fixtures?
Use a fixture that begins a transaction before the test and rolls it back after. For example:<br>
@pytest.fixture
 def db_rollback(db_session):
     db_session.begin()
     yield db_session
     db_session.rollback()
Click to reveal answer
intermediate
Why is it better to use rollback fixtures instead of manually cleaning the database after tests?
Rollback fixtures are faster and less error-prone because they undo changes automatically within a transaction, avoiding complex cleanup code and reducing test flakiness.
Click to reveal answer
What does a database rollback fixture do in pytest?
ADeletes the entire database
BReverts database changes after each test
CCommits database changes permanently
DCreates a new database for each test
Which pytest fixture scope is best for database rollback to isolate tests?
Amodule
Bsession
Cfunction
Dclass
Why use transactions with rollback in tests?
ATo undo changes automatically after tests
BTo keep database changes permanent
CTo speed up database queries
DTo backup the database
What happens if you don't rollback database changes after tests?
ATests may interfere with each other
BTests run faster
CDatabase stays clean
DDatabase size decreases
In pytest, how do you ensure a rollback happens after a test?
ARestart the database server
BCall commit() after test
CDelete database manually
DUse yield in fixture and rollback after yield
Explain how a database rollback fixture works in pytest and why it is important for test reliability.
Think about how transactions can undo changes automatically.
You got /5 concepts.
    Describe the steps to create a pytest fixture that rolls back database changes after each test function.
    Use yield in the fixture to separate setup and teardown.
    You got /4 concepts.