如何在 Python 假设中递归生成布尔表达式?

How can I generate a boolean expression recursively in Python Hypothesis?

我是 Python 的假设库和一般基于 属性 的测试的新手。我想使用以下语法生成任意嵌套的策略表达式:

((A and B) or C)

我感觉递归策略是我想要的,但我很难理解如何使用它。我的代码似乎只生成一个 "level" 表达式。这是我拥有的:

import unittest

from hypothesis import given
from hypothesis.strategies import text, composite, sampled_from, characters, recursive, one_of


def policy_expressions():
    return recursive(attributes(), lambda base_strategy: one_of(base_strategy, policy_expression()))

@composite
def policy_expression(draw):
    left = draw(attributes())
    right = draw(attributes())
    gate = draw(gates())
    return u' '.join((left, gate, right))


def attributes():
    return text(min_size=1, alphabet=characters(whitelist_categories='L', max_codepoint=0x7e))


def gates():
    return sampled_from((u'or', u'and'))


class TestPolicyExpressionSpec(unittest.TestCase):

    @given(policy_expression=policy_expressions())
    def test_policy_expression_spec(self, policy_expression):
        print policy_expression
        assert policy_expression # not empty

我如何使用假设生成任意嵌套的策略表达式?

我认为这可能会满足您的要求。

import unittest

from hypothesis import given
from hypothesis.strategies import text, composite, sampled_from, characters, recursive, one_of


def policy_expressions():
    return one_of(attributes(), policy_expression())

@composite
def policy_expression(draw):
    left = draw(policy_expressions())
    right = draw(policy_expressions())
    gate = draw(gates())
    return u' '.join((left, gate, right))


def attributes():
    return text(min_size=1, alphabet=characters(whitelist_categories='L', max_codepoint=0x7e))


def gates():
    return sampled_from((u'or', u'and'))


class TestPolicyExpressionSpec(unittest.TestCase):

    @given(policy_expression=policy_expressions())
    def test_policy_expression_spec(self, policy_expression):
        print policy_expression
        assert policy_expression # not empty

if __name__ == '__main__':
    unittest.main()

我认为正确的方法是将 base_strategy 作为 policy_expression 的参数:

def policy_expressions():
    return recursive(attributes(), policy_expression)

@composite
def policy_expression(draw, base_strategy):
    left = draw(base_strategy)
    right = draw(base_strategy)
    gate = draw(gates())
    return u' '.join((left, gate, right))

接受的答案不使用 recursive 可能 运行 进入假设博客 Generating recursive data post 中描述的问题。