Skip to content

Django 单元测试

1.在Django的指定moudel中,找到tests.py文件,要写的单元测试就在这里

执行目录下所有的测试(所有的test*.py文件):

$ python manage.py test

执行animals项目下tests包里的测试:

$ python manage.py test animals.tests

执行animals项目里的test测试:

$ python manage.py test animals

单独执行某个test case:

$ python manage.py test animals.tests.AnimalTestCase

单独执行某个测试方法:

$ python manage.py test animals.tests.AnimalTestCase.test_animals_can_speak

为测试文件提供路径:

$ python manage.py test animals/

通配测试文件名:

$ python manage.py test --pattern="tests_*.py"

启用warnings提醒:

$ python -Wall manage.py test

2.在控制台或者cmd中,执行python manage.py test就可以执行单元测试文件了

注意:

测试是需要数据库的,django会为测试单独生成数据库。不管你的测试是否通过,当你所有的测试都执行过后,这个测试数据库就会被销毁。

默认情况下,测试数据库的名字是test_DATABASE_NAME,DATABASE_NAME是你在settings.py里配置的数据库名.如果 你需要给测试数据库一个其他的名字,在settings.py中指定TEST_DATABASE_NAME的值。使用sqlite3时,数据库是在内存中创建的。

除了数据库是单独创建的以外,测试工具会使用相同的数据库配置--DATABASE_ENGINE, DATABASE_USER, DATABASE_HOST等等.创建测试数据库的用户DATABASE_USER(settings中)指定,所以你需要确认 DATABASE_USER有足够的权限去创建数据库。

可以在settings.py中添加一句话让数据库的操作变快:

TEST_RUNNER = 'django.test.runner.DiscoverRunner'

其实也没快多少...

3.如何开始单元测试

首先找到你的tests.py 创建一个类,大概什么样那?

python
from django.test import TestCase

# Create your tests here.

class MyTestCase(TestCase):

	#固定的开始方法,名称都不能变
    def setUp(self):
        print("kais")

    #固定的结束方法,名称也不能变
    def tearDown(self):
        print("结束")

	#所有的测试方法名称都要以"test_"开头
    def test_aaaa(self):
        print("aaa")

4.我们要测试什么东西

先来个接口测试下 http://localhost:8000/approval/jump_requisition_page

请求地址:approval/jump_requisition_page

python
#跳转请求页面
def test_jump_requisition_page(self):
    r = self.client.get("/approval/jump_requisition_page")
    print(r.status_code)

打印结果是301

5.如何保证你的测试是正确的

断言来了!!!

python
#跳转请求页面
def test_jump_requisition_page(self):
    r = self.client.get("/approval/jump_requisition_page")
    print(r.status_code)
    #通过断言来判断是否合格,改成300再测试下
    self.assertEqual(301,r.status_code)

两条测试通过.

改成300的时候就会出现报错信息

6.再测试下登录模块

python
#登录测试
def test_login(self):
    r = self.client.get("/login/")
    # print(r.status_code)
    self.assertEqual(200,r.status_code)


#用户登录,带参数的form提交
def test_check_login(self):
    data = {
        "username":"zhangsan",
        "password":"123456"
    }
    r = self.client.post("/login/check_login/",data=data)
    print(r.status_code)

注意:如果说给的data有问题的话,会报出一个很严重的错误,现在把password中的w给去掉,然后执行测试.

D:\unicom>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced).

.E.

ERROR: test_check_login (login.tests.LoginTestCase)

Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py", line 83, in _ getitem_ list_ = super(MultiValueDict, self).getitem(key) KeyError: 'password'

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "D:\unicom\login\tests.py", line 22, in test_check_login r = self.client.post("/login/check_login/",data=data) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\test\client.py", line 548, in post secure=secure, **extra) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\test\client.py", line 350, in post secure=secure, **extra) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\test\client.py", line 416, in generic return self.request(**r) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\test\client.py", line 501, in request six.reraise(*exc_info) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\six.py", line 686, in reraise raise value File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 41, i n inner response = get_response(request) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 187, in _g et_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 185, in g et_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\unicom\login\views.py", line 61, in check_login password = request.POST['password'] File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py", line 85, in _ getitem raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'password'"


Ran 3 tests in 0.314s

FAILED (errors=1) Destroying test database for alias 'default'...

7.生成测试报告,html版

coverage report -m 控制台打印

coverage html 生成html报告