Search code examples
pythontestingdjango-testingdjango-2.1

Is there a better way to write these tests?


So basically, the test works, it says OK when I put into the console

python3 manage.py test apps/diary

but the thing is that, when I check other sources, especially W.S. Vincent's(https://wsvincent.com/) way of doing tests, it's quite cleaner; it doesn't have to bother whether the session creating an object is authenticated or not, or so I think.

So in my code, these are all just some sort of makeshifts of what's supposed to be a well-written test, just because I can't think of another way of doing it. I have read this 'best practices' article in testing like in https://realpython.com/testing-in-django-part-1-best-practices-and-examples/, but it still don't find it helpful.

Here's a snippet of my code, a Test class: class DetailViewTest(TestCase):

def setUp(self):
    self.user = get_user_model().objects.create_user(
        username='testuser', email='[email protected]',
        password='secretpw', first_name='John',
        last_name='Doe'
    )
    self.client.force_login(self.user)
    self.client.post(reverse('diary:add'), {
        'title': 'Test Title',
        'author': self.user,
        'content': 'Loren ipsum'
    })
    self.client.logout()
    self.user2 = get_user_model().objects.create_user(
        username='testuser2', email='[email protected]',
        password='secretpw', first_name='John',
        last_name='Doe'
    )
    self.client.force_login(self.user2)
    self.client.post(reverse('diary:add'), {
        'title': 'Test Title',
        'author': self.user,
        'content': 'Loren ipsum'
    })
    self.client.logout()

def test_view_url_exists_at_proper_location(self):
    self.client.force_login(self.user)
    response = self.client.get('/post/1/')
    self.assertEqual(response.status_code, 200)

def test_view_uses_correct_template(self):
    self.client.force_login(self.user)
    response = self.client.get('/post/1/')
    self.assertEqual(response.status_code, 200)
    self.assertTemplateUsed(response, 'diary/post_detail.html')

def test_cannot_view_others_post(self):
    self.client.force_login(self.user2)
    response = self.client.get('/post/1/')
    self.assertEqual(response.status_code, 404)

(here's the full code anyway: https://pastebin.com/6ufabmJP)

Also, I've been wondering if it's okay to inherit Test classes to others, or if I always have to login before creating a db object, and if I always have to create a user before being able to login.

help and tips would be absolutely appreciated. thanks~


Solution

  • Thats really a broad question. I highly recommend this post about how to write good tests in Django-Projects:

    https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing

    It gives you great examples for testing views, like you’re trying in your snippet.