如何创建使用“builds()”的可配置自定义假设策略?

thi*_*ybk 2 python python-hypothesis

我使用builds()and创建了自定义假设策略@composite(设计灵感来自文档中的这个示例)。这些策略的设计类似于下面的伪代码:

# strategies.py

from hypothesis.strategies import builds, composite, draw, floats, integers

class SutConfiguration:
    """ Data which represents the configuration of the system under test. """
    def __init__(self, integer, float):
        self.integer = integer
        self.float = float

# custom strategy which uses builds()
SutConfigurationStrategy = builds(
    SutConfiguration,
    integer=integers(min_value=APP_SPECIFIC_INT_MIN, max_value=APP_SPECIFIC_INT_MAX),
    float=floats(min_value=APP_SPECIFIC_FLOAT_MIN, max_value=APP_SPECIFIC_FLOAT_MAX),
)

@composite
def overall_test_configuration(draw, sut_st=SutConfigurationStrategy, env_st=SutEnvironmentStrategy):
    """Custom strategy which uses draw."""
    sut_config = draw(sut_st)
    env_config = draw(env_st)
    return (sut_config, rc_stereomatching_config, env_config)
Run Code Online (Sandbox Code Playgroud)

该策略照常使用unittest,例如用作测试运行器:

# test.py

import unittest
from <package>.strategies import overall_test_configuration

class TestSut(unittest.TestCase):
    """Class containing several tests for the system under test."""
    @given(overall_test_configuration())
    def test_something():
        """Test which uses overall_test_configuration"""
        ...
Run Code Online (Sandbox Code Playgroud)

现在我想使策略可配置为实际应用程序以min_valueintegers(min_value=APP_SPECIFIC_INT_MIN, ...)定义测试功能时定义例如。这可以@composite通过像done here这样的 agruments为策略完成。但是我怎样才能使使用的策略可builds()配置呢?

DRM*_*ver 5

您可以定义一个函数,该函数返回与其他任何策略一样的策略:

def some_custom_strategy(a, b):
    return builds(foo, bar(a, b))
Run Code Online (Sandbox Code Playgroud)

当你有额外的参数时,这就是复合发生的所有事情——复合正在定义一个返回策略的函数,这些额外的参数通过函数传递给底层的装饰函数。