Python Unit Testing
It is used for a module, a class or a function for checking the correctness of the test work.
In Python unittest is its built-in unit testing framework for unit tests and functional tests are an essential part of the daily development.
For example, a function abs (), we can write about a few test cases:
- Enter a positive number, such as 1,1.2,0.99, we look forward to the return value is the same as the input
- Enter a negative number, such as -1, -1.2, -0.99, and we look forward to the return value of the input value opposite
- Enter 0, we look forward to the return 0
- Input non-numeric type, such as None, [], {}, we expect throw TypeError
The above test cases into a test module inside, is a complete unit testing.
A simple test case
Define a class, two simple implementation methods add, sub, and subjected to the test unit
To be tested file m1.py
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 5 class MyClass(object): 6 def __init__(self, x, y): 7 self.x = int(x) 8 self.y = int(y) 9 10 def add(self): 11 return self.x + self.y 12 13 def sub(self): 14 return self.x - self.y
Test.py create test files in the same directory m1.py, using the unittest framework for unit testing method for testing MyClass
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import unittest 5 from m1 import MyClass 6 7 8 class MyclassTest(unittest.TestCase): 9 def setUp(self): 10 self.calc = MyClass(7, 5) 11 12 def tearDown(self): 13 pass 14 15 def test_add(self): 16 ret = self.calc.add() 17 self.assertEqual(ret, 12) 18 19 def test_sub(self): 20 ret = self.calc.sub() 21 self.assertEqual(ret, 2) 22 23 24 # if __name__ == '__main__': 25 # suite = unittest.TestSuite() 26 # suite.addTest(MyclassTest('test_add')) 27 # suite.addTest(MyclassTest('test_sub')) 28 # 29 # runner = unittest.TextTestRunner() 30 # runner.run(suite) 31 32 if __name__ == '__main__': 33 unittest.main()
Run the test
1 python -m unittest test 2 .. 3 ---------------------------------------------------------------------- 4 Ran 2 tests in 0.000s 5 6 OK
to sum up:
When writing unit tests, we need to write a test class that inherits from unittest.TestCase, unittest.TestCase provides many built-in condition judge, we only need to call these methods can assert whether the output is what we expect. The most common assertion is assertEqual () method
Running unit tests:
1 Once you have written a good unit tests, we can run the unit tests. The simplest mode of operation is in the last two lines of code plus the test.py: 2 IF the __name__ == ' __main__ ' : . 3 unittest.main () . 4 so as to be normal to test.py python script: 5 $ the test.py Python . 6 another method is by the command line parameter - the unittest unit tests run directly m: . 7 $ -m Python the unittest test
unittest framework little knowledge carding
1. test fixture: test data to initialize and clean up the environment and to achieve TestCase by overriding the setUp () and tearDown () method
Using two methods: Imagine you need to start a test database, then, can connect to the database setUp () method, close the database, so that no need to repeat the same process for each test code tearDown () method:
1 class MyclassTest(unittest.TestCase): 2 3 def setUp(self): 4 print('setUp...') 5 6 def tearDown(self): 7 print('tearDown...')
2.test case: test case
3.test suite: a set of test cases, by addTest loaded into TestSuite TestCase, returns an instance of TestSuite
4.test runner: running test and returns the result, is performed by a test suite or test case based TextTestRunner run () method provides
note:
Unit testing by the program does not mean that there is no bug, but certainly not by a program bug
Django unit test
When creating the app automatically generates tests.py file in the app directory
Model section unit test
1 from django.db import models 2 3 # Create your models here. 4 5 6 class Book(models.Model): 7 title = models.CharField(max_length=32) 8 price = models.DecimalField(max_digits=10, decimal_places=2)
Test Case Code
1 from django.test import TestCase 2 from app01.models import Book 3 # Create your tests here. 4 5 6 class BookModelTest(TestCase): 7 def setUp(self): 8 Book.objects.create(title='斗破苍穹', price=10.99) 9 10 def test_book_model(self): 11 from decimal import Decimal 12 result = Book.objects.get(title='斗破苍穹') 13 self.assertEqual(result.price, Decimal('10.99'))
Run a test run under the project directory:
1 python manage.py test 2 Creating test database for alias 'default'... 3 System check identified no issues (0 silenced). 4 . 5 ---------------------------------------------------------------------- 6 Ran 1 test in 0.002s 7 8 OK 9 Destroying test database for alias 'default'...
View of a portion unit test
1 from django.shortcuts import render 2 3 # Create your views here. 4 5 6 def index(request): 7 return render(request, 'index.html')
Add the code in the test case app01 / tests.py file:
. 1 class IndexPageTest (TestCase): 2 "" " Test index page " "" . 3 DEF test_index_page_renders_index_template (Self): . 4 "" " Test index view " "" . 5 Response = self.client.get ( ' / index / ' ) . 6 self.assertEqual (response.status_code, 200 is) # Analyzing status code . 7 self.assertTemplateUsed (Response, ' index.html ' ) # determines whether the correct template rendered
Running unit tests:
1 python manage.py test 2 Creating test database for alias 'default'... 3 System check identified no issues (0 silenced). 4 .. 5 ---------------------------------------------------------------------- 6 Ran 2 tests in 0.044s 7 8 OK 9 Destroying test database for alias 'default'...