标签: python-hypothesis

Flaky:假设检验产生的不可靠结果是什么意思?

我正在使用假设python包进行测试.

我收到以下错误:

Flaky:假设test_visiting会产生不可靠的结果:在第一次调用时出现伪造,但在后续调用时出现伪造

据我所知,测试工作正常.

我该如何解决这个问题?

pytest python-hypothesis

3
推荐指数
2
解决办法
938
查看次数

从正则表达式生成字符串数据

我希望能够使用正则表达式并使用 python 假设库生成符合要求的数据。例如,给定一个正则表达式

regex = re.compile('[a-zA-Z]')
Run Code Online (Sandbox Code Playgroud)

这将匹配任何英文字母字符。一个示例生成器可能是。

import hypothesis
import string

hypothesis.strategies.text(alphabet=string.ascii_letters)
Run Code Online (Sandbox Code Playgroud)

但理想情况下,我想构建一个与传入的任何正则表达式匹配的字符串。

python-hypothesis

3
推荐指数
1
解决办法
891
查看次数

带有可选键的字典策略

目前我正在使用假设 fixed_dictionaries 策略来生成一个字典,其中包含被认为对我的应用程序有效的特定键和数据类型。我需要一个策略来生成这个固定的字典以及其他删除特定键的字典。或者具有特定最小键集和可选附加键的字典,最好以产生这些可选键的各种组合的方式。

这是需要验证的 json 架构示例,带有 2 个可选字段。我想为此模式生成所有可能的有效数据。

'user_stub': {
    '_id':        {'type': 'string'},
    'username':   {'type': 'string'},
    'social':     {'type': 'string'},
    'api_name':   {'type':     'string',
                   'required': False},
    'profile_id': {'type':     'integer',
                   'required': False},
}
Run Code Online (Sandbox Code Playgroud)

这是我想出的,但它是不正确的,因为它保留了键,但使用 None 作为值,而我想要删除键。

return st.fixed_dictionaries({
    '_id':        st.text(),
    'username':   st.text(),
    'social':     st.text(),
    'api_name':   st.one_of(st.none(),
                            st.text()),
    'profile_id': st.one_of(st.none(),
                            st.integers()),
})
Run Code Online (Sandbox Code Playgroud)

编辑:更新复合策略 ->

似乎最好根据返回的数据类型分离额外的可选字典,否则可能会得到值不匹配的键。

@st.composite
def generate_data(draw):
    base_data = st.fixed_dictionaries({
        '_id':      st.text(),
        'username': st.text(),
        'social':   st.text(),
    })
    optional_strs = st.dictionaries(
        keys=st.just('api_name'),
        values=st.text()
    )
    optional_ints = st.dictionaries(
        keys=st.just('profile_id'),
        values=st.integers()
    )

    b = draw(base_data)
    s …
Run Code Online (Sandbox Code Playgroud)

python testing unit-testing python-3.x python-hypothesis

3
推荐指数
1
解决办法
1385
查看次数

假设在给定的测试数据帧中使用 pd.datetime dtype 创建列

我想测试某种方法是否可以处理 pandas 数据框中的不同日期,并将其作为参数。下面的示例应该阐明我想要什么样的设置。在该示例中,column('Date', dtype=pd.datetime)不适用于在测试数据框中创建日期列:

from hypothesis import given
from hypothesis.extra.pandas import column, data_frames
import pandas as pd
from unittest import TestCase

class TestExampleClass(TestCase):

    @given(data_frames([column('A', dtype=str), column('B', dtype=int),column('Date', dtype=pd.datetime)]))
    def test_example_test_method(self, dataframe):
        self.assertTrue(True)

Run Code Online (Sandbox Code Playgroud)

有任何想法吗?我知道如何使用假设库创建日期时间索引的 pandas DataFrame?,但这对我的具体情况没有帮助。

python unit-testing pandas python-hypothesis

3
推荐指数
1
解决办法
168
查看次数

如何在同一测试用例中使用假设和pytest-tornado基于产量的测试?

我正在编写使用Tornado库的代码的py.test测试.如何在涉及协同程序和IOLoop的测试中使用假设?我已经能够编写基于产量测试,而假设用pytest基旋风的,但是当我尝试将其联合,我收到以下错误:@pytest.mark.gen_test@given

FailedHealthCheck:测试运行@given应该返回None,但test_both返回<generator object test_both at 0x7fc4464525f0>.

有关此内容的更多信息,请参见http://hypothesis.readthedocs.org/en/latest/healthchecks.html.如果要仅禁用此运行状况检查,请添加到此测试HealthCheck.return_valuesuppress_health_check设置.

我非常有信心这是一个真正的问题而不只是一个禁用健康检查的问题,考虑到假设文档

基于产量的测试根本不起作用.

这是代表我的情况的代码:

class MyHandler(RequestHandler):

    @gen.coroutine
    def get(self, x):
        yield gen.moment
        self.write(str(int(x) + 1))
        self.finish()


@pytest.fixture
def app():
    return Application([(r'/([0-9]+)', MyHandler)])


@given(x=strategies.integers(min_value=0))
def test_hypothesis(x):
    assert int(str(x)) == x


@pytest.mark.gen_test
def test_tornado(app, http_client, base_url):
    x = 123
    response = yield http_client.fetch('%s/%i' % (base_url, x))
    assert int(response.body) == x …
Run Code Online (Sandbox Code Playgroud)

python tornado pytest python-2.7 python-hypothesis

2
推荐指数
1
解决办法
856
查看次数

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

我使用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,例如用作测试运行器:

# …
Run Code Online (Sandbox Code Playgroud)

python python-hypothesis

2
推荐指数
1
解决办法
1605
查看次数

使用假设在fixed_dictionaries中生成两个长度相等的列表

我正在尝试使用以下fixed_dictionaries策略生成示例数据,其中两个键的列表作为必须具有相同长度的值,例如:

{'ids': [1, 2, 3],
 'words': ['foo', 'bar', 'baz']}
Run Code Online (Sandbox Code Playgroud)

我怎样才能强制执行这个限制?我想我也许能够将一个定义为另一个的复合体,但我不知道该怎么做。就像是:

import hypothesis.strategies as st

ids = st.lists(elements=st.integers())

@st.composite
def words(draw, elements=st.text()):
    draw(sample_ids) # ???
Run Code Online (Sandbox Code Playgroud)

python python-hypothesis

2
推荐指数
1
解决办法
735
查看次数