Skip to content

Testing

Flask 内置测试客户端,便于对路由/业务逻辑进行单元测试与集成测试。

依赖:

bash
pip install pytest pytest-cov

Pytest 基础结构:

project/
  app/
  tests/
    conftest.py
    test_app.py

测试夹具:

python
# tests/conftest.py
import pytest
from app import create_app

desired_config = {"TESTING": True}

@pytest.fixture()
def app():
    app = create_app()
    app.config.update(desired_config)
    yield app

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

示例用例:

python
# tests/test_app.py
def test_index(client):
    res = client.get("/")
    assert res.status_code == 200
    assert b"Hello" in res.data

覆盖率:pytest --cov=app --cov-report=term-missing