【问题标题】:Handling of pydantic ValidationError when testing with hypothesis.given使用hypothesis.given进行测试时处理pydantic ValidationError
【发布时间】: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


    【解决方案1】:

    在使用了更多假设的功能后,我想出了这种方法,它使用composite 策略和assume。使用composite,您可以创建自定义策略,然后可以在given 装饰器中使用。 assume 用于告诉假设示例不好并且应该跳过(我之前在测试中使用过,但在模型生成期间也可以使用它)。

    from pydantic import ValidationError
    from hypothesis import given, assume, strategies as st
    
    @st.composite
    def simple_model_strategy(draw) -> SimpleModel:
        try:
            simple_model = draw(st.builds(SimpleModel))
        except ValidationError:
            assume(False)
        return simple_model
    
    @given(simple_model_strategy())
    def test_simple_model(instance: SimpleModel):
        assert type(instance.b) == int
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 2016-02-26
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多