Bird
Raised Fist0
FastAPIframework~20 mins

Testing with database in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Database Testing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2: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
A200
B404
C500
D422
Attempts:
2 left
💡 Hint
Think about what the test client does and how the test database is set up.
🔧 Debug
intermediate
2: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
ABecause the test database is not created before running the test
BBecause the database session was not closed before adding the duplicate user
CBecause the User model is missing a primary key definition
DBecause the username or email must be unique and adding duplicate violates this constraint
Attempts:
2 left
💡 Hint
Think about database constraints on unique fields.
📝 Syntax
advanced
2: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?
A
def override_get_db():
    db = TestingSessionLocal()
    yield db
    db.close()
B
def override_get_db():
    db = TestingSessionLocal()
    try:
        yield db
    finally:
        db.close()
C
def override_get_db():
    with TestingSessionLocal() as db:
        yield db
D
def override_get_db():
    db = TestingSessionLocal()
    return db
Attempts:
2 left
💡 Hint
Remember how to properly yield a resource and ensure cleanup in Python generators.
❓ state_output
advanced
2: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()
A2
B0
C1
DRaises an error
Attempts:
2 left
💡 Hint
Think about what commit and rollback do to the database session.
🧠 Conceptual
expert
2: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?
ATo isolate test data and avoid corrupting or modifying production data during tests
BBecause FastAPI requires a different database type for testing
CTo speed up tests by using an in-memory database only supported in tests
DBecause the test database automatically fixes schema errors during tests
Attempts:
2 left
💡 Hint
Think about safety and data integrity when running automated tests.

Practice

(1/5)
1. Why should you use a separate test database when testing FastAPI applications that interact with a database?
easy
A. To skip database setup during tests
B. To make tests run slower and more realistic
C. To avoid changing real data and keep tests isolated
D. To share data between tests and production

Solution

  1. Step 1: Understand test isolation

    Tests should not affect real data to avoid accidental data loss or corruption.
  2. Step 2: Use separate test database

    Using a separate database keeps test data separate and allows safe repeated testing.
  3. Final Answer:

    To avoid changing real data and keep tests isolated -> Option C
  4. Quick Check:

    Separate test database = safe isolated tests [OK]
Hint: Always isolate test data from real data [OK]
Common Mistakes:
  • Using production database for tests
  • Not cleaning test data after tests
  • Assuming tests don't affect real data
2. Which of the following is the correct way to override the database dependency in FastAPI tests?
easy
A. app.replace_dependency(get_db, override_get_db)
B. app.override_dependency(get_db, override_get_db)
C. app.set_dependency(get_db, override_get_db)
D. app.dependency_overrides[get_db] = override_get_db

Solution

  1. Step 1: Recall FastAPI dependency override syntax

    FastAPI uses the dictionary app.dependency_overrides to replace dependencies during tests.
  2. Step 2: Match correct syntax

    Assigning override_get_db function to app.dependency_overrides[get_db] is the correct method.
  3. Final Answer:

    app.dependency_overrides[get_db] = override_get_db -> Option D
  4. Quick Check:

    Override dependencies via app.dependency_overrides dict [OK]
Hint: Use app.dependency_overrides dictionary to override [OK]
Common Mistakes:
  • Using non-existent methods like set_dependency
  • Trying to override dependencies without assignment
  • Confusing syntax with other frameworks
3. Given this test code snippet, what will be the output of response.json()?
def test_create_item(client):
    response = client.post('/items/', json={'name': 'Book', 'price': 10})
    return response.json()
medium
A. {'id': 1, 'name': 'Book', 'price': 10}
B. {'name': 'Book', 'price': 10}
C. An error because POST is not allowed
D. Empty response {}

Solution

  1. Step 1: Understand POST /items/ behavior

    Assuming the endpoint creates an item and returns it with an assigned id.
  2. Step 2: Analyze response.json()

    The response should include the new item's id plus the sent data.
  3. Final Answer:

    {'id': 1, 'name': 'Book', 'price': 10} -> Option A
  4. Quick Check:

    POST creates item and returns it with id [OK]
Hint: POST usually returns created object with id [OK]
Common Mistakes:
  • Expecting only sent data without id
  • Assuming POST is disallowed
  • Ignoring response content
4. What is the main issue with this test code snippet?
def override_get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

app.dependency_overrides[get_db] = override_get_db

def test_read_items(client):
    response = client.get('/items/')
    assert response.status_code == 200
    assert response.json() == []
medium
A. The dependency override is missing
B. The test database session is not properly created or isolated
C. The test client is not defined
D. The test expects wrong status code

Solution

  1. Step 1: Check override_get_db function

    It uses SessionLocal but does not ensure a separate test database or transaction rollback.
  2. Step 2: Identify test isolation problem

    Without a test database or rollback, tests may affect real data or each other.
  3. Final Answer:

    The test database session is not properly created or isolated -> Option B
  4. Quick Check:

    Test DB session must be isolated and separate [OK]
Hint: Ensure test DB session is isolated and rolled back [OK]
Common Mistakes:
  • Not using a test database
  • Not overriding dependencies correctly
  • Assuming client is auto-defined
5. You want to write a test that creates an item, then reads it back from the test database in FastAPI. Which approach correctly ensures the test uses a separate database and cleans up after itself?
hard
A. Use a test database URL, override get_db to yield a session from it, and rollback after each test
B. Use the production database URL and delete created items manually after test
C. Use an in-memory list to mock database and skip actual DB calls
D. Run tests without overriding get_db and rely on default DB

Solution

  1. Step 1: Use separate test database URL

    This prevents tests from affecting production data.
  2. Step 2: Override get_db to yield test session and rollback

    This ensures each test runs isolated and cleans up changes automatically.
  3. Final Answer:

    Use a test database URL, override get_db to yield a session from it, and rollback after each test -> Option A
  4. Quick Check:

    Separate DB + override + rollback = clean isolated tests [OK]
Hint: Always isolate tests with separate DB and rollback [OK]
Common Mistakes:
  • Using production DB for tests
  • Not cleaning test data after tests
  • Skipping dependency overrides
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard