首页 > 解决方案 > Hypothesis.strategies 从日期生成字符串

问题描述

我正在使用假设来测试我的应用程序并为端点生成随机输入数据。这是我的代码:

def generate_upload_data():
    today = datetime.date.today()
    start_date = today - relativedelta(months=1)
    return hypothesis.strategies.builds(
        SomeModelClass,
        date=hypothesis.strategies.dates(
            min_value=start_date, max_value=today
        ),
    )

这会将日期生成为 datetime.date 对象,但我需要它以字符串格式(01.01.2020)。所以我需要像这样转换它

random_date.strftime("%d.%m.%Y") 

但我找不到任何方法来做到这一点。是否可以从假设中的日期生成字符串?

标签: pythonhypothesis-testpython-hypothesis

解决方案


请参阅有关调整策略的文档。正如上面的 Azat Ibrakov 所说,您可以使用以下方法轻松地将日期转换为字符串

hypothesis.strategies.dates(...).map(lambda date: date.strftime("%d.%m.%Y"))

推荐阅读