views:

318

answers:

4

This is a best-practices question.

When writing tests in Django, is it better to hard code urls in your tests.py, or to use the dispatch's reverse() function to retrieve the correct url?

Using hard-coded urls for testing only feels like the right way, but at the same time I can't think of a good enough argument for not using reverse().

Option A. reverse()

# Data has already been loaded through a fixture
def test_view_blog(self):
    url = reverse('blog', kwargs={'blog_slug':'test-blog'})
    response = self.client.get(url)
    self.failUnlessEqual(response.status_code, 200)

Option B. hard-coded

# Data has already been loaded through a fixture
def test_view_blog(self):
    url = '/blog/test-blog/'
    response = self.client.get(url)
    self.failUnlessEqual(response.status_code, 200)
+2  A: 

I've recently started using Twill via django-test-utils to unit test some of my Django work.

Instead of hardcoding URLs and/or using reverse I use things like twill.follow('Blog') (to follow a "Blog" link on the page).

This lets you really test the behavior of your website, just like a web browser would see it, and can catch things the other methods can't. For example, it would fail if you accidentally removed the "Blog" link from your navigation links.

Steve Losh
Conceptually this route makes a lot more sense to me. Yay, 2 more technologies to learn...
T. Stone
+1  A: 

I would recommend to use "Option A. reverse()" because it enables you to decouple your test from the location at which the view is mounted.

for example if '/blog/test-blog/' becomes '/blog/test-better-url-blog/' for test will still be pertinent.

yml
A: 

It is better to use the reverse function to get the urls by view names. This will not only test your views but also ensures that your view names keep the same.

See it as internal API testing. You would recognize if some of your URLs are broken and get reminded to update your {% url %} tags in the templates.

Gregor Müllegger
A: 

Why not do both twill.follow('Blog') & reverse()?

citadelgrad