【編程語言-python】Django單元測試學習小結

django單元測試框架:

編寫測試用例:

  1. 用例編寫:

django.test繼承了python標準庫unittest,因此本身的測試用例類繼承django.test.TestCase便可:python

from django.test import TestCase
class MyClassTestCase(TestCase):
    def SetUp(self):
        # 環境構造
        pass
    def test_my_func(self):
        # 測試my_func方法
        pass
複製代碼

如示例,通常一個測試用例類對應一個業務類,在這個測試類中完成對該業務類中各方法的單元測試。shell

  1. Client使用:

主要用於模仿url請求,調用並返回請求結果。django

response = self.client.get('/vpc/list')
self.assertEquals(response.status_code, 302)
複製代碼
  1. RequestFactory使用:

主要用於構造request對象,與Client對比,沒有發生url接口的調用。json

request = self.request_factory.post('vpc/list', data={'start': 0, 'length': 10})
vpc_manage = VpcManage(request)
複製代碼
  1. 斷言(Assertions):

判斷用例執行結果的主要手段,斷言測試函數返回結果跟預期結果的一致性。segmentfault

self.assertEquals(res['recordsTotal'], 0)
複製代碼

使用Mock打樁:

因爲單元測試主要測試的是函數級功能,因此須要經過mock對待測函數中調用到的方法進行打樁,返回便於測試的值。bash

vpc_manage.get_user_info = mock.Mock(
    return_value=mock.Mock(**self.user_info_attrs))
res = vpc_manage.vpc_list()
res = json.loads(res)
複製代碼

用例執行:

1. 僅執行用例:

python manage.py test -v 2
複製代碼

2. 覆蓋率統計:

  • 安裝coverage包:
pip install coverage
複製代碼
  • 執行用例
coverage run --source '.' manage.py test -v 2
複製代碼
  • 查看覆蓋率:
coverage report
複製代碼

Name Stmts Miss Cover authclient/init.py 2 0 100% authclient/authexception.py 12 4 67% authclient/authuser.py 81 62 23% authclient/decorators.py 81 48 41% authclient/settings.py 26 4 85% authclient/test.py 9 0 100% authclient/urls.py 4 0 100% authclient/views.py 28 21 25% libs/init.py 0 0 100% libs/ac_config.py 6 0 100% libs/agile_controller.py 464 333 28% libs/constants.py 17 0 100% libs/json_helper.py 19 5 74% libs/logger.py 39 22 44% libs/mongo_tool.py 43 21 51% manage.py 13 6 54% project/init.py 0 0 100% project/settings.py 24 0 100% project/urls.py 3 0 100% project/wsgi.py 4 4 0% vpc/init.py 0 0 100% vpc/admin.py 4 0 100% vpc/apps.py 4 4 0% vpc/forms.py 173 90 48% vpc/manage.py 1079 812 25% vpc/migrations/0001_initial.py 8 0 100% vpc/migrations/init.py 0 0 100% vpc/models.py 206 11 95% vpc/tasks.py 5 5 0% vpc/tests/init.py 0 0 100% vpc/tests/test_router_manage.py 13 0 100% vpc/tests/test_views.py 24 6 75% vpc/tests/test_vpc_manage.py 80 0 100% vpc/urls.py 3 0 100% vpc/views.py 168 118 30% TOTAL 2642 1576 40%app

參考文檔:

相關文章
相關標籤/搜索