I am working my way through a Django book and part of that covers the test cases. In the current chapter I have the following code form the start of the test cases but some of it feels like it breaking the DRY principle.

from django.test import TestCase, SimpleTestCase
from django.contrib.auth import get_user_model
from django.urls import reverse

# Create your tests here.
class HomePageTests(SimpleTestCase):
    def test_home_page_status_code(self):
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)

    def test_view_url_by_name(self):
        response = self.client.get(reverse('home'))
        self.assertEqual(response.status_code, 200)

    def test_view_uses_correct_template(self):
        response = self.client.get(reverse('home'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'home.html')

I understand the difference between the first and second test case. One is testing the path explicitly the second is testing against the name look up that some of my views might use. However In the third test it feels to me a bit redundant to again test the status code of the response object from the reverse look up when we just tested that functionality in the previous test case.

Is there a particular benefit to testing the status code again on the reverse look up in the third test case.

Also given that the second and third test case are calling for the exact same get response couldn't this be taken out the methods and stored in the class its self so its only run once, or at least set the reverse_path look up once. Again is there any specific reason or benefit of calling it each time in the individual test cases.

  • \$\begingroup\$ There's definitely something fishy going on here, but is this your code or the code from the book? \$\endgroup\$
    – Mast
    Jan 13, 2020 at 21:14
  • \$\begingroup\$ This is the code from the book. \$\endgroup\$ Jan 13, 2020 at 21:15
  • \$\begingroup\$ Since Code Review is a community where programmers improve their skills through peer review, we require that the code be posted by an author or maintainer of the code and that the poster know why the code is written the way it is. Why was it written like this? Probably because it's an educational book that wants to focus more on getting things done than on DRY. \$\endgroup\$
    – Mast
    Jan 13, 2020 at 21:17
  • \$\begingroup\$ Please take a look at our help center. \$\endgroup\$
    – Mast
    Jan 13, 2020 at 21:18


Browse other questions tagged or ask your own question.