Testing with a database helps ensure your app works well with stored data. It checks if saving, reading, and updating data behaves as expected.
Testing with database in Flask
import unittest from yourapp import create_app, db class TestDatabase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client() def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop()
Use setUp to prepare a fresh test database before each test.
Use tearDown to clean up after each test to avoid leftover data.
def test_add_user(self): user = User(username='testuser') db.session.add(user) db.session.commit() self.assertEqual(User.query.count(), 1)
def test_query_user(self): user = User(username='alice') db.session.add(user) db.session.commit() found = User.query.filter_by(username='alice').first() self.assertIsNotNone(found)
This example creates a simple Flask app with an in-memory database. It tests adding a user and then querying that user to confirm it was saved correctly.
import unittest from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['TESTING'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) class TestDatabase(unittest.TestCase): def setUp(self): self.app = app self.app_context = self.app.app_context() self.app_context.push() db.create_all() def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_add_and_query_user(self): user = User(username='tester') db.session.add(user) db.session.commit() found = User.query.filter_by(username='tester').first() self.assertIsNotNone(found) self.assertEqual(found.username, 'tester') if __name__ == '__main__': unittest.main()
Use an in-memory SQLite database for fast, isolated tests.
Always clean up the database after each test to avoid interference.
Use Flask's app.app_context() to access app resources during tests.
Testing with a database ensures your app handles data correctly.
Use setUp and tearDown to prepare and clean the test database.
Use simple queries to check if data is saved and retrieved as expected.
Practice
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 BQuick Check:
Test database isolates data = C [OK]
- Thinking test DB speeds up production
- Confusing test DB with session storage
- Assuming test DB replaces main DB in deployment
Solution
Step 1: Recall Flask test lifecycle methods
In Flask testing,setUpruns before each test to prepare the environment.Step 2: Match method to database preparation
Preparing the test database (like creating tables) happens insetUp.Final Answer:
setUp -> Option CQuick Check:
Prepare DB before test = setUp [OK]
- Confusing tearDown with setup
- Using runTest which is not for setup
- Assuming initTest is a Flask method
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))Solution
Step 1: Analyze user addition and commit
The code adds one user and commits to the test database.Step 2: Query all users after commit
Querying all users returns a list with the one added user.Final Answer:
1 -> Option AQuick Check:
One user added and committed = 1 [OK]
- Forgetting to commit before query
- Assuming previous tests add users
- Thinking session is not initialized
def tearDown(self):
db.session.remove()
db.drop_all()Solution
Step 1: Understand tearDown purpose
tearDown cleans up after tests by removing session and dropping tables.Step 2: Identify missing rollback before drop_all()
Without rollback, pending changes may not be discarded, potentially causing errors or inconsistent state.Final Answer:
No call to rollback() before drop_all() -> Option DQuick Check:
Rollback before drop_all to discard changes [OK]
- Thinking create_all belongs in tearDown
- Believing session removal is wrong in tearDown
- Ignoring rollback before drop_all
Solution
Step 1: Understand test setup and cleanup
Creating tables before each test ensures a fresh database state.Step 2: Understand test teardown
Dropping tables after each test cleans up to avoid data carryover.Step 3: Match correct sequence
Callingcreate_all()in setUp anddrop_all()in tearDown is the correct pattern.Final Answer:
Call db.create_all() in setUp, run test, then db.drop_all() in tearDown -> Option AQuick Check:
Create tables before, drop after test = A [OK]
- Dropping tables before test instead of after
- Calling create_all and drop_all both in setUp
- Confusing commit with setup/teardown
Ready to prove it?
Pass the test and this pattern moves unknown
