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

How to write tests for Pydantic models in FastAPI?

我刚开始使用 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 等于“国家”。

你想实现的测试用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'

但我同意:

Generally speaking, you don't write tests like this. Pydantic has a good test suite (including a unit test like the one you're proposing) . Your test should cover the code and logic you wrote, not the packages you imported.

如果您有一个像 PhoneNumber 模型这样的模型,它非常简单并且没有“特殊”/“花哨”的行为,那么编写简单实例化它并检查属性的测试将不会那么有用。像这样的测试就像测试 Pydantic 本身。

但是,如果您的模型有一些 validator functions 会执行一些“特殊”/“奇特”检查,例如,它会检查 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'
        }]
    }