Django Unit Test cases with Forms and Views

Reading Time : ~ .

Test Cases For Forms, Views

In this post, we’ll see how to write unit test cases for any project.

Having tests for any project will helps you to find bugs. If any of the function breaks, you will know about it. Its easier to debug code line by line.

Unit Tests: Unit Tests are isolated tests that test one specific function.

Test Case: A test case is executing set of features for your Application. Proper development of test cases finds problems in your functionality of an Application.

Test suite: A test suite is a collection of test cases. It is used to aggregate tests that should be executed together.

In general, tests result in either a Success (expected results), Failure (unexpected results), or an error. While writting test cases, not only testing for the expected results but also need to test how good your code handles for unexpected results.

Testing the Forms:

Consider a Form:

from django import forms
from .models import *

    class UserForm(forms.ModelForm):
       class Meta:
          model = User
          fields = ('email', 'password', 'first_name', 'phone')

setUp(): The setUp() methods allows to define instructions which will be executed before and after each test method.

Every TestCase method should start with "test", because When you run your tests, the default behaviour of the test utility is to find all the test cases in all your files, function name starts with test, which automatically build a test suite out for all test cases, and run.

For Testing any Form, In "Setup_Class" we create required objects here, and will test whether the created object details matched or not.

Write in your tests.py

from django.test import TestCase
from django.test import Client
from .forms import *   # import all forms

class Setup_Class(TestCase):

    def setUp(self):
        self.user = User.objects.create(email="user@mp.com", password="user", first_name="user", phone=12345678)

class User_Form_Test(TestCase):

    # Valid Form Data
    def test_UserForm_valid(self):
        form = UserForm(data={'email': "user@mp.com", 'password': "user", 'first_name': "user", 'phone': 12345678})
        self.assertTrue(form.is_valid())

    # Invalid Form Data
    def test_UserForm_invalid(self):
        form = UserForm(data={'email': "", 'password': "mp", 'first_name': "mp", 'phone': ""})
        self.assertFalse(form.is_valid())

assertTrue() or assertFalse() functions is to verify condition which returns "True/False"

In the above functions in class "User_Form_Test" returns True/False based on the input data given.

Testing the Views:

When we start testing the vews, first test for the response codes then we got with the actual response.

class User_Views_Test(SetUp_Class):

    def test_home_view(self):
        user_login = self.client.login(email="user@mp.com", password="user")
        self.assertTrue(user_login)
        response = self.client.get("/")
        self.assertEqual(response.status_code, 302)

    def test_add_user_view(self):
        response = self.client.get("include url for add user view")
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "include template name to render the response")

    # Invalid Data
    def test_add_user_invalidform_view(self):
        response = self.client.post("include url to post the data given", {'email': "admin@mp.com", 'password': "", 'first_name': "mp", 'phone': 12345678})
        self.assertTrue('"error": true' in response.content)

    # Valid Data
    def test_add_admin_form_view(self):
        user_count = User.objects.count()
        response = self.client.post("include url to post the data given", {'email': "user@mp.com", 'password': "user", 'first_name': "user"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(User.objects.count(), user_count+1)
        self.assertTrue('"error": false' in response.content)

assertEqual(): assertEqual() to check for an expected result.
assertTemplateUsed(): This Assert is used for rendering the response.

Command line usage to Run the tests:

    python manage.py test

Third-party package:

Coverage: It is a tool used for measuring the effectiveness of tests, showing the percentage of your codebase covered by tests.

Installation: Pip install coverage

Use "coverage run" to run your program and gather data:

coverage run manage.py test
coverage report -m  # provides the report for the tests
    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Preserve file names with sorl for better SEO Ashwin Kumar

We use sorl-thumbnail for scaling images by keeping the original one intact. Sorl proven to be great tool for generating different sized images throughout website. ...

Continue Reading...
Multifactor Authentication with Django MFA using Google Authenticator Vinisha Naladala

Use Django Multi-Factor Authentication method to verify user identity with more than one authentication methods. It can be used for user login, any transactional methods ...

Continue Reading...
Add captcha to django web page using Python-reCaptcha Divya Sri

Python-reCaptcha is a pythonic and well-documented reCAPTCHA client that supports all the features of the remote API to generate and verify CAPTCHA challenges. To add ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties