Django基础,Day6 - 单元测试tests
在django项目app目录下,有个tests.py,我们通常可以直接在这文件中写我们的单元测试代码。
test for a model
根据前面章节的操作步骤下来,在Question Model中有一个函数 was_published_recently(),判断文章发表时间在当前一天之内。代码如
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
仔细检查,可发现上述函数有个bug。如果发表时间在未来呢,按照上面的代码是会返回true的,显然不对。
编写测试用例 polls/tests.py:
from django.test import TestCase
import datetime
from django.utils import timezone
from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self):
"""
was_published_recently() should return False for questions whose
pub_date is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
运行测试用例
$ python manage.py test polls
运行结果如:
Creating test database for alias 'default'...
F
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionMethodTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "E:\workspace_python\mysite\polls\tests.py", line , in test_was_published_recently_with_future_question
self.assertIs(future_question.was_published_recently(), False)
AssertionError: True is not False ----------------------------------------------------------------------
Ran test in .002s FAILED (failures=)
Destroying test database for alias 'default'...
What happened is this:
python manage.py test polls
looked for tests in thepolls
application- it found a subclass of the
django.test.TestCase
class - it created a special database for the purpose of testing
- it looked for test methods - ones whose names begin with
test
- in
test_was_published_recently_with_future_question
it created aQuestion
instance whosepub_date
field is 30 days in the future - ... and using the
assertIs()
method, it discovered that itswas_published_recently()
returnsTrue
, though we wanted it to returnFalse
修复该bug,代码如
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
重新运行测试代码,则用例通过。
$ python manage.py test polls
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran test in .001s OK
Destroying test database for alias 'default'...
添加更多的测试用例,如
from django.test import TestCase
import datetime
from django.utils import timezone
from .models import Question class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self):
"""
was_published_recently() should return False for questions whose
pub_date is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self):
"""
was_published_recently() should return False for questions whose
pub_date is older than 1 day.
"""
time = timezone.now() - datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() should return True for questions whose
pub_date is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)
test for a view
以view.index 为例,显然现在的代码也有bug,显示了发布时间属于将来的文章,代码如
测试之前,先修复view.index 中应该不显示发布时间在将来的文章。测试代码代码如
polls/views.py:
polls/index.html:
测试用例代码
Django provides a test Client
to simulate a user interacting with the code at the view level
from django.test import TestCase
import datetime
from django.urls import reverse
from django.utils import timezone
from .models import Question class QuestionViewTests(TestCase):
def test_index_view_with_no_questions(self):
"""
If no questions exist, an appropriate message should be displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_a_past_question(self):
"""
Questions with a pub_date in the past should be displayed on the
index page.
"""
create_question(question_text="Past question.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
) def test_index_view_with_a_future_question(self):
"""
Questions with a pub_date in the future should not be displayed on
the index page.
"""
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self):
"""
Even if both past and future questions exist, only past questions
should be displayed.
"""
create_question(question_text="Past question.", days=-30)
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
) def test_index_view_with_two_past_questions(self):
"""
The questions index page may display multiple questions.
"""
create_question(question_text="Past question 1.", days=-30)
create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***
Django基础,Day6 - 单元测试tests的更多相关文章
- Python之路-(js正则表达式、前端页面的模板套用、Django基础)
js正则表达式 前端页面的模板套用 Django基础 js正则表达式: 1.定义正则表达式 /.../ 用于定义正则表达式 /.../g 表示全局匹配 /.../i 表示不区分大小写 /.../m ...
- django基础入门
1. http协议 1.1 请求协议 请求协议格式: 请求首行: // 请求方式 请求路径 协议和版本,例如:GET /index.html HTTP/1.1 请求头信息: // 请求头名称:请求头内 ...
- python的django基础篇
一.Django基础 Django 是用Python开发的一个免费开源的Web框架,可以用于快速搭建高性能,优雅的网站! Django的特点: 强大的数据库功能:拥有强大的数据库操作接口(QueryS ...
- python3之Django基础篇
一.Django基础 Django 是用Python开发的一个免费开源的Web框架,可以用于快速搭建高性能,优雅的网站! Django的特点: 强大的数据库功能:拥有强大的数据库操作接口(QueryS ...
- Django基础和基本使用
Django基础 Django是Python下的一款著名的Web框架 框架 任何语言进入到高级部分时,会有认证.session.http.连接数据库等等功能操作,没有框架时需要自己实现 框架 是整个或 ...
- Django基础之MTV模型
一.Django基础 一.Django简介 Django是一个开放源代码的Web应用框架,由Python写成.采用了MVC的软件设计模式,即模型(Model).视图(View)和控制器(Control ...
- Django基础之模型(models)层(上)
目录 Django基础之模型(models)层 单表查询 必知必会13条 神奇的双下划线查询 多表查询 外键的字段的增删改查 表与表之间的关联查询 基于双下划线的跨表查询(连表查询) 补充知识 Dja ...
- Django 博客单元测试:测试评论应用
作者:HelloGitHub-追梦人物 文中所涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库 评论应用的测试和博客应用测试的套路是一样的. 先来建立测试文件的目录结构.首先在 c ...
- Django REST framework 单元测试
Django REST framework 单元测试 只是简单记录一下测试代码怎么写 环境 Win10 Python3.7 Django2.2 项目 参照官网 快速开始 写了一个 demo 测试 参照 ...
随机推荐
- nodejs---修改文件名字
D:\node\update_name目录有如下文件: 1:文件夹:icons 2:js文件:update-name.js js文件代码: // 引入fs文件处理模块var fs = require( ...
- MS SQL巡检系列——检查重复索引
前言感想:一时兴起,突然想写一个关于MS SQL的巡检系列方面的文章,因为我觉得这方面的知识分享是有价值,也是非常有意义的.一方面,很多经验不足的人,对于巡检有点茫然,不知道要从哪些方面巡检,另外一方 ...
- 编译安装zabbix3.2
1.1 环境准备 系统环境准备:redhat 6.6 64位mysql-5.6.34php-5.6.28zabbix-3.2.1配置前先关闭iptables和SELINUX,避免安装过程中报错. # ...
- javascript判断数组中是否包含某个元素
//判断数组array中是否包含元素obj的函数,包含则返回true,不包含则返回false function array_contain(array, obj){ for (var i = 0; i ...
- Ubuntu15.04安装不完全指南
0x00. 烧盘 使用UltraISO(破解版)烧录到U盘里,设置电脑从U盘启动,即可安装. 安装时可能出现not COM32R image的命令行,“boot:” 后面直接输入live即可解决问题. ...
- Spring事物管理
spring事务配置的五种方式 前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学习发觉Spring的事务配置只 ...
- jquery each函数 break和continue功能
jquery each函数 break和continue功能幸运的是另一个突破,持续一个jQuery循环方式.你可以打破在函数返回一个jQuery参数虚假循环.一个可以继续执行只是在做不指定返回值或返 ...
- DeveloperExceptionPageMiddleware中间件如何呈现“开发者异常页面”
DeveloperExceptionPageMiddleware中间件如何呈现"开发者异常页面" 在<ASP.NET Core应用的错误处理[1]:三种呈现错误页面的方式&g ...
- [LeetCode] Add Two Numbers 两个数字相加
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
- 对于一个div下两个横内元素对其或者居中的方法
我们会经常遇到这样的对其问题图片和文字,或者文字和单选按钮之类的,而且,如果文字不是12px或者14px,有时候想大一点的时候,会出现对不起的情况或者居中不了. 下面我们来看看: 有时候会出现: 这种 ...