python - 假设 - 在测试之间重用@given

标签 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

重用 @given block 的最佳方法是什么?

最佳答案

策略被设计为可组合对象,重用它们没有问题。

因此,除了已接受的答案之外,还可以将配置的子策略简单地存储为可重用的全局变量,例如

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):
    ...

timezones示例显示了该模式,它定义了一个 aware_datetimes 策略并在多个测试中使用该策略,由可变数量的兄弟组成。

关于python - 假设 - 在测试之间重用@given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57769809/

相关文章:

travis-ci - pytest 因 ModuleNotFoundError 和未使用插件的名称而失败

python - 假设+单元测试测试锁定sqlite数据库

python - 如何通过ID合并文件?

python - 如何从 C 代码访问 python bool 变量?

python - Numpy 和 matplotlib 垃圾收集

Python-Hypothesis:指定和管理 NaN 值

python - 如何使用假设库创建日期时间索引 pandas DataFrame?

Python:将用户名与/密码匹配;提示密码不正确;

python - 如何通过索引替换 python 上的列表项

python - 使用假设在 fixed_dictionaries 中生成两个等长列表