Pytest和Hypothesis:在嵌套异步函数中给出



我有一个测试用例的问题,如下所示。我想测试一个类Foo的函数,但我不能创建类Foo的任何实例,直到我创建我的测试函数。然后为了创建测试的测试值,我需要Foo的实例作为假设。我不能在测试文件的顶层这样做,因为我没有Foo实例。

当我运行pytest时,我得到错误:hypothesis.errors.InvalidArgument: Hypothesis doesn't know how to run async test functions like inner。无论内部函数是否带有装饰符@pytest.mark.asyncio,都会抛出错误。

有没有人有过类似的情况,知道如何解决它?

import pytest
from hypothesis import given
from hypothesis import strategies as st
class Foo:

async def bar(value):
return value
@st.composite
def int_datatype(draw, target):
...
@pytest.mark.asyncio
async def test_write_and_read_int():
targets = [Foo(), Foo(), Foo()] # can only be generated here
for target in targets:
print(target)
@pytest.mark.asyncio
@given(int_datatype(target=target))
async def inner(value: int):
assert value == await target.bar(value)
await inner()

我正在使用:

python 3.9.4
  • pytest 7.1.2
  • pytest-asyncio 0.15.1
  • 假设6.49.1

我找到了一个通过https://hypothesis.readthedocs.io/en/latest/details.html#custom-function-execution导出的解决方案

class Foo:

async def bar(self, value):
return value
@st.composite
def int_datatype(draw, target):
return draw(st.integers())
def test_write_and_read_int():
targets = [Foo(), Foo(), Foo()] # can only be generated here
for target in targets:
class Inner:
@given(int_datatype(target))
async def inner(self, value):
assert value == await target.bar(value)
def execute_example(self, f):
asyncio.run(f())
Inner().inner()

最新更新