如何在FastAPI中为Pydantic模型编写测试?



我刚开始使用FastAPI,但我不知道如何为Pydantic模型编写单元测试(使用pytest)。

下面是一个Pydantic模型的示例:

class PhoneNumber(BaseModel):
id: int
country: str
country_code: str
number: str
extension: str

我想通过创建一个示例PhoneNumber实例来测试这个模型,并确保PhoneNumber实例与字段类型相符。例如:

PhoneNumber(1, "country", "code", "number", "extension")

然后,我要断言PhoneNumber。国家等于国家。

您想要实现的测试可以直接使用pytest:

import pytest
def test_phonenumber():
pn = PhoneNumber(id=1, country="country", country_code="code", number="number", extension="extension")
assert pn.id == 1
assert pn.country == 'country'
assert pn.country_code == 'code'
assert pn.number == 'number'
assert pn.extension == 'extension'

但是我同意这个评论:

一般来说,您不会编写这样的测试。Pydantic有良好的测试套件(包括像你提议的那样的单元测试)。您的测试应该涵盖您编写的代码和逻辑,而不是代码导入的包

如果你有一个像PhoneNumber模型这样的模型,没有任何特殊/复杂的验证,那么编写简单地实例化它并检查属性的测试将不会那么有用。这样的测试就像测试Pydantic本身。

但是,如果您的模型有一些特殊/复杂的验证器函数,例如,它检查countrycountry_code是否匹配:

from pydantic import BaseModel, root_validator
class PhoneNumber(BaseModel):
...
@root_validator(pre=True)
def check_country(cls, values):
"""Check that country_code is the 1st 2 letters of country"""
country: str = values.get('country')
country_code: str = values.get('country_code')
if not country.lower().startswith(country_code.lower()):
raise ValueError('country_code and country do not match')
return values

…那么针对特定行为的单元测试将会更有用:

import pytest
def test_phonenumber_country_code():
"""Expect test to fail because country_code and country do not match"""
with pytest.raises(ValueError):
PhoneNumber(id=1, country='JAPAN', country_code='XY', number='123', extension='456')

另外,正如我在评论中提到的,既然你提到了FastAPI,如果你使用这个模型作为路由定义的一部分(无论是请求参数还是响应模型),那么一个更有用的测试将是确保你的路由可以正确使用你的模型。

@app.post("/phonenumber")
async def add_phonenumber(phonenumber: PhoneNumber):
"""The model is used here as part of the Request Body"""
# Do something with phonenumber
return JSONResponse({'message': 'OK'}, status_code=200)
from fastapi.testclient import TestClient
client = TestClient(app)
def test_add_phonenumber_ok():
"""Valid PhoneNumber, should be 200/OK"""
# This would be what the JSON body of the request would look like
body = {
"id": 1,
"country": "Japan",
"country_code": "JA",
"number": "123",
"extension": "81",
}
response = client.post("/phonenumber", json=body)
assert response.status_code == 200

def test_add_phonenumber_error():
"""Invalid PhoneNumber, should be a validation error"""
# This would be what the JSON body of the request would look like
body = {
"id": 1,
"country": "Japan",
# `country_code` is missing
"number": 99999,     # `number` is int, not str
"extension": "81",
}
response = client.post("/phonenumber", json=body)
assert response.status_code == 422
assert response.json() == {
'detail': [{
'loc': ['body', 'country_code'],
'msg': 'field required',
'type': 'value_error.missing'
}]
}

最新更新