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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With