ide*_*typ 5 python python-hypothesis
我已经使用hypothesis了一段时间了。我想知道如何重用@given parts.
我拥有的一些代码大约有 20 行,我将整个@given部分复制到几个测试用例之上。
一个简单的测试示例
@given(
some_dict=st.fixed_dictionaries(
{
"test1": st.just("name"),
"test2": st.integers()
}
)
)
def test_that uses_some_dict_to_initialize_object_im_testing(some_dict):
pass
Run Code Online (Sandbox Code Playgroud)
重用@given块的最佳方法是什么?
策略被设计为可组合对象,重用它们没有问题。
因此,接受答案的替代方案只是将配置的子策略存储为可重用的全局变量,例如
a_strategy = st.fixed_dictionaries({ "test1": st.just("name"), "test2": st.integers()})
@given(some_dict=a_strategy)
def test_uses_some_dict_to_initialize_object_im_testing(some_dict):
...
@given(some_dict=a_strategy, value=st.integers())
def test_other(some_dict, value):
...
Run Code Online (Sandbox Code Playgroud)
时区示例显示了该模式,它定义了一个aware_datetimes策略并在多个测试中使用该策略,由可变数量的同级组成。
创建您自己的装饰器:
def fixed_given(func):
return given(
some_dict=st.fixed_dictionaries(
{
"test1": st.just("name"),
"test2": st.integers()
}
)
)(func)
@fixed_given
def test_that_uses_some_dict_to_initialize_object_in_testing(some_dict):
pass
Run Code Online (Sandbox Code Playgroud)