12

我正在使用 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()

4

1 回答 1

22

您会看到不同的行为,因为requests并且在每个方面都与wrapsTestClient不完全相同。要深入挖掘,请参阅源代码:(使用来自 starlette 库,仅供参考)TestClientrequestsFastAPITestClient

https://github.com/encode/starlette/blob/master/starlette/testclient.py

要解决,您可以摆脱MultipartEncoder因为requests可以接受文件字节并按form-data格式对其进行编码,例如

# change it
r = requests.post(url, data=m, headers={'Content-Type': m.content_type}, timeout = 8000)

# to 
r = requests.post(url, files={"file": ("filename", open(filename, "rb"), "image/jpeg")})

并修改 FastAPI 测试代码:

# change
response = client.post("/analyse",
                       data=m,
                       headers={"Content-Type": "multipart/form-data"}
                       )
# to
response = client.post(
    "/analyse", files={"file": ("filename", open(filename, "rb"), "image/jpeg")}
)
于 2020-03-23T03:17:39.523 回答