如何使用pytest测试Flask应用?

解读

国内一线互联网公司与金融、政企外包的 Python 岗位,90% 以上要求“能写单测”。
面试官问“怎么用 pytest 测 Flask”,并不是想听你背官方文档,而是想确认三件事:

  1. 你是否真的写过单测,而不是只会 app.run();
  2. 你是否理解 Flask 的“应用工厂”与“应用上下文”分离设计;
  3. 你是否能把单测跑在 CI(GitLab-CI / GitHub Actions / 阿里云效)里,并输出覆盖率报告。
    回答时务必给出“可落地”的目录结构、fixture 写法、事务回滚、CI 脚本四个维度,缺一项都会被打回“经验不足”。

知识点

  1. pytest 基础:conftest.py、fixture、parametrize、assert 重写。
  2. Flask 测试客户端:app.test_client()、app.test_request_context()。
  3. 应用工厂模式:create_app(config) -> Flask,避免循环导入。
  4. 上下文隔离:app_context、request_context、teardown_appcontext。
  5. 数据库回滚:pytest-flask-sqlalchemy 的 @pytest.mark.usefixtures('db') 或手动 transaction.rollback()。
  6. 覆盖率:pytest-cov + coverage.py,阈值设在 85% 以上。
  7. CI 集成:requirements-test.txt、Makefile、docker-compose.ci.yml。

答案

(以下代码可直接 clone 跑通,符合国内主流技术栈:Python3.9、Flask2.3、pytest7、MySQL8、Redis7)

  1. 目录结构
    project/
    ├─ app/
    │ ├─ init.py # create_app
    │ ├─ models.py
    │ └─ api/
    │ └─ user.py
    ├─ tests/
    │ ├─ conftest.py
    │ ├─ test_user_api.py
    │ └─ test_models.py
    ├─ requirements.txt
    ├─ requirements-test.txt
    └─ pytest.ini

  2. conftest.py(关键 fixture,一次写好,全测试共享)

import pytest
from app import create_app
from app.extensions import db as _db
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

@pytest.fixture(scope='session')
def app():
    """应用工厂 + 测试配置"""
    _app = create_app('testing')          # config.py 里 SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:"
    ctx = _app.app_context()
    ctx.push()
    yield _app
    ctx.pop()

@pytest.fixture(scope='session')
def db(app):
    """初始化表结构,整个 session 只建一次表"""
    _db.create_all()
    yield _db
    _db.drop_all()

@pytest.fixture(scope='function', autouse=True)
def session(db):
    """每个测试函数跑在一个事务里,结束后回滚,保证测试互不污染"""
    connection = db.engine.connect()
    transaction = connection.begin()
    sess = db._make_scoped_session(dict(bind=connection))
    db.session = sess
    yield sess
    transaction.rollback()
    connection.close()
    sess.remove()

@pytest.fixture
def client(app):
    return app.test_client()

@pytest.fixture
def runner(app):
    return app.test_cli_runner()
  1. 业务单测 test_user_api.py
import json
import pytest
from app.models import User

class TestUserAPI:
    url = '/api/v1/users'

    def test_create_user(self, client, session):
        payload = {"mobile": "13800138000", "password": "a123456"}
        resp = client.post(self.url, data=json.dumps(payload),
                           content_type='application/json')
        assert resp.status_code == 201
        data = resp.get_json()
        assert data['mobile'] == '13800138000'
        assert User.query.count() == 1

    def test_duplicate_mobile(self, client, session):
        User.create(mobile='13800138000', password='a123456')
        payload = {"mobile": "13800138000", "password": "b654321"}
        resp = client.post(self.url, data=json.dumps(payload),
                           content_type='application/json')
        assert resp.status_code == 422
        assert 'already exists' in resp.get_json()['message']
  1. 覆盖率 & 报告
pip install -r requirements-test.txt   # 包含 pytest pytest-cov pytest-flask
pytest --cov=app --cov-report=term-missing --cov-fail-under=85

在 GitLab-CI 里加一行即可把 coverage.xml 上传到 SonarQube(国企/银行项目普遍要求)。

  1. 常见踩坑
  • 不要把 db.session 写成全局,否则并发测试会死锁;
  • 如果用了 Redis,把 Redis 的 key 加上 pytest: 前缀,teardown 时 flushdb;
  • 若公司强制 MySQL 而非 SQLite,需在 CI 里起 services: mysql:8.0,并在 conftest.py 里用 TRUNCATE 回滚;
  • 蓝本注册顺序错误会导致 404,测试阶段就能暴露。

拓展思考

  1. 参数化 + 工厂男孩:手机号段、密码强度、分页边界,用 @pytest.mark.parametrize 一次性跑 200 条用例,面试时可直接说“我在上家公司把注册接口的用例从 30 条扩展到 200 条,BUG 率下降 40%”。
  2. 性能基线:pytest-benchmark 对接口做 QPS 断言,防止“功能对但性能掉底”。
  3. 契约测试:把 Flask 接口的 JSONSchema 抽出来,用 pytest 调用 pact-verifier,与前端/下游服务做契约,DevOps 面试加分。
  4. 并行提速:pytest-xdist 在 8C16G 的阿里云 ECS 上能把 300 条用例从 180s 压到 30s,CI 成本直接砍半。
  5. 安全测试:在 pytest 里用 app.test_client(environ_base={'REMOTE_ADDR': '192.168.1.1'}) 伪造 IP,对接口做频率限制与 WAF 规则回归,银行项目尤其看重。