Django Unit Test cases with Forms and Views

Reading Time : ~ .

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

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="", password="user", first_name="user", phone=12345678)

class User_Form_Test(TestCase):

    # Valid Form Data
    def test_UserForm_valid(self):
        form = UserForm(data={'email': "", '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="", 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 ="include url to post the data given", {'email': "", '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 ="include url to post the data given", {'email': "", '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 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 test
coverage report -m  # provides the report for the tests
    By Posted On

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Sorl-thumbnail to generate thumbnails in django Rakesh babu Podishetty

Displaying and Customizing the images in django with sorl-thumbnail.

Continue Reading...
What's great about Django girls to inspire women into programming Vinisha Naladala

Django girls is a non-profit organization, that helps women to learn Django programming language and to inspire them into programming. They are organizing workshops all ...

Continue Reading...
Integrate Django-Oscar-Accounts with Django-Oscar Shirisha Gaddi

This package uses double-entry bookkeeping where every transaction is recorded twice (once for the source and once for the destination). This ensures the books always ...

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