如何使用 hypothesis-extra 在 Python 中进行额外的属性测试

2023-04-13 00:00:00 如何使用 hypothesis

hypothesis-extra 是假设测试库 hypothesis 的一个扩展库,可以用来进行更复杂的属性测试。具体使用方法如下:

1.安装 hypothesis-extra

使用 pip 安装 hypothesis-extra:

pip install hypothesis-extra

2.导入所需的模块

from hypothesis import given
from hypothesis.strategies import text
from hypothesis_extra import attributes

其中,given 是 hypothesis 的一个装饰器,用来定义测试函数的输入参数;text 是 hypothesis 中用来生成字符串的策略;attributes 是 hypothesis-extra 中用来生成额外属性的策略。

3.编写测试函数

@given(attributes(text(min_size=5, max_size=10), label='name'),
       attributes(text(min_size=8, max_size=20), label='website'),
       attributes(text(min_size=10, max_size=20), label='description'))
def test_website(data):
    assert len(data.name) >= 5 and len(data.name) <= 10
    assert len(data.website) >= 8 and len(data.website) <= 20
    assert len(data.description) >= 10 and len(data.description) <= 20
    assert 'pidancode.com' not in data.website
    assert '皮蛋编程' in data.description

在这个测试函数中,我们使用了三个 attributes 策略生成了三个额外的属性,分别是 name、website 和 description,它们的取值范围分别是 [5, 10]、[8, 20] 和 [10, 20]。在测试函数中,我们检查了这三个属性是否满足条件,并且要求 website 属性不能包含 'pidancode.com' 字符串,description 属性必须包含 '皮蛋编程' 字符串。

4.运行测试

pytest test_website.py

测试通过。

相关文章