You need to enable JavaScript to run this app. 如何在FastAPI中为Pydantic模型编写pytest单元测试
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI中为Pydantic模型编写pytest单元测试

Pydantic 模型 pytest 单元测试方案

Pydantic 模型会在实例化时自动执行类型校验,一旦输入不符合字段类型要求会直接抛出ValidationError异常,你的测试需求可以按照以下方案实现:


完整测试代码示例

创建测试文件test_models.py,写入以下内容:

import pytest
from pydantic import ValidationError
# 替换为你实际的模型导入路径
from your_module_path import PhoneNumber

def test_phone_number_valid_input():
    # 推荐使用关键字参数传值,避免后续字段顺序调整导致传参错位
    phone_instance = PhoneNumber(
        id=1,
        country="country",
        country_code="code",
        number="number",
        extension="extension"
    )
    # 断言字段值符合预期
    assert phone_instance.country == "country"
    # 可补充其他字段的断言逻辑
    assert phone_instance.id == 1
    assert phone_instance.country_code == "code"
    assert phone_instance.number == "number"
    assert phone_instance.extension == "extension"

def test_phone_number_type_validation():
    # 额外补充非法输入测试,验证类型约束生效
    with pytest.raises(ValidationError):
        # id字段要求为int类型,传入字符串会触发校验失败
        PhoneNumber(
            id="invalid_string",
            country="country",
            country_code="code",
            number="number",
            extension="extension"
        )

运行测试

在项目根目录执行以下命令即可执行测试:
pytest test_models.py -v

如果合法输入用例运行通过,就说明模型类型校验生效、字段赋值符合你的预期。你原来使用的位置参数传值PhoneNumber(1, "country", "code", "number", "extension")也可以正常运行,只是关键字参数的写法可维护性更高。

内容的提问来源于stack exchange,提问作者PercySherlock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:33:00