0
0
Flaskframework~8 mins

Testing with database in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Testing with database
MEDIUM IMPACT
This concept affects page load speed and interaction responsiveness by how database queries during tests impact server response time.
Running tests that involve database operations
Flask
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
Uses an isolated in-memory test database and flushes instead of committing to avoid slow disk writes.
📈 Performance GainReduces test runtime by avoiding disk I/O; faster test feedback loop.
Running tests that involve database operations
Flask
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
This test commits to the real database, causing slow tests and possible data pollution.
📉 Performance CostBlocks test execution for multiple milliseconds per commit; slows overall test suite.
Performance Comparison
PatternDB OperationsTest RuntimeServer Response DelayVerdict
Real DB commit in testsFull commit to diskHigh (slow)High delay[X] Bad
In-memory DB with flushNo commit, flush onlyLow (fast)Minimal delay[OK] Good
Rendering Pipeline
Database testing affects server response time which impacts how fast the browser receives data to render. Slow DB tests delay server responses, increasing interaction latency.
Server Processing
Network Transfer
Rendering
⚠️ BottleneckServer Processing due to blocking database commits
Core Web Vital Affected
INP
This concept affects page load speed and interaction responsiveness by how database queries during tests impact server response time.
Optimization Tips
1Avoid committing to the real database during tests to reduce blocking disk writes.
2Use in-memory or mock databases to speed up test execution.
3Flush session changes instead of committing when possible to minimize delays.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is committing to the real database during tests a performance problem?
AIt improves test accuracy and speed.
BIt causes slow disk writes and blocks test execution.
CIt reduces server response time.
DIt has no impact on performance.
DevTools: Network
How to check: Run tests and observe server response times in the Network panel; look for long waiting (TTFB) times.
What to look for: High Time To First Byte (TTFB) indicates slow server response likely due to DB operations.