Skip to content

Instantly share code, notes, and snippets.

@aliceridgway
Created March 21, 2021 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aliceridgway/2f860b54f1649f6c63ee30c399065b35 to your computer and use it in GitHub Desktop.
Save aliceridgway/2f860b54f1649f6c63ee30c399065b35 to your computer and use it in GitHub Desktop.
Example of testing a view in Django
from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth import get_user_model
USER_MODEL = get_user_model()
class TestAddPostView(TestCase):
""" Things to test:
- Does the url work?
- If a user isn't logged in, are they redirected?
- Are the correct form fields displayed?
- When a post is saved, does it redirect to the preview page?
"""
@classmethod
def setUpTestData(cls):
cls.client = Client()
cls.url = reverse('add')
cls.user = USER_MODEL.objects.create_user(
email='janedoe@test.com',
first_name='Jane',
last_name='Doe',
username='user123',
password='password456'
)
def test_get_add(self):
""" Tests that a GET request works and renders the correct template"""
self.client.force_login(self.user)
response = self.client.get(self.url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'blog/add.html')
def test_user_must_be_logged_in(self):
""" Tests that a non-logged in user is redirected """
response = self.client.get(self.url)
self.assertEqual(response.status_code, 302)
def test_form_fields(self):
""" Tests that only title and body fields are displayed in the user form"""
self.client.force_login(self.user)
response = self.client.get(self.url)
form = response.context_data['form']
self.assertEqual(len(form.fields), 3)
self.assertIn('title', form.fields)
self.assertIn('body', form.fields)
def test_success_url(self):
""" Tests that submitting the form redirects to the draft page """
self.client.force_login(self.user)
form_data = {
'title':'my title',
'body':'This is the post body',
}
response = self.client.post(self.url, data=form_data)
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, '/user123/my-title/draft')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment