Challenge - 5 Problems
Database Testing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this FastAPI test with a test database?
Consider this FastAPI test code snippet using a test database session. What will be the value of
response.status_code after running this test?FastAPI
from fastapi.testclient import TestClient from main import app, get_db from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database import Base SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}) TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base.metadata.create_all(bind=engine) def override_get_db(): try: db = TestingSessionLocal() yield db finally: db.close() app.dependency_overrides[get_db] = override_get_db client = TestClient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200
Attempts:
2 left
💡 Hint
Think about what the test client does and how the test database is set up.
✗ Incorrect
The test overrides the database dependency with a test session connected to a SQLite test database. The endpoint '/' exists and returns status 200, so the test client receives 200.
🔧 Debug
intermediate2:00remaining
Why does this FastAPI test with database raise an IntegrityError?
Given this test code snippet, why does the test raise an IntegrityError when trying to add a user twice?
FastAPI
def test_create_duplicate_user(): db = TestingSessionLocal() user_data = {"username": "testuser", "email": "test@example.com"} user = User(**user_data) db.add(user) db.commit() duplicate_user = User(**user_data) db.add(duplicate_user) db.commit() # Raises IntegrityError here
Attempts:
2 left
💡 Hint
Think about database constraints on unique fields.
✗ Incorrect
The IntegrityError occurs because the database enforces uniqueness on username or email fields. Adding a duplicate user violates this constraint.
📝 Syntax
advanced2:00remaining
Which option correctly overrides the FastAPI database dependency for testing?
You want to override the
get_db dependency in FastAPI to use a test database session. Which option correctly implements this override?Attempts:
2 left
💡 Hint
Remember how to properly yield a resource and ensure cleanup in Python generators.
✗ Incorrect
Option B correctly uses a generator with try-finally to yield the session and ensure it closes after use. Option B closes after yield which is unreachable. Option B uses a context manager which auto-commits the session upon exiting the 'with' block after the yield, interfering with manual transaction control typical in FastAPI endpoints. Option B returns a session but does not yield, breaking FastAPI dependency pattern.
❓ state_output
advanced2:00remaining
What is the number of users in the test database after this test runs?
Given this test code that adds users to the test database, how many users will be in the database after the test completes?
FastAPI
def test_add_users(): db = TestingSessionLocal() user1 = User(username="user1", email="user1@example.com") user2 = User(username="user2", email="user2@example.com") db.add(user1) db.commit() db.add(user2) db.rollback() users = db.query(User).all() return len(users) result = test_add_users()
Attempts:
2 left
💡 Hint
Think about what commit and rollback do to the database session.
✗ Incorrect
The first user is added and committed, so it is saved. The second user is added but then the session is rolled back, so the second user is not saved. Query returns 1 user.
🧠 Conceptual
expert2:00remaining
Why is using a separate test database important in FastAPI testing?
Which reason best explains why you should use a separate test database when running FastAPI tests that involve database operations?
Attempts:
2 left
💡 Hint
Think about safety and data integrity when running automated tests.
✗ Incorrect
Using a separate test database ensures tests do not affect real production data, keeping data safe and tests isolated.