Flask单元测试 #

一、测试概述 #

1.1 安装测试工具 #

bash
pip install pytest pytest-cov

1.2 测试配置 #

python
from app import create_app, db

import pytest

@pytest.fixture
def app():
    app = create_app('testing')
    app.config['TESTING'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
    
    with app.app_context():
        db.create_all()
        yield app
        db.drop_all()

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

二、编写测试 #

2.1 测试视图 #

python
def test_index(client):
    response = client.get('/')
    assert response.status_code == 200
    assert b'Welcome' in response.data

def test_login(client):
    response = client.post('/login', data={
        'username': 'test',
        'password': 'test'
    })
    assert response.status_code == 302

2.2 测试API #

python
import json

def test_api_get_users(client):
    response = client.get('/api/users')
    assert response.status_code == 200
    data = json.loads(response.data)
    assert isinstance(data, list)

def test_api_create_user(client):
    response = client.post('/api/users',
        data=json.dumps({'username': 'test', 'email': 'test@example.com'}),
        content_type='application/json'
    )
    assert response.status_code == 201

三、运行测试 #

bash
pytest
pytest --cov=app

四、下一步 #

接下来让我们学习 测试覆盖率,了解测试覆盖率分析!

最后更新:2026-03-28