如何测试消耗图像的FastAPI api端点?

问题描述 投票:1回答:1

我正在使用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()的正确方法是什么?

我正在使用pytest来测试FastAPI端点,该端点以@ app.post(“ / analyse”)二进制格式输入输入图像,异步定义分析(文件:字节=文件(...)):图像= Image.open(io.BytesIO(...

python pytest multipart fastapi starlette
1个回答
0
投票
  1. 为什么有区别?
© www.soinside.com 2019 - 2024. All rights reserved.