如何在假设中使用复合策略(hypothesis.errors.InvalidArgument:预期的 SearchStrategy 但得到了函数)

The*_*Cat 7 python-hypothesis

此示例是文档中示例的变体:

import hypothesis.strategies as st
    
from hypothesis import given
    
@st.composite
def s(draw):
    x = draw(st.text(), min_size=1)
    y = draw(st.text(alphabet=x))
    return (x, y)
    
    
    
@given(s1=s, s2=s)
def test_subtraction(s1, s2):
    
    print(s1, s2)
    
    assert 0
Run Code Online (Sandbox Code Playgroud)

它失败:

E hypothesis.errors.InvalidArgument: Expected SearchStrategy but got <function accept.<locals>.s at 0x7fd7e5c05620> (type=function)

/mnt/work/unfuncat/software/anaconda/lib/python3.6/site-packages/hypothesis/internal/validation.py:40: InvalidArgument
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

The*_*Cat 10

您需要调用复合函数。文档中没有对此进行解释,但2016 年的博客文章中有一个示例。

@given(s1=s(), s2=s()) # <===== change
def test_subtraction(s1, s2):
    
    print(s1, s2)
    
    assert 0
Run Code Online (Sandbox Code Playgroud)

  • [文档中还有一个示例](https://hypothesis.readthedocs.io/en/latest/data.html#composite-strategies) (`list_and_index`),但我同意这应该在文本中明确说明。 (3认同)