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 测试 参照 ...
随机推荐
- Oracle Connect by与递归with
层次查询 select * from emp; select empno, ename, job, mgr, sal, deptno,level lv, sys_connect_by_path(ena ...
- 轻量级ORM框架——第一篇:Dapper快速学习
我们都知道ORM全称叫做Object Relationship Mapper,也就是可以用object来map我们的db,而且市面上的orm框架有很多,其中有一个框架 叫做dapper,而且被称为th ...
- 重邮二进制日天群-pwn1
给学弟们练手的题目,做的过程中接触一些基本概念 #include <stdio.h> #include <unistd.h> int main() { ]; welcome() ...
- Linux 查看命令源码
一.简介 有时候想看看ls.cat.more等命令的源代码,本文介绍相应查看方法. 二.方法 参考: http://blog.csdn.net/silentpebble/article/details ...
- [数据分析]excel带名称的四象限散点图制作
本文前言:方法来至Excel图表之道这本数,偶然看到,好久没出数据分析的文章了,也难怪最近几个月都忙作网页,数据分析自己也就用excell和sql 正文: 带象限的散点图效果如下: 看到图片,这里制作 ...
- js控制div滚动条,滚动滚动条使div中的元素可见并居中
1.html代码如下 <div id="panel"> <div id="div1"></div> <div id=& ...
- POJ 1753. Flip Game 枚举or爆搜+位压缩,或者高斯消元法
Flip Game Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 37427 Accepted: 16288 Descr ...
- BZOJ 2820: YY的GCD [莫比乌斯反演]【学习笔记】
2820: YY的GCD Time Limit: 10 Sec Memory Limit: 512 MBSubmit: 1624 Solved: 853[Submit][Status][Discu ...
- [No00008B]远程桌面发送“Ctrl+Alt+Delete”组合键调用任务管理器
向远程桌面发送"Ctrl+Alt+Delete"组合键的两种方法 1.在本地按下Ctrl+Alt+End,可以成功发送"Ctrl+Alt+Delete"组合键! ...
- 一个virtualbox开机即aborted的问题解决
问题: 之前想装最新的virtualbox版本,从官网下载了virtualbox最新的5点几的版本,使用sudo dpkg -i *.deb进行安装的. 然而,在virtualbox中启动了ubunt ...