property-based-testing - 如何在 Python 假设中递归地生成布尔表达式?
问题描述
一般来说,我是 Python 的假设库和基于属性的测试的新手。我想使用以下语法生成任意嵌套的策略表达式:
((A和B)或C)
我觉得递归策略是我想要的,但我很难理解如何使用它。我拥有的代码似乎只生成一个“级别”的表达。这是我所拥有的:
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
如何使用 Hypothesis 生成任意嵌套的策略表达式?
解决方案
我认为这可能会做你想要的。
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()
推荐阅读
- php - Wordpress 在自定义页面上更改 URL 参数
- python - PyQt5可移动按钮导致屏幕拖影
- python - 如何处理将作为另一个包的依赖项的命名空间包
- sql-server - 需要帮助查找 SSIS 教程的文件
- javascript - javascript中的基本和基本矩阵
- visual-studio - 当我使用EF Code First时,是否可以在vstudio中看到数据模型图?
- go - DEX LDAP 连接器令牌签名
- c# - Ext.NET 部分视图未显示
- linux - 如何在linux shell中将子字符串与特殊字符匹配?
- python - difflib 序列匹配器缺少公共子字符串