Unit testing: pytest writes high-coverage Flask tests
📂 Stage: Stage 5 - Advanced Advancement (Performance and Architecture) 🔗 Related chapters: Flask-Login 实战 · environment-setup
Every time I change the code, I dare not go online. Are I always worried that I have missed a route, form verification, or permissions are not configured properly? Stop using "handmade dots" to embolden yourself.
pytest + Flask is a golden combination to help you automatically verify business logic - it can not only simulate real requests, but also isolate the database. This tutorial will help you build a test suite from scratch that covers views, login authentication, and database operations, giving you more confidence when submitting code.
1. Zero threshold startup: installation and configuration of pytest
1.1 One line of commands to install necessary dependencies
Except for the corepytest, recommended to installpytest-flask, it can help you automatically handle the Flask application context and avoid manual tossing in tests.app_context():
1.2 Add project root directorypytest.ini
With this configuration file, you don't need to add a bunch of parameters after the command line every time. build onepytest.ini, paste the following content in:
Then knock directlypytestwill automatically entertests/Directory, identificationtest_*.pyfiles, saving a lot of repetitive work.
2. No more repetitive code: pytest Fixtures in practice
If every time you write a test function, you have to manually create an application, create a table, register a user, and log in, the test code will soon become a hell of "eight-part essay".
conftest.pyIt is the global scaffolding file provided by pytest. We put the reusable pre/post logic here, usingfixtureEncapsulate it. Each test function can automatically obtain a clean environment by declaring which fixture is required.
Tips:
yieldThe previous code is run before the test function is executed, and the subsequent code is run after the test is completed. This is the common paradigm to implement "create tables before testing and clear them after testing".
3. Basic view test: from home page to login and registration
Let's start with the simplest, stateless public pages - homepage, login page, registration page. This type of testing is less error-prone and can help you quickly build confidence in the testing framework.
Regardless of whether it is a "success path" or a "failure path", each test only focuses on one scenario. In this way, when the use case fails, you can immediately know which specific logic has the problem.
4. Advanced test: verify login protection and permissions
Using Flask-Login@login_requiredFinally we have to confirm:
- Not logged in users will be redirected to the login page.
- Logged in users can access and perform operations normally.
Here'sauthenticated_clientfrom us atconftest.pyThe fixtures defined in , completely eliminate the trouble of repeated login.
5. Give your code a "physical examination": test coverage
After writing a bunch of tests, how much business code is covered? usepytest-covIntuitive visual reports can be generated to see at a glance which lines of code have never been executed.
5.1 Installation and operation
5.2 Small coverage goals
Don’t be held hostage by “100% coverage.” It is recommended that core processes (login, registration, protected operations) reach 80% or more, and tool functions and simple logic can pursue 100%. Prioritize ensuring that those scenarios with “more bad news than good news” are covered by tests.
6. Checklist & Best Practices
📝 Commonly used pytest + Flask test syntax quick check
💡 Best Practice Tips
- Test naming should be done in human language: Just look at the function name to know whether it is testing "success", "failure" or "boundary case".
- A use case only tests one thing: Don’t put registration, login, and article posting into the same
test_*inside. - Only use the database in a test environment: Never touch the development or production database, be sure to use independent configurations and instances.
- Try TDD (Test Driven Development): First write a failing test, then write code to make it green, and finally refactor.
🔗 Extended reading

