Django Unit Test Example

When you create website use Django, you should want to run unit test in it to verify website functions or models. This article will show you how to write and run unit test in Django web application. This example is based on Django Bootstrap3 Example, so if you want to learn more code about this example, please refer that article first.

1. Where To Write Django Unit Test Code.

django project app dept_emp source files structure

When you create the Django project in PyCharm, it will create a file in the application folder. This file is just where the Django application unit test source code saved. Double click the dept_emp / file to edit it and input below source code in it.

2. How To Write Django Unit Test Code.

  1. Import django.test.TestCase class in file. django.test.TestCase is a subclass of unittest.TestCase.
  2. Create a subclass of django.test.TestCase.
    class ModelTest(TestCase):
  3. Add test functions in the Django test case class, and implement class level or instance level setup or teardown methods.
  4. In the example setUpClass method, we create Department, User and Employee model objects.
  5. In the example test functions method, we retrieve the added Department and Employee model objects and verify the department description and employee username.
  6. When you run below Django app test case, because it manipulate models, so the test case will create a temporary database to save the test data, and destroy the temporary database after all test function’s execution. The temporary database is separated from the project real database, so the test data will not pollute the app real database. If you meet any error, please read article How To Fix User Matching Query Does Not Exist Error In Django Unit Test.

from django.test import TestCase
from django.contrib.auth.models import User
from dept_emp.models import Department, Employee

class ModelTest(TestCase):

    def setUpClass(cls):

        # below code will fix AttributeError: type object 'Model Test' has no attribute 'cls_atomics' error.
        super(ModelTest, cls).setUpClass()

        # create and save a Department object.
        dept = Department(dept_name='QA', dept_desc='Quality Assurance')

        # create a User model object in temporary database.
        user = User(username='tom', password='tom')

        # get employee user.
        user = User.objects.get(username='tom')
        print('Added user data : ')
        # get employee department.
        dept = Department.objects.get(dept_name='QA')
        print('Added department data : ')
        # create and save the Employee object.
        emp = Employee(user=user, dept=dept, emp_mobile='1381998982289', emp_salary=8000)
        print('Added employee data : ')

    def test_department_models(self):
        dept = Department.objects.get(dept_name='QA')
        self.assertEqual(dept.dept_desc,'Development department')

    def test_employee_models(self):
        emp = Employee.objects.get(emp_mobile='1381998982289')
        self.assertEqual(emp.user.username, 'tom')

2. Run Django Unit Test.

  1. Open a terminal and cd into the Django project root folder( DjangoHelloWorld in this example ).
  2. Run python3 test dept_empthen you will see below unit test output. From the output, we can see that the unit test create the temporary database at beginning and destroy it at the ending.
    Creating test database for alias 'default'...
    System check identified some issues:
    ?: (urls.W001) Your URL pattern '^$' uses include with a route ending with a '$'. Remove the dollar from the route to avoid problems including URLs.
    System check identified 1 issue (0 silenced).
    Added user data : 
    Added department data : 
    QA,Quality Assurance
    Added employee data : 
    FAIL: test_department_models (dept_emp.tests.ModelTest)
    Traceback (most recent call last):
      File "/Users/zhaosong/Documents/WorkSpace/", line 40, in test_department_models
        self.assertEqual(dept.dept_desc,'Development department')
    AssertionError: 'Quality Assurance' != 'Development department'
    - Quality Assurance
    + Development department
    Ran 2 tests in 0.008s
    FAILED (failures=1)
    Destroying test database for alias 'default'...


  1. How To Run Unit Test Use External CSV Test Data In Python
0 0 vote
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x