MST

星途 面试题库

面试题:Python中如何使用Pytest测试RESTful API的状态码

假设你有一个使用Flask框架搭建的简单RESTful API,例如一个返回JSON数据的GET请求接口。请描述如何使用Pytest测试框架来验证该API返回的HTTP状态码为200。给出关键代码片段并解释。
39.0万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
  1. 安装依赖: 确保flaskpytest已经安装。可以使用pip install flask pytest来安装。
  2. 示例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)
  1. 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,测试将会失败。