Bird
Raised Fist0
Flaskframework~10 mins

Testing with database in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Testing with database
Setup Test Database
↓
Create Test Client
↓
Run Test Function
↓
Insert Test Data
↓
Perform Test Actions
↓
Check Results
↓
Teardown Test Database
↓
END
This flow shows how Flask tests use a separate test database, run test code, check results, then clean up.
Execution Sample
Flask
def test_add_user(client, db):
    user = User(name='Alice')
    db.session.add(user)
    db.session.commit()
    assert User.query.count() == 1
This test adds a user to the test database and checks if the user count is 1.
Execution Table
StepActionDatabase StateResult
1Start test, test DB emptyUsers: 0Ready to add user
2Create User(name='Alice')Users: 0User object created, not saved
3Add user to sessionUsers: 0User staged for commit
4Commit sessionUsers: 1 (Alice)User saved in DB
5Query User countUsers: 1 (Alice)Count is 1, test passes
6Teardown test DBUsers: 0Test DB cleaned
💡 Test ends after verifying user count is 1 and cleaning test database
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
userNoneUser(name='Alice')User(name='Alice')User(name='Alice')User(name='Alice')
db.sessionEmptyEmptyHas user stagedCommittedEmpty after teardown
User.query.count()00010 after teardown
Key Moments - 3 Insights
Why does the user count stay 0 before committing?
Because adding to the session only stages changes; the commit actually saves to the database (see step 3 vs step 4 in execution_table).
Why do we use a separate test database?
To avoid changing real data and to allow tests to run safely and independently (see step 1 and step 6 in execution_table).
What happens if we forget to commit?
The user won't be saved, so the count stays 0 and the test fails (compare step 3 and step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the user count after step 3?
AUser object not created yet
B1
C0
DTest database is empty
💡 Hint
Check the 'Database State' column at step 3 in execution_table
At which step does the user get saved to the database?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look for the commit action in execution_table
If we skip the teardown step, what happens to the test database?
AIt stays with test data, possibly affecting other tests
BIt deletes all data automatically
CIt resets user count to 0
DNothing changes because tests are isolated
💡 Hint
See the purpose of step 6 in execution_table and key_moments about test DB cleanup
Concept Snapshot
Testing with database in Flask:
- Use a separate test database
- Create test client and setup DB
- Add and commit test data
- Query and assert results
- Teardown DB to clean
This ensures tests don't affect real data.
Full Transcript
In Flask testing with a database, we first set up a separate test database to keep tests isolated from real data. Then, we create a test client and run test functions. Inside a test, we create objects like a User, add them to the database session, and commit to save them. We then query the database to check if the data is saved correctly. After tests run, we teardown the test database to clean up. This process ensures tests are safe and repeatable without affecting real application data.

Practice

(1/5)
1. What is the main purpose of using a test database in Flask testing?
easy
A. To store user sessions permanently
B. To isolate tests so they don't affect the real data
C. To speed up the app in production
D. To replace the main database in deployment

Solution

  1. Step 1: Understand test database role

    A test database is used to keep test data separate from real data to avoid unwanted changes.
  2. Step 2: Identify isolation benefit

    This isolation ensures tests do not affect the real app data or state.
  3. Final Answer:

    To isolate tests so they don't affect the real data -> Option B
  4. Quick Check:

    Test database isolates data = C [OK]
Hint: Test DB keeps test data separate from real data [OK]
Common Mistakes:
  • Thinking test DB speeds up production
  • Confusing test DB with session storage
  • Assuming test DB replaces main DB in deployment
2. Which Flask testing method is used to prepare the test database before each test runs?
easy
A. tearDown
B. initTest
C. setUp
D. runTest

Solution

  1. Step 1: Recall Flask test lifecycle methods

    In Flask testing, setUp runs before each test to prepare the environment.
  2. Step 2: Match method to database preparation

    Preparing the test database (like creating tables) happens in setUp.
  3. Final Answer:

    setUp -> Option C
  4. Quick Check:

    Prepare DB before test = setUp [OK]
Hint: Use setUp to prepare before each test [OK]
Common Mistakes:
  • Confusing tearDown with setup
  • Using runTest which is not for setup
  • Assuming initTest is a Flask method
3. Given this test code snippet, what will print(len(users)) output?
def test_user_creation(self):
    user = User(name='Anna')
    db.session.add(user)
    db.session.commit()
    users = User.query.all()
    print(len(users))
medium
A. 1
B. 0
C. Error: session not initialized
D. Multiple users depending on previous tests

Solution

  1. Step 1: Analyze user addition and commit

    The code adds one user and commits to the test database.
  2. Step 2: Query all users after commit

    Querying all users returns a list with the one added user.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    One user added and committed = 1 [OK]
Hint: Commit before query to see added users [OK]
Common Mistakes:
  • Forgetting to commit before query
  • Assuming previous tests add users
  • Thinking session is not initialized
4. What is wrong with this test code snippet?
def tearDown(self):
    db.session.remove()
    db.drop_all()
medium
A. Missing call to create_all() in tearDown
B. tearDown should not remove session
C. drop_all() should be in setUp, not tearDown
D. No call to rollback() before drop_all()

Solution

  1. Step 1: Understand tearDown purpose

    tearDown cleans up after tests by removing session and dropping tables.
  2. Step 2: Identify missing rollback before drop_all()

    Without rollback, pending changes may not be discarded, potentially causing errors or inconsistent state.
  3. Final Answer:

    No call to rollback() before drop_all() -> Option D
  4. Quick Check:

    Rollback before drop_all to discard changes [OK]
Hint: Always rollback before dropping tables in tearDown [OK]
Common Mistakes:
  • Thinking create_all belongs in tearDown
  • Believing session removal is wrong in tearDown
  • Ignoring rollback before drop_all
5. You want to test a Flask app that uses a database. Which sequence correctly sets up and cleans the test database for each test?
hard
A. Call db.create_all() in setUp, run test, then db.drop_all() in tearDown
B. Call db.drop_all() in setUp, run test, then db.create_all() in tearDown
C. Call db.session.commit() in setUp, then db.session.remove() in tearDown
D. Call db.create_all() and db.drop_all() both in setUp

Solution

  1. Step 1: Understand test setup and cleanup

    Creating tables before each test ensures a fresh database state.
  2. Step 2: Understand test teardown

    Dropping tables after each test cleans up to avoid data carryover.
  3. Step 3: Match correct sequence

    Calling create_all() in setUp and drop_all() in tearDown is the correct pattern.
  4. Final Answer:

    Call db.create_all() in setUp, run test, then db.drop_all() in tearDown -> Option A
  5. Quick Check:

    Create tables before, drop after test = A [OK]
Hint: Create tables before test, drop after test [OK]
Common Mistakes:
  • Dropping tables before test instead of after
  • Calling create_all and drop_all both in setUp
  • Confusing commit with setup/teardown
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