Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 251
idetyp Avatar asked Sep 03 '19 10:09

idetyp


2 Answers

Strategies are designed as composable objects, there is no problem with reusing them.

Thus an alternative to the accepted answer simply store configured sub-strategies as reusable globals e.g.

a_strategy = st.fixed_dictionaries({ "test1": st.just("name"), "test2": st.integers()})

@given(some_dict=a_strategy)
def test_uses_some_dict_to_initialize_object_im_testing(some_dict):
    ...

@given(some_dict=a_strategy, value=st.integers())
def test_other(some_dict, value):
    ...

The timezones examples shows that pattern, it defines an aware_datetimes strategy and uses that strategy in multiple tests, composed with a variable number of siblings.

like image 172
Masklinn Avatar answered Sep 27 '22 18:09

Masklinn


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
like image 43
sanyassh Avatar answered Sep 27 '22 17:09

sanyassh