One of the best tests to do in Django is a view test. It exercises a lot of code, but it doesn’t require a lot of effort, as far as system tests go.

But these tests can seem to be very not DRY. Hypothesis is meant to make your tests more robust, but it also lets you make your tests less redundant. So here’s an approach that I took to cut down on the testing of views in Django.

Some commentary on what’s going on here. In the ViewsTestCase class, I setup two lists, `PUBLIC_URLS` and `PRIVATE_URLS`, and I made some convenience methods for testing to make my tests a little more readable.

Then I sub-classed the ViewsTestCase for two different user cases; those logged in and those who are not.

Finally, we start to get to the bit of magic that Hypothesis provides:

@given(url_name=st.sampled_from(ViewsTestCase.PUBLIC_URLS))

def test_public_urls(self, url_name):

self.assert_200_response_code(url_name)

So this is very dense, but basically, the code is saying this: please select a value from the PUBLIC_URLS list to pass in as the variable `url_name`. It passes in all the way down to the assert convenience method I wrote.

This seems kind of silly at first. I don’t want to test just one value. I want to test them all.

However, since this is a decorator, it’s not done. Hypothesis will keep testing this test trying to find a falsifying example. Since my list is relatively short, it’ll test all of the urls in PUBLIC_URLS. (By default, it’ll look for at max 200 examples.)