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().
# 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)
# 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)
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.
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).
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With