• 确认bug
  • 写test测试暴露bug
  • 修复bug
  • 更多测试例子
  • 测试一个view
    • The Django test client测试客户端.
    • 提升DemoAppPoll/views.py
    • 测试我们的view.index
    • 测试DemoAppPoll/views.py/DetailView
  • 测试的技巧:
  • 完整的测试文件

确认bug

如果传入一个未来的时间,那么was_published_recently()会返回什么?

D:\desktop\todoList\Django\mDjango\demoSite>python manage.py shell
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import datetime
>>> from django.utils import timezone
>>> from DemoAppPoll.models import Question
>>> future_question = Question(pub_date=timezone.now()+datetime.timedelta(days=30))
>>> future_question.was_published_recently()
True

写test测试暴露bug

将上述的过程,写成test如下:

DemoAppPoll/tests.py

import datetime

from django.test import TestCase
from django.utils import timezone from DemoAppPoll.models import Question class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
time = timezone.now()+datetime.timedelta(days=30)
furture_question = Question(pub_date=time)
self.assertEqual(furture_question.was_published_recently(),False)

运行测试:

python manage.py test DemoAppPoll

1> "python manage.py test DemoAppPoll "从DemoAppPoll(APP)下找tests.

2>"django.test.TestCase",测试示例,DemoAppPoll作为TestCase参数传入:

class QuestionMethodTests(TestCase):

3>创建了一个为了测试的特殊的数据库

4>assertEqual() 最后来判断.

修复bug

DemoAppPoll/models.py

def was_published_recently(self):
now = timezone.now()
return now-datetime.timedelta(days=1) <=self.pub_date<=now
#return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

由原来的单边不等式,改为现在的双边不等式即可.

测试结果:

D:\desktop\todoList\Django\mDjango\demoSite>python manage.py test DemoAppPoll
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.318s
OK
Destroying test database for alias 'default'...

更多测试例子

如果是以前的问题?如果是最近的问题?

DemoAppPoll/tests.py

    def test_was_published_rencently_with_old_question(self):
time = timezone.now()-datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertEqual(old_question.was_published_recently(),False)
def test_was_published_rencently_with_recent_question(self):
time = timezone.now()-datetime.timedelta(hours=1)
recent_question=Question(pub_date=time)
self.assertEqual(recent_question.was_published_recently(),True)

测试一个view

The Django test client测试客户端.

D:\Documents\mandroid\demoSite>python manage.py shell
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> client =Client()
>>> response=client.get('/')
>>> response.status_code
404
>>> from django.core.urlresolvers import reverse
>>> response=client.get(reverse('DemoAppPoll:index'))
>>> response.status_code
200
>>> response.content
'\r\n <ul>\r\n \r\n \r\n\t\t<li><a href="/DemoAppPoll/1/">what's up </a></li>\r\n \r\n \'
>>> from DemoAppPoll.models import Question
>>> from django.utils import timezone
>>> q=Question(question_text="who is your favourite Beatle",pub_date=timezone.now())
>>> q.save()
>>> response=client.get('/DemoAppPoll/')
>>> response.content
'\r\n <ul>\r\n \r\n \r\n\t\t<li><a href="/DemoAppPoll/3/">who is your favourite Beatle</a></li>\r\n
\r\n\t\t<li><a href="/DemoAppPoll/2/">what time is it?</a></li>\r\n \r\n </ul>\r\n'
>>> response.context['latest_question_list']
[<Question: who is your favourite Beatle>, <Question: what's up >, <Question: what time is it?>]
>>>

提升DemoAppPoll/views.py

    def get_queryset(self):
#return Question.objects.order_by('-pub_date')[:5]
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

上面需要

from django.utils import timezone

测试我们的view.index

def create_question(question_text,days):
time = timezone.now()+ datetime.timedelta(days=days) return Question.objects.create(question_text=question_text,pub_date=time) class QuestionViewTests(TestCase):
def test_index_view_with_a_future_question(self):
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('DemoAppPoll:index'))
self.assertContains(response, "No polls are available.",
status_code=200)
self.assertQuerysetEqual(response.context['latest_question_list'], [])

还是那几个步骤:

1> 导入需要的包:

from django.core.urlresolvers import reverse

2>编写类,传入TestCase参数

3>编写测试方法:a)创建实例,b)模拟请求,c)比较结果

测试DemoAppPoll/views.py/DetailView

首先,稍微修改DemoAppPoll/views.py:

class DetailView(generic.DetailView):
model = Question
template_name = "DemoAppPoll/detail.html"
def get_queryset(self):
#return Question.objects.order_by('-pub_date')[:5]
return Question.objects.filter(pub_date__lte=timezone.now())

如果有人直接访问DemoAppPoll/xx/,那么,返回空.

下面编写测试:

class QuestionIndexDetailTests(TestCase):#编写类,传入参数TestCase
#
def test_detail_view_with_a_future_question(self):
#编写测试方法
future_question=create_question(question_text="Future question", days=5)
#测试场景前提
response = self.client.get(reverse('DemoAppPoll:detail',args=(future_question.id,)))
#模拟请求.
self.assertEqual(response.status_code,404)
#与预期结果比较.
def test_detail_view_with_a_past_question(self):
past_question=create_question(question_text="past question", days=-5)
response = self.client.get(reverse('DemoAppPoll:detail',args=(past_question.id,)))
self.assertContains(response,'past question')

测试的技巧:

  1. 为每个model/view编写一个单独的测试类方法

  2. 为每一种测试条件编写一个单独的测试函数/过程.

  3. 测试的函数名称,能够描述这个函数的功能.


最后,附上完整的测试文件:

demoSite/DemoAppPoll/tests.py

# -*- coding: utf-8 -*-
import datetime
from django.test import TestCase
from django.utils import timezone
from DemoAppPoll.models import Question
from django.core.urlresolvers import reverse class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
time = timezone.now() + datetime.timedelta(days=30)
furture_question = Question(pub_date=time)
self.assertEqual(furture_question.was_published_recently(), False)
def test_was_published_rencently_with_old_question(self):
time = timezone.now() - datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertEqual(old_question.was_published_recently(), False)
def test_was_published_rencently_with_recent_question(self):
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertEqual(recent_question.was_published_recently(), True) def create_question(question_text,days):
time = timezone.now()+ datetime.timedelta(days=days) return Question.objects.create(question_text=question_text,pub_date=time) class QuestionViewTests(TestCase):
def test_index_view_with_no_question(self):
response = self.client.get(reverse('DemoAppPoll: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):
create_question(question_text="Past question", days=-30)
response = self.client.get(reverse("DemoAppPoll:index"))
self.assertQuerysetEqual(response.context['latest_question_list'],
['<Question: Past question>']
)
def test_index_view_with_a_future_question(self):
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('DemoAppPoll:index'))
self.assertContains(response, "No polls are available.",
status_code=200)
self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_index_view_with_future_question_and_past_question(self):
create_question(question_text="Past question.", days=-30)
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('DemoAppPoll:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
) def test_index_view_with_two_past_questions(self):
create_question(question_text="Past question 1.", days=-30)
create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse('DemoAppPoll:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
class QuestionIndexDetailTests(TestCase):#编写类,传入参数TestCase
#
def test_detail_view_with_a_future_question(self):#编写测试方法
future_question=create_question(question_text="Future question", days=5)#测试场景前提
response = self.client.get(reverse('DemoAppPoll:detail',args=(future_question.id,)))#模拟请求.
self.assertEqual(response.status_code,404)#与预期结果比较.
def test_detail_view_with_a_past_question(self):
past_question=create_question(question_text="past question", days=-5)
response = self.client.get(reverse('DemoAppPoll:detail',args=(past_question.id,)))
self.assertContains(response,'past question')

# Writing your-first Django-app-part 5 -test的更多相关文章

  1. Writing your first Django app, part 1(转)

    Let’s learn by example. Throughout this tutorial, we’ll walk you through the creation of a basic pol ...

  2. # Writing your first Django app, part 2

    创建admin用户 D:\desktop\todoList\Django\mDjango\demoSite>python manage.py createsuperuser 然后输入密码 进入a ...

  3. Writing your first Django

    Quick install guide 1.1   Install Python, it works with Python2.6, 2.7, 3.2, 3.3. All these version ...

  4. Python-Django 第一个Django app

    第一个Django app   by:授客 QQ:1033553122 测试环境: Python版本:python-3.4.0.amd64 下载地址:https://www.python.org/do ...

  5. Django APP打包重用

    引言 有时候,我们需要将自己写的app分发(dist)给同事,分享给朋友,或者在互联网上发布,这都需要打包.分发我们的app. Django的子系统重用是基于app级别的.也就是一个项目可以包含多个互 ...

  6. Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第一部分(Page 6)

    编写你的第一个 Django app,第一部分(Page 6)转载请注明链接地址 Django 2.0.1 官方文档翻译: Django 2.0.1.dev20171223092829 documen ...

  7. Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第七部分(Page 12)

    编写你的第一个 Django app,第七部分(Page 12)转载请注明链接地址 本节教程承接第六部分(page 11)的教程.我们继续开发 web-poll应用,并专注于自定义django的自动生 ...

  8. Django 2.0.1 官方文档翻译:编写你的第一个 Django app,第六部分(Page 11)

    编写你的第一个 Django app,第六部分(Page 11)转载请注明链接地址 本教程上接前面第五部分的教程.我们构建了一个经过测试的 web-poll应用,现在我们会添加一个样式表和一张图片. ...

  9. Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第五部分(Page 10)

    编写你的第一个 Django app,第五部分(Page 10)转载请注明链接地址 我们继续建设我们的 Web-poll 应用,本节我们会为它创建一些自动测试. 介绍自动测试 什么是自动测试 测试是简 ...

  10. Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第四部分(Page 9)

    编写你的第一个 Django app,第四部分(Page 9)转载请注明链接地址 该教程上接前面的第三部分.我们会继续开发 web-poll 应用,并专注于简单的表单处理和简化代码. 写一个简单的表单 ...

随机推荐

  1. numpy 中的axis轴问题

    在numpy库中,axis轴的问题比较重要,不同的值会得到不同的结果,为了便于理解,特此将自己的理解进行梳理 为了梳理axis,借助于sum函数进行! a = np.arange(27).reshap ...

  2. Linux 的僵尸(zombie)进程

    可能很少有人意识到,在一个进程调用了exit之后,该进程 并非马上就消失掉,而是留下一个称为僵尸进程(Zombie)的数据结构.在Linux进程的5种状态中,僵尸进程是非常特殊的一种,它已经放弃了几乎 ...

  3. STL 的string类怎么啦?

    前言   上个周末在和我的同学爬香山闲聊时,同学说到STL中的string类曾经让他备受折磨,几年前他开发一个系统前对string类还比较清楚,然后随着程序的复杂度的加深,到了后期,他几乎对strin ...

  4. iOS 9 学习系列: Xcode Code Coverage

    Code coverage 是一个计算你的单元測试覆盖率的工具. 高水平的覆盖给你的单元測试带来信心.也表明你的应用被彻底的測试过了. 你可能写了几千个单元測试,但假设覆盖率不高.那么你写的这套測试可 ...

  5. C#基础第六天-作业答案-利用面向对象的思想去实现名片

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  6. Windows 计划任务 Task Schedule 怎么 运行 .bat文件

    1. 新建 test.bat 需要切换文件夹以后 并且执行程序. cd /D "F:\xxxfolder" && dotnet testdll.dll 2. 直接设 ...

  7. 在Android Studio 和 Eclipse 的 git 插件操作 "代码提交"以及"代码冲突"

    面向对象:曾经使用过SVN的同学. (因为Git 它 可以说是双重的SVN (本地一个服务器,远程一个服务器)),提交代码要有两次步骤,先提交到本地服务器,再把本地服务器在提交到远程服务器. 所以连S ...

  8. java解析邮箱中的邮件信息

    import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import ...

  9. HTML5学习笔记(二十一):BOM

    BOM(Browser Object Model) 是指浏览器对象模型. 由于最初JavaScript就是设计在浏览器中执行的脚本语言,所以BOM是浏览器提供给JavaScript操作自身的接口. w ...

  10. HTML5学习笔记(九):选择器详解

    在前面的笔记中我们已经接触过几种常见的选择器,本笔记我们将深入了解CSS的选择器. 元素选择器 最常见的 CSS 选择器是元素选择器.换句话说,文档的元素就是最基本的选择器.在 W3C 标准中,元素选 ...