Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Testing - Hard code URLs or Not

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)
like image 884
T. Stone Avatar asked Oct 15 '09 20:10

T. Stone


People also ask

Why hard coded URLs are bad?

Why are hard coded URLs bad? Changes require code update: If we need to update any micro service URL in our project, we use hard coded URLs then it is very difficult to change that URL because we need to write the all location which uses that URL in our project manually.

What is a hard coded URL?

a) A hard-coded reference is a URL that contains the instance name in the URL (e.g. na1.salesforce.com). Replace these hard-coded references with generic, non-instance specific or relative URLs (e.g. login.salesforce.com or <mydomain>. my.salesforce.com).

Which function in the Django URLs package can help you avoid Hardcoding URLs?

Django Redirects: A Super Simple Example To avoid hard-coding the URL, you can call redirect() with the name of a view or URL pattern or a model to avoid hard-coding the redirect URL. You can also create a permanent redirect by passing the keyword argument permanent=True .


1 Answers

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.

like image 60
yml Avatar answered Oct 11 '22 07:10

yml