Performance: Testing with database
This concept affects page load speed and interaction responsiveness by how database queries during tests impact server response time.
import pytest @pytest.fixture def test_db(): db.create_all() yield db db.drop_all() def test_user_creation(client, test_db): user = User(name='Test') test_db.session.add(user) test_db.session.flush() # no commit response = client.get('/users') assert response.status_code == 200
def test_user_creation(client): user = User(name='Test') db.session.add(user) db.session.commit() response = client.get('/users') assert response.status_code == 200
| Pattern | DB Operations | Test Runtime | Server Response Delay | Verdict |
|---|---|---|---|---|
| Real DB commit in tests | Full commit to disk | High (slow) | High delay | [X] Bad |
| In-memory DB with flush | No commit, flush only | Low (fast) | Minimal delay | [OK] Good |
setUp runs before each test to prepare the environment.setUp.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))def tearDown(self):
db.session.remove()
db.drop_all()create_all() in setUp and drop_all() in tearDown is the correct pattern.Pass the test and this pattern moves unknown