如何更改假设生成的最大测试用例数?

Aud*_*cot 5 python automated-tests property-based-testing python-hypothesis

著名的基于属性的测试框架假设能够生成大量的测试用例。

但有没有办法限制假设生成的测试用例的数量,从而缩短测试周期呢?

例如,将特定的关键字参数提供给@given装饰器?

Aza*_*kov 8

这取决于您是要限制一项测试还是所有测试,但方法类似并且基于设置

配置单个测试

要更改某些测试的默认行为,我们可以用类似的settings对象来装饰它们

from hypothesis import given, settings, strategies


@given(strategies.integers())
@settings(max_examples=10)
def test_this_a_little(x):
    ...


@given(strategies.integers())
@settings(max_examples=1000)
def test_this_many_times(x):
    ...
Run Code Online (Sandbox Code Playgroud)

fortest_this_a_little将会10生成(最多)示例并且 fortest_this_many_times将会生成1000.

配置所有测试

要在测试运行引导期间更改所有测试的默认行为(例如,pytest它可以是conftest.pymodule),我们可以定义一个自定义hypothesis设置配置文件,然后在测试调用期间使用它,例如

from hypothesis import settings

settings.register_profile('my-profile-name',
                          max_examples=10)
Run Code Online (Sandbox Code Playgroud)

之后(假设您正在使用pytest

> pytest --hypothesis-profile=my-profile-name
Run Code Online (Sandbox Code Playgroud)

进一步阅读

hypothesis非常棒,允许我们配置很多东西,可用选项在文档中列出。