在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 the polls 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 a Question instance whose pub_datefield is 30 days in the future
  • ... and using the assertIs() method, it discovered that its was_published_recently() returns True, though we wanted it to return False

修复该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的更多相关文章

  1. Python之路-(js正则表达式、前端页面的模板套用、Django基础)

    js正则表达式 前端页面的模板套用 Django基础 js正则表达式: 1.定义正则表达式 /.../  用于定义正则表达式 /.../g 表示全局匹配 /.../i 表示不区分大小写 /.../m ...

  2. django基础入门

    1. http协议 1.1 请求协议 请求协议格式: 请求首行: // 请求方式 请求路径 协议和版本,例如:GET /index.html HTTP/1.1 请求头信息: // 请求头名称:请求头内 ...

  3. python的django基础篇

    一.Django基础 Django 是用Python开发的一个免费开源的Web框架,可以用于快速搭建高性能,优雅的网站! Django的特点: 强大的数据库功能:拥有强大的数据库操作接口(QueryS ...

  4. python3之Django基础篇

    一.Django基础 Django 是用Python开发的一个免费开源的Web框架,可以用于快速搭建高性能,优雅的网站! Django的特点: 强大的数据库功能:拥有强大的数据库操作接口(QueryS ...

  5. Django基础和基本使用

    Django基础 Django是Python下的一款著名的Web框架 框架 任何语言进入到高级部分时,会有认证.session.http.连接数据库等等功能操作,没有框架时需要自己实现 框架 是整个或 ...

  6. Django基础之MTV模型

    一.Django基础 一.Django简介 Django是一个开放源代码的Web应用框架,由Python写成.采用了MVC的软件设计模式,即模型(Model).视图(View)和控制器(Control ...

  7. Django基础之模型(models)层(上)

    目录 Django基础之模型(models)层 单表查询 必知必会13条 神奇的双下划线查询 多表查询 外键的字段的增删改查 表与表之间的关联查询 基于双下划线的跨表查询(连表查询) 补充知识 Dja ...

  8. Django 博客单元测试:测试评论应用

    作者:HelloGitHub-追梦人物 文中所涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库 评论应用的测试和博客应用测试的套路是一样的. 先来建立测试文件的目录结构.首先在 c ...

  9. Django REST framework 单元测试

    Django REST framework 单元测试 只是简单记录一下测试代码怎么写 环境 Win10 Python3.7 Django2.2 项目 参照官网 快速开始 写了一个 demo 测试 参照 ...

随机推荐

  1. [AlwaysOn Availability Groups]监控AG性能

    监控AG性能 AG的性能的性能方面,在关键任务数据库上进行语句级维护性能是很重要的.理解AG如何传输日志到secondary副本对评估RTO和RPO,表明AG是否性能不好. 1. 数据同步步骤 为了评 ...

  2. APUE学习之出错处理

         当UNIX函数发生错误时,通常会返回一个负值,而且整形变量errno通常被设置为具有特定信息的值.        errno是全局变量,仅当函数出错才有被改变.对待errno,应注意两条规则 ...

  3. C#相关开发视频

    Quickly Generate C# Classes from JSON Responses .NET Compiler Platform ("Roslyn") for the ...

  4. Execl数据导入sql server方法

    在日常的程序开发过程中,很多情况下,用户单位给予开发人员的数据往往是execl或者是access数据,如何把这些数据转为企业级是数据库数据呢,下面就利用sqlserver自带的功能来完成此项任务. 首 ...

  5. Salesforce Apex 开发环境设置和Hello World示例

    本文介绍了Salesforce Apex开发环境的设置以及一个简单的Hello World示例的实现过程. Salesforce开发环境 Salesforce通过http://developer.fo ...

  6. 威佐夫博弈(Wythoff Game)

    有两堆石子,数量任意,可以不同.游戏开始由两个人轮流取石子.游戏规定,每次有两种不同的取法,一是可以在任意的一堆中取走任意多的石子:二是可以在两堆中同时取走相同数量的石子.最后把石子全部取完者为胜者. ...

  7. MVC系列——MVC源码学习:打造自己的MVC框架(一:核心原理)

    前言:最近一段时间在学习MVC源码,说实话,研读源码真是一个痛苦的过程,好多晦涩的语法搞得人晕晕乎乎.这两天算是理解了一小部分,这里先记录下来,也给需要的园友一个参考,奈何博主技术有限,如有理解不妥之 ...

  8. 判断是pc端还是手机端,并跳转到相应页面

    <!-- 判断浏览器是否为手机端 -->  <script>     // class     ! function(navigator) {         var user ...

  9. web兼容学习分析笔记--块级、内联、内联块级元素

    一.块级.内联.内联块级元素 (1)块级元素:block **独占一行 **可设置width,height,margin,padding **内部可包含块级或内联元素 (3)内联(行内)元素:inli ...

  10. python学习之路 第三天

    1.set集合:去掉重复字段 set.difference()找出不同并创建一个新的集合,不改变原来集合: set.difference_update() 改变原来集合,剔除掉括号内容: set.di ...