This page looks best with JavaScript enabled

Automated Testing in Django

 ·  ☕ 2 min read

Automated testing in Django can be done with doctests or unit tests. The logic of automated testing is to pass test data into the function under test, then use whether the output matches the expected result as the criterion for whether the test passes. There are a few key points here: (1) you need test data, (2) you need to identify the function under test, and (3) you need to give the expected result.

1. Test-Driven Development

tdd.png

Test-driven development is an iterative development cycle: write the automated test code first, then fill in the functionality.

  • Step one, write the test first
  • Step two, look at where the test fails
  • Step three, write enough code to make the test pass
  • Step four, test again
  • Step five, refactor the code
  • Step six, repeat the above

2. doctests

doctests is a testing module built into Python.

It consists of an ordinary part and an executable part.

  • The ordinary part is the comment section
  • The executable part is distinguished by the ‘»>’ (python shell prompt) or ‘…’ prompt.

doctest searches the docstrings of each module, class, and function, running each executable section as a single test example. It then compares the actual running value against the expected value as one run result.

myfunction.py

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-
import doctest

def add(x, y):
    """
    >>> add(1, 2)
    3
    """
    return x + y
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
python -m doctest -v myfunction.py

Trying:
    add(1, 2)
Expecting:
    3
ok
1 items had no tests:
    mytest
1 items passed all tests:
   1 tests in myfunction.add
1 tests in 2 items.
1 passed and 0 failed.
Test passed.

The -v parameter turns on verbose mode so you can see the details; without -v, there is no output at all when the test succeeds. If the test fails, an error report is printed.

3. unit tests

Django’s unit tests are implemented with classes.

When running tests, the test runner looks for unit test case classes (inheriting from TestCase) in test*.py files in the directory, and executes the functions starting with test inside the test class.

Django ships with some test helper classes, such as Test Client, TestCase, and Email Service. With Client you can conveniently issue a get or post request and get the response. TestCase is a wrapper around unittest.TestCase that saves a lot of repetitive code and adds a self.client. Email Service provides convenient methods for sending email.

3.1 How to Write Unit Tests

Testing the Model part

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django.test import TestCase
from .models import Fruit

class FruitTestCase(TestCase):
    # 初始化代码
    def setUp(self):
        Fruit.objects.create(name="apple", price=10)

    def test_fruit(self):
        fruit= Fruit.objects.get(name='apple')
        self.assertEqual(fruit.price, 10)

Testing the View part

1
2
3
4
5
6
from django.test import TestCase

class ViewTest(TestCase):
    def test_get(self):
        response = self.client.get('/fruit/1/')
        self.assertEqual(response.status_code, 200)

3.2 Running Unit Tests

1
2
3
4
5
6
# 搜索当前目录及子目录中test*.py文件,全部测试用例执行
python manage.py  test
# 运行某个测试类的全部用例
manage.py test myapp.FruitTestCase
# 运行某个测试类中某一个用例
manage.py test myapp.FruitTestCase.test_fruit

Django automatically creates test data in the Model and clears it after the test. If you want to keep the test data, pass the –keepdb parameter when running the unit tests.

4. References


WeChat Official Account
WRITTEN BY
WeChat Official Account