I'm new to Python's Hypothesis library and property based testing in general. I want to generate arbitrarily nested policy expressions with the following grammar:
((A and B) or C)
I'm feeling that the recursive strategy is what I want, but I'm having a hard time understanding how to use it. The code I have only seems to generate one "level" of expression. Here's what I have:
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
How might I generate arbitrarily nested policy expressions using Hypothesis?