# 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 应用,并专注于简单的表单处理和简化代码. 写一个简单的表单 ...
随机推荐
- Tensorflow运行程序报错 FailedPreconditionError
1 FailedPreconditionError错误现象 在运行tensorflow时出现报错,报错语句如下: FailedPreconditionError (see above for trac ...
- Android App优化之ANR详解
引言 背景:Android App优化, 要怎么做? Android App优化之性能分析工具 Android App优化之提升你的App启动速度之理论基础 Android App优化之提升你的App ...
- API设计原则
译序 Qt的设计水准在业界很有口碑,一致.易于掌握和强大的API是Qt最著名的优点之一.此文既是Qt官网上的API设计指导准则,也是Qt在API设计上的实践总结.虽然Qt用的是C++,但其中设计原则和 ...
- svm工具箱快速入手简易教程
首先svm是用来做分类的,是一种有监督的分类器. 什么是有监督的呢?就是说在你给我一个数据集让我做分类之前.我已经有一些经验数据了.即要先进行学习,再进行分类. 这里就有了训练集和测试集.先用训练集来 ...
- django 文档生成器
参考博客:http://www.liujiangblog.com/course/django/160
- Spark学习笔记之-Spark远程调试
Spark远程调试 本例子介绍简单介绍spark一种远程调试方法,使用的IDE是IntelliJ IDEA. 1.了解jvm一些参数属性 -X ...
- 2012版辅助开发工具包(ADT)新功能特性介绍及安装使用
原文链接:http://android.eoe.cn/topic/android_sdk 2012年的Android辅助设备开发工具包(ADK)是Android开放设备协议(AOA)设备的最新参考实现 ...
- [转]:Android 5.0的调度作业JobScheduler
参考:http://blog.csdn.net/cuiran/article/details/42805057 增加 JobScheduler 的同时,去掉了几个广播, CONNECTIVITY_AC ...
- Wireshark数据抓包分析——网络协议篇
Wireshark数据抓包分析--网络协议篇 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGF4dWViYQ==/ ...
- 逆向project实战--Acid burn
0x00 序言 这是第二次破解 crackme 小程序,感觉明显比第一次熟练.破解过程非常顺利,差点儿是分分钟就能够找到正确的 serial,可是我们的目标是破解计算过程.以下将具体介绍. 0x01 ...