Search code examples
pythonpython-hypothesis

Hypothesis - reuse @given between tests


I've been using hypothesis for some time now. I'm wondering how I could reuse @given parts.

Some of the ones I have are like 20 lines and I copy the whole @given part above a couple of the test cases.

A simple example of a test

@given(
    some_dict=st.fixed_dictionaries(
        {
            "test1": st.just("name"),
            "test2": st.integers()
            }
        )
    )
def test_that uses_some_dict_to_initialize_object_im_testing(some_dict):
    pass

What would be the best way to go around reusing @given blocks?


Solution

  • Create your own decorator:

    def fixed_given(func):
        return given(
            some_dict=st.fixed_dictionaries(
                {
                    "test1": st.just("name"),
                    "test2": st.integers()
                }
            )
        )(func)
    
    
    @fixed_given
    def test_that_uses_some_dict_to_initialize_object_in_testing(some_dict):
        pass