1

I have a problem with a test case as shown below. I want to test a function of class Foo, but I can't create any instance of class Foo until I create my test function. Then for creation test values for the test, I need the instance of Foo for hypothesis. I cannot do this at the top level of my test file, cause I haven't the Foo instance.

When I run pytest, I get the error: hypothesis.errors.InvalidArgument: Hypothesis doesn't know how to run async test functions like inner. No matter if with or without the decorator @pytest.mark.asyncio over the inner function it throws the error.

Has anyone had a similar case before and know how to fix it?

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()

I am using:

  • python 3.9.4
  • pytest 7.1.2
  • pytest-asyncio 0.15.1
  • hypothesis 6.49.1
Phil997
  • 575
  • 5
  • 15

1 Answers1

1

I found a solution derived with 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()
Phil997
  • 575
  • 5
  • 15