You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Hypothesis生成满足指定顺序关系的两个测试值?

解决Hypothesis生成有序参数的几种方案

针对你需要生成满足valid_from <= valid_to的两个日期参数的场景,有几种实用方案:

方案一:元组+映射排序

直接生成日期元组后排序,确保第一个值小于等于第二个,同时保留两个独立参数:

import datetime as dt

from hypothesis import given
from hypothesis import strategies as st


@given(
    date_pair=st.tuples(st.dates(), st.dates()).map(lambda pair: tuple(sorted(pair)))
)
def test_dates_are_ordered(date_pair):
    valid_from, valid_to = date_pair
    assert valid_from <= valid_to

如果想保持测试函数的参数列表更清晰,也可以配合unpack=True直接拆分参数:

@given(
    st.tuples(st.dates(), st.dates()).map(lambda pair: tuple(sorted(pair)), unpack=True)
)
def test_dates_are_ordered(valid_from: dt.date, valid_to: dt.date):
    assert valid_from <= valid_to

方案二:用st.data()动态生成依赖参数

在测试函数内部先生成第一个日期,再基于它生成第二个不小于它的日期,这种方式更灵活,适合复杂的依赖关系:

import datetime as dt

from hypothesis import given, data
from hypothesis import strategies as st


@given(data=data())
def test_dates_are_ordered(data: data.DataObject):
    valid_from = data.draw(st.dates())
    # 生成大于等于valid_from的日期
    valid_to = data.draw(st.dates().filter(lambda d: d >= valid_from))
    assert valid_from <= valid_to

方案三:自定义可复用策略

如果这类有序参数的场景经常出现,可以封装成自定义策略,提升复用性:

import datetime as dt

from hypothesis import given
from hypothesis import strategies as st


def ordered_dates():
    return st.tuples(st.dates(), st.dates()).map(lambda pair: tuple(sorted(pair)))


# 用unpack直接拆分参数
@given(ordered_dates(), unpack=True)
def test_dates_are_ordered(valid_from: dt.date, valid_to: dt.date):
    assert valid_from <= valid_to

这几种方案都能保留两个独立参数,同时确保它们满足顺序关系,你可以根据场景复杂度选择合适的方式。

内容的提问来源于stack exchange,提问作者Max Görner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:11:09