Testing
Flask ships with a test client, so you can unit-test and integration-test routes and business logic without starting a real HTTP server. It pairs best with pytest.
Installing Dependencies
Project Structure
Fixtures (conftest.py)
This is where the application-factory pattern pays off in testing — create an independently configured app instance for tests:
Testing Routes
client.get/post/put/delete accept json= (auto-serialized with the right Content-Type), data= (form data), headers=, query_string=, and more.
Testing Logged-In State
session_transaction() lets you read/write the session outside a request:
Testing Code That Needs an App Context
Code outside views (model methods, utilities) that touches current_app or the database needs a context pushed manually:
Running Tests and Coverage
Practical Advice
- Keep tests independent: in-memory database plus create/drop in fixtures prevents cross-test pollution.
- Test behavior (status codes, response content, database side effects), not internal implementation details.
- Stub external services (email, third-party APIs) with
unittest.mockor theresponseslibrary.