I started using hypothesis to write my tests. I like it, but I am stuck to generate some kind of data.
I have a test that use list of data, which can be constructed from tuple(key, value).
Key can be text, integer or float, value can be anything comparable. For one test, all keys must be the same type, and all values must be the same type.
The only way I found to generate data I want is something like that:
@given(
st.one_of(
st.lists(st.tuples(st.integers(), st.integers())),
st.lists(st.tuples(st.integers(), st.floats())),
st.lists(st.tuples(st.integers(), st.text())),
st.lists(st.tuples(st.floats(), st.integers())),
st.lists(st.tuples(st.floats(), st.floats())),
st.lists(st.tuples(st.floats(), st.text())),
#...
))
def test_stuff(lst):
data = [Mydata(k, v) for k, v in lst]
#...
Is there a better way to generate all data type combination I want to test ?
My preferred way to do this is to choose the key and value strategies in @given
, then construct your strategy and draw from it inside your test. The "all keys must be of the same one of these types" thing is an unusual requirement, but interactive data is very powerful:
@given(
st.data(),
key_st=st.sampled_from([st.integers(), st.floats(), st.text()]),
value_st=st.sampled_from([st.integers(), st.floats(), st.text()]),
)
def test_stuff(data, key_st, value_st):
test_data = data.draw(st.lists(st.builds(Mydata, key_st, value_st)))
... # TODO: assert things about test_data
I've also used st.builds()
rather than going via tuples - since we're calling it inside the test, any exceptions in Mydata
will be (minimised) test failures rather than errors.