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

Per*_*ock 13 python unit-testing pytest pydantic fastapi

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

这是 Pydantic 模型的示例:

class PhoneNumber(BaseModel):
    id: int
    country: str
    country_code: str
    number: str
    extension: str
Run Code Online (Sandbox Code Playgroud)

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

PhoneNumber(1, "country", "code", "number", "extension")
Run Code Online (Sandbox Code Playgroud)

然后,我想断言 PhoneNumber.country 等于“country”。

Gin*_*pin 31

您想要实现的测试可以直接使用 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'
Run Code Online (Sandbox Code Playgroud)

但我同意这个评论

一般来说,您不会编写这样的测试。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
Run Code Online (Sandbox Code Playgroud)

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

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')
Run Code Online (Sandbox Code Playgroud)

另外,正如我在评论中提到的,既然您提到了 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)
Run Code Online (Sandbox Code Playgroud)
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'
        }]
    }
Run Code Online (Sandbox Code Playgroud)