- 安装依赖:
确保
flask
和pytest
已经安装。可以使用pip install flask pytest
来安装。
- 示例Flask应用代码(假设为
app.py
):
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/data', methods=['GET'])
def get_data():
return jsonify({'message': 'Hello, World!'})
if __name__ == '__main__':
app.run(debug=True)
- Pytest测试代码(假设为
test_app.py
):
import pytest
from app import app
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_get_data_status_code(client):
response = client.get('/data')
assert response.status_code == 200
代码解释
pytest.fixture
:
- 定义了一个名为
client
的fixture。app.config['TESTING'] = True
开启测试模式,这样Flask应用在测试时会有一些特殊的行为(例如异常会直接返回而不是显示错误页面)。with app.test_client()
创建一个测试客户端,它可以模拟HTTP请求发送到Flask应用。yield client
将测试客户端返回给测试函数使用,测试结束后会自动清理资源。
test_get_data_status_code
:
- 这是一个测试函数,它接收
client
fixture作为参数。通过client.get('/data')
发送一个GET请求到/data
端点。然后使用assert response.status_code == 200
来验证返回的HTTP状态码是否为200,如果状态码不是200,测试将会失败。