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 pollslooked for tests in thepollsapplication- it found a subclass of the
django.test.TestCaseclass - 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_questionit created aQuestioninstance whosepub_datefield 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 测试 参照 ...
随机推荐
- 什么是RAID?RAID有什么用?RAID原理
什么是RAID 硬盘是个很脆弱的东西,它经常会坏掉.所以,为了保证服务器可靠耐用,硬盘必须时时刻刻保持可用.所以有了RAID这个东西.它的目的是将好几个硬盘合并在一起,就算硬盘坏了一个,剩下还有好几个 ...
- 尝试解析js面试题(二)
说明:一共有13题(原本14题,最后一道什么鬼,嫌弃不要了),覆盖面比较广,都属于比较烧脑的类型,各种神坑:不过对于夯实js理论基础帮助非常大:看看都能做对几题吧(
- Windows Server 2012 虚拟化实战:存储(二)
五.搭建Window Server 2012虚拟化的存储网络 前文我们讨论了Window Server 2012支持的各种与存储相关的技术,接下来我们通过实践对其中的一些技术进行检验.实际上Windo ...
- mysql报错: 1548-Cannot load from mysql.proc. The table is probably corrupted 解决办法
use mysql: ALTER TABLE `proc` MODIFY COLUMN `comment` text CHARACTER SET utf8 COLLATE utf8_bin NOT N ...
- 【FLUENT案例】04:利用DDPM+DEM模拟鼓泡流化床
1 引言2 问题描述3 准备4 FLUENT前处理 1 引言 DEM碰撞模型扩展了DPM模型的功能,能够用于稠密颗粒流动的模拟.该模型可以与DDPM(Dense DPM)模型何用以模拟颗粒对主相的阻碍 ...
- [转]Asp.Net Core 简单的使用加密的Cookie保存用户状态
本文转自:http://www.cnblogs.com/Joes/p/6023820.html 在以前的Asp.Net中可以用 FormsAuthentication 类的一系列方法来使用加密的Coo ...
- 【原】移动web滑屏框架分享
本月26号参加webrebuild深圳站,会上听了彪叔的对初心的讲解,“工匠精神”这个词又一次被提出,也再次引起了我对它的思考.专注一个项目并把它做得好,很好,更好...现实工作中,忙忙碌碌,抱着完成 ...
- 第10章 Shell编程(1)_正则表达式
1. 基础的正则表达式 1.1 正则表达式与通配符 (1)正则表达式用来在文件中匹配符合条件的字符串,正则是包含匹配.grep.awk.sed等命令可以支持正则表达式. (2)通配符用来匹配符合条件的 ...
- Android开发用过的十大框架
http://blog.csdn.net/u011200604/article/details/51695096 本文系多方综合与转载整合,意在Android开发中能够知道和使用一些好用的第三方支持, ...
- ns3 print 丢包内容的两种方法
1.方法一enable ascii print AsciiTraceHelper ascii; pointToPoint.EnableAsciiAll (ascii.CreateFileStream ...