Hypothesis插件
Hypothesis 是用于基于属性的测试 的 Python 库。 Hypothesis 可以从 typing
中推断出如何构造带类型注释的类,并支持内置类型、许多标准库类型和泛型类型 和 typing_extensions
默认模块。
从 Pydantic v1.8 和 Hypothesis v5.29.0,Hypothesis 将自动加载对自定义类型 像 PaymentCardNumber
和 PositiveFloat
,这样 st.builds()
和 st.from_type()
策略无需任何用户配置即可支持它们。
Warning
请注意,虽然插件支持这些类型,但假设将(当前)为受约束的函数类型生成给定参数之外的值。
示例测试 Example tests¶
import typing
from hypothesis import given, strategies as st
from pydantic import BaseModel, EmailStr, PaymentCardNumber, PositiveFloat
class Model(BaseModel):
card: PaymentCardNumber
price: PositiveFloat
users: typing.List[EmailStr]
@given(st.builds(Model))
def test_property(instance):
# Hypothesis calls this test function many times with varied Models,
# so you can write a test that should pass given *any* instance.
assert 0 < instance.price
assert all('@' in email for email in instance.users)
@given(st.builds(Model, price=st.floats(100, 200)))
def test_with_discount(instance):
# This test shows how you can override specific fields,
# and let Hypothesis fill in any you don't care about.
assert 100 <= instance.price <= 200
from hypothesis import given, strategies as st
from pydantic import BaseModel, EmailStr, PaymentCardNumber, PositiveFloat
class Model(BaseModel):
card: PaymentCardNumber
price: PositiveFloat
users: list[EmailStr]
@given(st.builds(Model))
def test_property(instance):
# Hypothesis calls this test function many times with varied Models,
# so you can write a test that should pass given *any* instance.
assert 0 < instance.price
assert all('@' in email for email in instance.users)
@given(st.builds(Model, price=st.floats(100, 200)))
def test_with_discount(instance):
# This test shows how you can override specific fields,
# and let Hypothesis fill in any you don't care about.
assert 100 <= instance.price <= 200
(这个脚本是完整的,它应该“按原样”运行)
与 JSON 模式一起使用 Use with JSON Schemas¶
要测试客户端代码,您可以将 Model.schema()
与 hypothesis-jsonschema
包 生成与模式匹配的任意 JSON 实例。 对于 Web API 测试,Schemathesis 提供了更高级别的包装器,可以检测错误和安全漏洞。