• 确认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. sqlserver不太常见的,可能常见但又疑问的tsql语句

    2013年10月29日16:01:58 当数据有 time类型列时候,比如 打电话的通话时长,我们查询时候不方便,我们可以添加一个冗余列,直接统计秒 ,但是 后期知道的,现在我把例如 00:12:23 ...

  2. MFC添加自定义窗口消息

    原文链接: http://www.cnblogs.com/smartvessel/archive/2011/07/18/2109472.html 1. 在头文件stdafx.h中增加一个自定义消息宏 ...

  3. Java 8 – StringJoiner example

    In this article, we will show you a few StringJoiner examples to join String. 1. StringJoiner1.1 Joi ...

  4. elk 使用中遇到的问题(kafka 重复消费)

    问题描述: 在使用过程中,当遇到大量报错的时候,我们到eagle后台看到报错的那个consumer的消费情况到到lag 远远大于0(正常情况应该为0),activie  节点没有,kibana面板上没 ...

  5. [LintCode] N-Queens

    N-Queens The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no tw ...

  6. 怎样使用 Apache ab 以及 OneAPM 进行压力測试?

    下一个 release 准备小长假后就要 go-live .全部的測试 case 都 cover 过了.但还未进行过压力測试,有点不放心,刚好过节期间家人都回家去了,假期最终能够抽点时间压測一把. A ...

  7. 令新手头疼的modelsim库编译

    估计很多人买了CB哥的书来看吧,他们在学习modelsim仿真的过程中可能遇到过明明是按照书上的步骤添加器件库的了,但还是出现如下的错误: 首先,我想说的是CB哥书上的modelsim-altera1 ...

  8. Redis为什么使用单进程单线程方式

    Redis采用的是基于内存的采用的是单进程单线程模型的KV数据库,由C语言编写.官方提供的数据是可以达到100000+的qps.这个数据不比采用单进程多线程的同样基于内存的KV数据库Memcached ...

  9. 通过ip查找能应机器的MAC

    例如:10.100.0.61 这些都是基于linux系统: 首先:ping 一下这个ip 然后arp 10.100.0.61就可以找出主机的MAC地址

  10. Pycharm 2017.1 激活服务器

    最近发现pycharm激活异常困难 原来的激活码 都不能用了 so 根据网上 教程 自己建了激活服务器 尝试可用服务器 20170504 测试发现 给需要域名 http://www.05nb.com: ...