# Writing your-first Django-app-part 5 -test
- 确认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')
测试的技巧:
为每个model/view编写一个单独的测试类方法
为每一种测试条件编写一个单独的测试函数/过程.
测试的函数名称,能够描述这个函数的功能.
最后,附上完整的测试文件:
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的更多相关文章
- 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 ...
- # Writing your first Django app, part 2
创建admin用户 D:\desktop\todoList\Django\mDjango\demoSite>python manage.py createsuperuser 然后输入密码 进入a ...
- 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 ...
- Python-Django 第一个Django app
第一个Django app by:授客 QQ:1033553122 测试环境: Python版本:python-3.4.0.amd64 下载地址:https://www.python.org/do ...
- Django APP打包重用
引言 有时候,我们需要将自己写的app分发(dist)给同事,分享给朋友,或者在互联网上发布,这都需要打包.分发我们的app. Django的子系统重用是基于app级别的.也就是一个项目可以包含多个互 ...
- Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第一部分(Page 6)
编写你的第一个 Django app,第一部分(Page 6)转载请注明链接地址 Django 2.0.1 官方文档翻译: Django 2.0.1.dev20171223092829 documen ...
- Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第七部分(Page 12)
编写你的第一个 Django app,第七部分(Page 12)转载请注明链接地址 本节教程承接第六部分(page 11)的教程.我们继续开发 web-poll应用,并专注于自定义django的自动生 ...
- Django 2.0.1 官方文档翻译:编写你的第一个 Django app,第六部分(Page 11)
编写你的第一个 Django app,第六部分(Page 11)转载请注明链接地址 本教程上接前面第五部分的教程.我们构建了一个经过测试的 web-poll应用,现在我们会添加一个样式表和一张图片. ...
- Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第五部分(Page 10)
编写你的第一个 Django app,第五部分(Page 10)转载请注明链接地址 我们继续建设我们的 Web-poll 应用,本节我们会为它创建一些自动测试. 介绍自动测试 什么是自动测试 测试是简 ...
- Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第四部分(Page 9)
编写你的第一个 Django app,第四部分(Page 9)转载请注明链接地址 该教程上接前面的第三部分.我们会继续开发 web-poll 应用,并专注于简单的表单处理和简化代码. 写一个简单的表单 ...
随机推荐
- cron执行service
在Cron的环境下,是没有定义路径的,所以,service xxx start等等要使用绝对路径 => /sbin/service xxx start service的路径可以用whereis ...
- 安卓Textview的getLineCount返回0
ViewTreeObserver observer = tv.getViewTreeObserver(); // textAbstract为TextView控件 observer.addOnGloba ...
- “The operation cannot be completed because the DbContext has been disposed” exception with lazy load disabled
http://stackoverflow.com/questions/18261732/the-operation-cannot-be-completed-because-the-dbcontext- ...
- 使用 Apache Commons CSV 读写 CSV 文件
有时候,我们需要读写 CSV 文件,在这里给大家分享Apache Commons CSV,读写 CSV 文件非常方便. 具体官方文档请访问Apache Commons CSV. 官方文档已经写得很详细 ...
- 修改firefox/chrome浏览器的UserAgent
Firefox: about:config ---> useragent ---> general.useragent.override -> DIY_AGENT Chrome: 创 ...
- 【转载并整理】javaweb单点登录
很好的一篇,讲述原理的文章: http://www.importnew.com/22863.html https://www.cnblogs.com/Leo_wl/p/6111623.html 京东s ...
- Web安全之XSS(Cross Site Scripting)深入理解
XSS的含义 XSS(Cross Site Scripting)即跨站脚本.跨站的主要内容是在脚本上. 跨站脚本 跨站脚本的跨,体现了浏览器的特性,可以跨域.所以也就给远程代码或者第三方域上的代码提供 ...
- SQL Server中关于跟踪(Trace)那点事(转载)
前言 一提到跟踪俩字,很多人想到警匪片中的场景,同样在我们的SQL Server数据库中“跟踪”也是无处不在的,如果我们利用好了跟踪技巧,就可以针对某些特定的场景做定向分析,找出充足的证据来破案. 简 ...
- 主流磁盘接口比较(SATA/SCSI/SAS/FC)[转]
数据越来越多,用户对存储容量的要求是越来越高.作为数据存储最基本的介质——硬盘,其种类也越来越多.面对市场上纷繁复杂的硬盘,用户又该如何选择呢?本文就对SATA.FC.SAS三种硬盘进行了比较,希望能 ...
- Talend open studio如何调试代码
Talend将设计的模型直接生成了java代码,可以直接对模型生成的java代码进行调试,排查问题比kettle灵活很多, 设计的模型如下: 生成的代码如下: 点击 Java Debug进入调试模式, ...