作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚开始使用 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.country 等于“country”。
最佳答案
您想要实现的测试很容易使用 pytest。不需要特殊技巧,只需遵循 pytest docs and tutorials :
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'
但我同意
this comment :
Generally speaking, you don't write tests like this. Pydantic has agood test suite (including a unit test like the one you're proposing). Your test should cover the code and logic you wrote, not thepackages you imported.
PhoneNumber
模型这样的模型,它非常简单并且没有“特殊”/“花哨”行为,那么编写简单地实例化它并检查属性的测试将不会那么有用。像这样的测试就像测试 Pydantic 本身。
country
和
country_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')
另外,正如我提到的
in my comment ,因为你提到了 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'
}]
}
关于python - 如何在 FastAPI 中为 Pydantic 模型编写测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68705698/
我是一名优秀的程序员,十分优秀!