[TIP] Testing django redirects/render

Carl Meyer carl at oddbird.net
Tue Apr 23 09:22:15 PDT 2013


Hi andrea,

On 04/23/2013 09:59 AM, andrea crotti wrote:
> Now I would also like to unit test the render and redirects, but I am a
> bit in trouble because for example redirects try to do a reverse
> routing, which then fails in the unit tests.
> 
> One way would be to mock redirect and just check that it gets called
> with the right arguments which would already be good enough, but maybe
> there are other ways?

Well, for a middle ground you could create a test URLconf and
temporarily set ROOT_URLCONF for the duration of the test. This isolates
your test from your real urlconf, but not from all the url-routing code.
In practice I think this is often the worst of both worlds; it won't be
any faster than using the real urlconf, but like mocking it introduces
the possibility of divergence. (Same discussion applies to template
rendering: replace "ROOT_URLCONF" with "TEMPLATE_DIRS" and "test
urlconf" with "test templates directory"). So I think your best choices
are to just mock redirect/render for a unit test, or only test your view
functions via integration tests.

I tend to do the latter. View functions (or controllers) are the
"integration" level of a web app. (In the terms Gary Bernhardt used in
his Boundaries talk at PyCon, they are the "imperative shell" as opposed
to the "functional core"). I find the best mileage in just minimizing
the amount of code (and especially the number of conditionals) at this
level, and then covering this code via integration tests only, rather
than brittle mock-heavy unit tests.

> I don't really want to use the django client, because it's too slow and
> they would not be unit tests anymore. In plus for integration tests I
> would rather spend time with selenium, that at least really checks the
> whole flow.

I find value in Python-level integration tests (though I prefer WebTest
to the Django test client) -- they are still an order of magnitude
faster than Selenium tests. Though the balance there does depend on how
heavy the client-side behavior is in the flows you need to test.

Carl



More information about the testing-in-python mailing list