python - 假设库: strategy for the complement of some other strategy

标签 python unit-testing python-hypothesis

我正在使用Hypothesis用于单元测试的库。使用此库,您不必手动选择输入,而是可以定义要测试的完整输入集。然后,假设将从该集合中进行采样,以查找破坏该函数的输入。这也称为基于属性的测试。在假设中,这些集合称为策略。

现在我想对一个验证某些输入的函数进行单元测试:

GRIDSIZE_FORMAT = "^[0-9]+x[0-9]+$"
CELL_FORMAT = "^[A-Z]+[0-9]+$"

def _validate(gridsize, walls, entrance):
    if not re.match(GRIDSIZE_FORMAT, gridsize):
        raise ValueError(f"grid size '{gridsize}' does not match format '{GRIDSIZE_FORMAT}'")
    for wall in walls:
        if not re.match(CELL_FORMAT, walls):
            raise ValueError(f"wall '{wall}' does not match format '{CELL_FORMAT}'")
    if not re.match(CELL_FORMAT, entrance):
        raise ValueError(f"entrance '{entrance}' does not match format '{CELL_FORMAT}'")

为了正确测试此函数,我想生成“除 X 之外的任何内容”形式的示例,X 是此函数的正确输入格式。

假设库中是否有可以生成这样的输入的策略?

最佳答案

不幸的是,假设无法计算策略的补集,因为策略可以由任意用户提供的代码组成(包括副作用!)。例如,hypothesis.extra.django.from_model(User) 的补集应该是什么,它将生成的实例插入数据库? (无效,数据库中没有,...)

在更具体的情况下,您可以采用规范的补充,然后从该补充中派生策略。你的正则表达式技巧是一个很好的例子 - 显式的集补往往比天真的“生成正确的东西,并过滤掉有效实例”方法更有效。

关于python - 假设库: strategy for the complement of some other strategy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71869905/

相关文章:

python - 单击 : how do I apply an action to all commands and subcommands but allow a command to opt-out (part duex)?

python - Kubernetes:加载 ASGI 应用程序时出错。在模块 "app"中找不到属性 "main"

angular - 没有将 "exportAs"设置为 "cdkStep"的指令

unit-testing - 在同一项目中使用GrailsUnitTestCase和Spock规范

python - 假设+单元测试测试锁定sqlite数据库

python - 管理应用程序依赖性的工具/最佳实践?

python - 迭代相反的数字序列

c# - 如何使用 Moq 返回 Task<string>?

python - 在 python 中使用假设和 py.test 测试复合策略,我必须一次测试它们吗?

Python 假设 : How to compose generators that are dependent on each other?