Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a pytest fixture that sets up a database connection.
PyTest
import pytest @pytest.fixture def db_connection(): conn = create_connection() # Setup connection yield conn conn.[1]() # Teardown connection
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'commit' instead of 'close' for teardown.
Forgetting to close the connection causing resource leaks.
✗ Incorrect
The fixture should close the database connection after the test finishes to free resources.
2fill in blank
mediumComplete the code to use the database fixture in a test function.
PyTest
def test_user_count([1]): count = db_connection.execute('SELECT COUNT(*) FROM users').fetchone()[0] assert count >= 0
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the fixture name.
Not including the fixture as a parameter.
✗ Incorrect
The test function parameter must match the fixture name to use it.
3fill in blank
hardFix the error in the fixture to ensure the database transaction rolls back after each test.
PyTest
import pytest @pytest.fixture def db_session(): session = create_session() yield session session.[1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using commit instead of rollback causing test data to persist.
Not rolling back causing side effects between tests.
✗ Incorrect
Rolling back the session after each test ensures no changes persist in the database.
4fill in blank
hardFill both blanks to create a fixture that sets up a test database and tears it down after tests.
PyTest
import pytest @pytest.fixture(scope='module') def test_db(): db = setup_test_db() yield db db.[1]() [2]_test_db()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using create_all instead of drop_all for teardown.
Not cleaning up test database resources.
✗ Incorrect
After tests, the fixture drops all tables and cleans up the test database.
5fill in blank
hardFill all three blanks to create a fixture that starts a transaction, yields a session, and rolls back after the test.
PyTest
import pytest @pytest.fixture def transactional_session(): connection = engine.connect() transaction = connection.[1]() session = Session(bind=connection) yield session session.[2]() transaction.[3]() connection.close()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Committing before rollback causing test data to persist.
Not closing the connection after tests.
✗ Incorrect
The fixture begins a transaction, yields the session, rolls back session changes, rolls back the transaction, and closes connection.