Test Cases For Forms, Views

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

Having tests for any project will helps you to structure good code, find bugs. If a specific function breaks, you will know about it. Tests also make debugging breaks in code much easier.

Django’s Unit Tests uses a Python standard library module: unit test. This module defines tests using a class-based approach.

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

Test Case: A test case is the smallest unit of testing. It checks for a specific response to a particular set of inputs.

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. You not only need to test for expected results but also how well your code handles unexpected results also.

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 allow you to define instructions that will be executed before and after each test method.

Every TestCase method should start with "test", because When you run your tests, the default behavior of the test utility is to find all the test cases in any file whose name begins with test, automatically build a test suite out of all test cases, and run that suite.

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})

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

Here assertTrue() or assertFalse() to verify a condition, which returns "True" or "Flase"

Here the above functions in class "User_Form_Test" returns "True" or "False" it depends on the data given.

Testing the Views:

While testing the views, we test for the response codes, and then we test the actual response.

First, we check for user is logged in then, we fetch the URL from the client, store the results in the variable and then test our assertions.

class User_Views_Test(SetUp_Class):

    def test_home_view(self):
        user_login = self.client.login(email="user@mp.com", password="user")
        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(): Asserts that the template with the given name was used in 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

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
Latest Comments
Related Articles
Sending emails using sendgrid on heroku for a Django App Vinisha Naladala

Integrate Sendgrid API to your Heroku app to deliver simplified emails like any notification emails, user signups etc.

Continue Reading...
Creating Django App Siva Chittamuru

Django is a high-level, free and open-source Python Web framework that encourages rapid development. Django follows the model–view–controller (MVC) architectural pattern. Django's primary goal is ...

Continue Reading...
Django - migrating from function based views to class based views Anjaneyulu Batta

The single most significant advantage in Django class-based views is inheritance. On a large project it's likely that we will have lots of similar views. ...

Continue Reading...