声明由假设生成的两个参数之间的关系

2024-04-25 19:30:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我用假设来检验,我想在检验的两个参数之间建立一种关系。我知道assume,但当我事先知道约束时,这似乎相当浪费。你知道吗

下面是一个简单的例子:

from datetime import date

import pytest
from hypothesis import given, assume, strategies as st


def get_daterange_filter(start, end):
    """`start` and `end` are dates of the format: YYYYMMDD"""
    if int(start) > int(end):
        raise ValueError(f"{start} comes after {end}")
    else:
        pass


dt_strategy = st.dates(min_value=date(2019, 4, 1),
                       max_value=date(2019, 7, 31))


@given(dt_strategy, dt_strategy)
def test_daterange_filter(dt1, dt2):
    assume(dt1 > dt2)
    start, end = dt1.strftime("%Y%m%d"), dt2.strftime("%Y%m%d")
    with pytest.raises(ValueError):
        get_daterange_filter(start, end)

上述统计摘要报告如下:

hypo.py::test_daterange_filter:

  - 100 passing examples, 0 failing examples, 68 invalid examples
  - Typical runtimes: 0-1 ms
  - Fraction of time spent in data generation: ~ 47%
  - Stopped because settings.max_examples=100

那是浪费的尝试。这是一个非常简单的案例,但在一个典型的数据密集型项目中,我可以预见许多这样的场景。所以我想知道,是否有一个简单的方法来判断两个参数满足某种关系的假设(在这个例子中,一个大于另一个)。我在文件里找不到任何东西。你知道吗


Tags: import参数date关系dt浪费filterstart
1条回答
网友
1楼 · 发布于 2024-04-25 19:30:02

如果您需要相互依赖的策略,请使用策略共享:

dates = st.shared(st.dates(min_value=date(2019, 4, 1), max_value=date(2019, 7, 31)))

@st.composite
def later_dates(draw):
    return draw(st.dates(min_value=draw(dates)))
    # or, if you need the strict inequality for passing
    # the test in its given form, add a day to min_value:
    # return draw(st.dates(min_value=draw(dates) + timedelta(days=1)))


@given(start=later_dates(), end=dates)
def test_daterange_filter(start, end):
    fstart, fend = start.strftime("%Y%m%d"), end.strftime("%Y%m%d")
    with pytest.raises(ValueError):
        get_daterange_filter(fstart, fend)

运行更多记录时间的示例:

...
collected 2 items

test_spam.py::test_daterange_filter PASSED
test_spam.py::test_daterange_filter_shared_date_strategy PASSED
======================================== Hypothesis Statistics =========================================

test_spam.py::test_daterange_filter:

  - 10000 passing examples, 0 failing examples, 10050 invalid examples
  - Typical runtimes: < 1ms
  - Fraction of time spent in data generation: ~ 44%
  - Stopped because settings.max_examples=10000

test_spam.py::test_daterange_filter_shared_date_strategy:

  - 10000 passing examples, 0 failing examples, 0 invalid examples
  - Typical runtimes: < 1ms
  - Fraction of time spent in data generation: ~ 50%
  - Stopped because settings.max_examples=10000

======================================== slowest test durations ========================================
12.55s call     test_spam.py::test_daterange_filter
6.27s call     test_spam.py::test_daterange_filter_shared_date_strategy

(0.00 durations hidden.  Use -vv to show these durations.)
====================================== 2 passed in 18.86 seconds =======================================

相关问题 更多 >