Django笔记5-测试类 test


首先django中有3个测试cmd命令。

1.python manage.py test:执行所有的测试用例

2.python manage.py test app_name:执行该app的所有测试用例

3.python manage.py test app_name.case_name: 执行指定的测试用例,该条可用于只测试tests.py中的一个类 (实际测试无效果.过会再试)


对models中的方法进行测试

1.在app路径下的tests.py中添加一个测试类

2.编写测试的方法.要以test为前缀开头,并继承TestCase 这相当于python中的unittest

3.对需要预料到的结果进行断言测试.这里用的例子是对Question模块中was_published_recently()方法进行单元测试


Django笔记5-测试类 test_第1张图片
cmd使用python manage.py test blog 进行测试

如果有测试错误.会把异常显示在控制台.

这个过程是 1.首先运行python manage.py test blog 对blog这个app进行单元测试 

2.发现有django.test.TestCase这个类的子类

3.生成一个临时的数据库进行测试.

4.查找测试类中已test开头的测试方法.

5.使用断言assertIs() 来进行测试判断

对was_published_recently 完整的进行测试

Django笔记5-测试类 test_第2张图片

对view进行测试

有2种.第一种直接在shell中测试.不写了.

在test中进行测试

首先要在views.py中设置下,让主页对时间在未来的Question不进行显示


Django笔记5-测试类 test_第3张图片


这里要对IndexView跟DetailView共同配置, 否则index不显示了在detail中可以根据Question的id猜到url让detail.index把未来的Question 暴露出来.

pub_date__lte 表示<= 


编写对view进行单元测试的代码


Django笔记5-测试类 test_第4张图片

这里编写各种逻辑,比如Question的入库时间在未来index.html会怎么显示.在过去入库又会怎样怎样.考虑各种情况写对应的断言

这里有2个django新增加的的断言

assertQuerysetEqual():

assertContains():

Intest_past_question, we create a question and verify that it appears in the list.

Intest_future_question, we create a question with apub_datein the future. The database is reset for each test method, so the first question is no longer there, and so again the index shouldn’t have any questions in it.

这里有一个坑.自带文档没用mysql,用的自带的数据库.所以要在代码中加入save()才能获取到下面的

你可能感兴趣的:(Django笔记5-测试类 test)