我正在使用 pytest 测试一个 FastAPI 端点,该端点以二进制格式输入图像,如
@app.post("/analyse")
async def analyse(file: bytes = File(...)):
image = Image.open(io.BytesIO(file)).convert("RGB")
stats = process_image(image)
return stats
启动服务器后,我可以通过运行调用手动成功测试端点requests
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
url = "http://127.0.0.1:8000/analyse"
filename = "./example.jpg"
m = MultipartEncoder(
fields={'file': ('filename', open(filename, 'rb'), 'image/jpeg')}
)
r = requests.post(url, data=m, headers={'Content-Type': m.content_type}, timeout = 8000)
assert r.status_code == 200
但是,以以下形式设置测试:
from fastapi.testclient import TestClient
from requests_toolbelt.multipart.encoder import MultipartEncoder
from app.server import app
client = TestClient(app)
def test_image_analysis():
filename = "example.jpg"
m = MultipartEncoder(
fields={'file': ('filename', open(filename, 'rb'), 'image/jpeg')}
)
response = client.post("/analyse",
data=m,
headers={"Content-Type": "multipart/form-data"}
)
assert response.status_code == 200
运行测试时python -m pytest
,这给了我一个
> assert response.status_code == 200
E assert 400 == 200
E + where 400 = <Response [400]>.status_code
tests\test_server.py:22: AssertionError
-------------------------------------------------------- Captured log call ---------------------------------------------------------
ERROR fastapi:routing.py:133 Error getting request body: can't concat NoneType to bytes
===================================================== short test summary info ======================================================
FAILED tests/test_server.py::test_image_analysis - assert 400 == 200
我究竟做错了什么?使用图像文件
编写测试函数的正确方法是什么?test_image_analysis()