1. 程式人生 > >django的單元測試框架unittest

django的單元測試框架unittest

self 文件名 訪問 produce print lte setup www. clas

django的單元測試

指定測試範圍:

  • 指定運行某些測試文件./manage.py test --pattern="tests_*.py" -v 2
  • 運行所有測試文件./manage.py test -v 2
  • # Run all the tests in the animals.tests module
    $ ./manage.py test animals.tests
    
  • # Run all the tests found within the ‘animals‘ package
    $ ./manage.py test animals
    
  • # Run just one test case
    $ ./manage.py test animals.tests.AnimalTestCase
    
  • # Run just one test method
    $ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak

臨時數據庫:

運行時會臨時創建數據庫,運行結束後刪除,數據庫名字:test_用到的數據庫。猜測是使用migragtion文件創建的

舉例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    @Author      : 
    @Date        : 2019-01-02 22:48
    @Description : 本文件的作用描述
    @File        : test_demo.py 
""" from unittest.mock import patch from django.test import TestCase import os def multiple(a, b): return a * b class Calculator(object): def add(self, a, b): return a+b def is_error(self): try: os.mkdir("11") return False except Exception
as e: return True def multiple(self, a, b): return a * b # Mock一個函數。 class TestOneFunc(TestCase): # 指定函數的寫法:要先寫當前文件名,即module name @patch(test_demo.multiple) def test_multiple(self, mock_multiple): mock_multiple.return_value = 3 self.assertEqual(multiple(8, 14), 3) class TestProducer(TestCase): def setUp(self): self.calculator = Calculator() # Mock的函數每次被調用返回不同的值 @patch.object(Calculator, add) def test_effect(self, mock_add): # 註意list的順序要和後面的順序一一對應 mock_add.side_effect = [1, 2, 3] self.assertEqual(self.calculator.add(8, 14), 1) self.assertEqual(self.calculator.add(8, 14), 2) self.assertEqual(self.calculator.add(8, 14), 3) # Mock一個對象裏面的方法 @patch.object(Calculator, add) def test_add1(self, mock_add1): # 模擬add函數的返回值為3,所以不管真實結果是否是3,都沒有影響 mock_add1.return_value = 3 self.assertEqual(self.calculator.add(8, 14), 3) # 讓Mock的函數拋出exception @patch(os.mkdir) def test_exception(self, mock_mkdir): mock_mkdir.side_effect = Exception self.assertEqual(self.calculator.is_error(), True) # Mock多個函數,主要是註意順序 @patch.object(Calculator, add) @patch.object(Calculator, multiple) def test_both(self, mock_multiple, mock_add): mock_add.return_value = 1 mock_multiple.return_value = 2 self.assertEqual(self.calculator.add(8, 14), 1) self.assertEqual(self.calculator.multiple(8, 14), 2) class ClassTemplate(object): def __init__(self, name): # __name c是私有變量,只有類本身可以訪問,子類也不可以訪問 # _name 是受保護變量,類本身和子類可以訪問,from module import *無法導入 # decorator/叠代器/yield/ self.__name = name def run(self): print("my name is %s" % self.__name) @staticmethod def staticmethod(value): print("my value is {}".format(value)) if __name__ == __main__: ClassTemplate(a_name).run() ClassTemplate.staticmethod(a_value)

參考:

1、https://www.jianshu.com/p/b87d7b4a222a

2、https://segmentfault.com/a/1190000002965620

3、https://docs.python.org/3.7/library/unittest.mock.html

4、https://docs.djangoproject.com/zh-hans/2.1/topics/testing/overview/

django的單元測試框架unittest