Using Gabbi and Hypothesis to Test Django APIs
by
In the world of testing it is important to write tests that are both easy to read and covering a wide range of scenarios. Often one of these will be sacrificed to facilitate the other. Here we discuss two tools that, when combined, will allow you to explore more of the test surface of your web API while still creating clear and maintainable tests.
Hypothesis
Hypothesis is a library that, when provided with a description of the parameters for your API, will explore many situations that will stress your system. Hypothesis uses "strategies" to inject parameters into your test cases, producing 200 different random example values.
from hypothesis import given
from hypothesis.strategies import floats
from my.module import add
@given(floats(), floats())
def test_float_addition_is_commutative(first, second):
assert add(first, second) == add(second, first)In general, we want to test properties of our methods using Hypothesis to avoid replicating the implementation in the test itself. This keeps tests clear and independent. For complex examples, such as encoding and decoding data, you should test that given a value, encoding and decoding returns the original result.