【发布时间】:2022-09-27 17:50:07
【问题描述】:
在使用假设来测试我的 pydantic 模型时,我不知道如何处理自定义验证器抛出的 ValidationError。这是一个显示问题的非常小的示例:
# model
from pydantic import BaseModel, validator
class SimpleModel(BaseModel):
a: int
b: int
@validator(\'b\')
def check_numbers(cls, b, values):
if b*values[\'a\'] < 0:
raise ValueError(\'a*b > 0 does not hold\')
return b
# test
from hypothesis import given, strategies as st
@given(st.builds(SimpleModel))
def test_simple_model(instance: SimpleModel):
assert type(instance.b) == int
到目前为止,我已经编写了自定义假设搜索策略来仅生成有效的实例。但是对于更复杂的模型来说,这变得非常乏味,所以在我看来,必须有一种更聪明的方法来“使用”ValidationError。该错误也在测试功能之前引发,因此我无法在测试功能中处理它。
我需要一种生成实例的可能性,它只是跳过引发 ValidationError 的实例。
标签: python error-handling pydantic python-hypothesis