📖 Scenario: You are building a simple Flask app that stores user names in a database. You want to write tests to check that your app correctly adds and retrieves users from the database.
🎯 Goal: Create a Flask app with a database setup, configure a test database, write a test to add a user, and complete the test setup to run the test.
📋 What You'll Learn
Create a Flask app with SQLAlchemy database
Configure a test database URI
Write a test function to add a user to the test database
Complete the test setup with assertions and cleanup
💡 Why This Matters
🌍 Real World
Testing database operations is essential in web apps to ensure data is saved and retrieved correctly without affecting real data.
💼 Career
Many developer jobs require writing tests for database interactions to maintain app quality and prevent bugs.
Progress0 / 4 steps
1
Create Flask app and database model
Create a Flask app called app and set up SQLAlchemy with db. Define a User model with an id column as primary key and a username column as string.
Flask
Hint
Use Flask(__name__) to create the app and SQLAlchemy(app) for the database. Define User as a class inheriting from db.Model.
2
Configure test database URI
Add a configuration variable app.config['TEST_DATABASE_URI'] and set it to 'sqlite:///:memory:' for an in-memory test database.
Flask
Hint
Set app.config['TEST_DATABASE_URI'] to use SQLite in-memory database for fast tests.
3
Write test function to add a user
Write a test function called test_add_user() that sets the config to the test database URI using app.config['SQLALCHEMY_DATABASE_URI'] = app.config['TEST_DATABASE_URI'], uses with app.app_context():, creates the test database with db.create_all(), adds a User with username='testuser', commits the session, and queries the user back with User.query.filter_by(username='testuser').first().
Flask
Hint
Inside test_add_user(), set the database URI to the test URI, use with app.app_context():, create tables, add a user, commit, and query the user.
4
Complete the test with assertions and cleanup
Add the final lines to test_add_user() to assert that queried_user is not None and that queried_user.username equals 'testuser'. Also, add db.drop_all() at the end to clean up.
Flask
Hint
Use assert statements to check the user was added and then call db.drop_all() to remove tables after the test.
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
Step 1: Understand test database role
A test database is used to keep test data separate from real data to avoid unwanted changes.
Step 2: Identify isolation benefit
This isolation ensures tests do not affect the real app data or state.
Final Answer:
To isolate tests so they don't affect the real data -> Option B
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
Step 1: Recall Flask test lifecycle methods
In Flask testing, setUp runs before each test to prepare the environment.
Step 2: Match method to database preparation
Preparing the test database (like creating tables) happens in setUp.
Final Answer:
setUp -> Option C
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?