Search code examples
python-hypothesis

Use subclass class variables with pytest hypothesis tests


In the following example, how can I use the new value of t (bool) in TestBool with test_subclass in TestInt?

from hypothesis import given, strategies as st

class TestInt:
    t = int

    @given(u=st.just(t))
    def test_subclass(self, u):
        assert issubclass(u, int)

class TestBool(TestInt):
    t = bool

Solution

  • In an immediate sense, this doesn't work as you'd hoped because the decorator on test_subclass is evaluated when TestInt is defined, and then the decorated method is inherited by TestBool. There are a few ways you could get around this immediate problem.

    However, I strongly recommend against inheriting methods decorated with @given() - there are so many ways for that to go subtly (or very obviously) wrong that we implemented a health check to warn against it. Better to refactor your tests to avoid this kind of inheritance.