什么是自动化测试

  1. 每次更新完系统后,可自动进行测试,而不是手工从头测试一遍;
  2. 从长远和全局的角度看,测试能节约我们的时间;
  3. 测试是一种积极的行为,它能预防问题,而不仅仅是识别问题;
  4. 测试有助于代码美观和团队合作;
  5. 测试能使你详细你的代码,没有测试的代码存在设计漏洞;
  6. 测试可以边编写边执行,也可以测试为驱动,或者最后进行测试;

model部分的测试

tests.py文件

import datetime

from django.utils import timezone
from django.test import TestCase from polls.models import Poll class PollMethodTests(TestCase): def test_was_published_recently_with_future_poll(self):
"""
was_published_recently() should return False for polls whose
pub_date is in the future
"""
future_poll = Poll(pub_date=timezone.now() + datetime.timedelta(days=30))
self.assertEqual(future_poll.was_published_recently(), False)

运行命令

python manage.py test polls

流程如下:

  1. 首先寻找polls应用下的tests
  2. 找到了django.test.TestCase的子类
  3. 创建了以测试为目的的数据库
  4. 寻找测试的方法——以test开头的方法
  5. 在方法中,创建了一个Poll的对象
  6. 用断言的方法返回结果

修正BUG

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

完整的测试

def test_was_published_recently_with_old_poll(self):
"""
was_published_recently() should return False for polls whose pub_date
is older than 1 day
"""
old_poll = Poll(pub_date=timezone.now() - datetime.timedelta(days=30))
self.assertEqual(old_poll.was_published_recently(), False) def test_was_published_recently_with_recent_poll(self):
"""
was_published_recently() should return True for polls whose pub_date
is within the last day
"""
recent_poll = Poll(pub_date=timezone.now() - datetime.timedelta(hours=1))
self.assertEqual(recent_poll.was_published_recently(), True)

视图层的测试

Django测试client

此过程不会创建测试数据库,因此会修改原有数据库

>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test.client import Client
>>> client = Client()
>>> response = client.get('/')
>>> from django.core.urlresolvers import reverse
>>> response = client.get(reverse('polls:index'))
>>> response.status_code
>>> response.content

修正view并测试

不显示未来发表的投票

from django.utils import timezone
def get_queryset(self):
"""
Return the last five published polls (not including those set to be
published in the future).
"""
return Poll.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]

进行测试

from django.core.urlresolvers import reverse
def create_poll(question, days):
"""
Creates a poll with the given `question` published the given number of
`days` offset to now (negative for polls published in the past,
positive for polls that have yet to be published).
"""
return Poll.objects.create(question=question,
pub_date=timezone.now() + datetime.timedelta(days=days)) class PollViewTests(TestCase):
def test_index_view_with_no_polls(self):
"""
If no polls 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_poll_list'], []) def test_index_view_with_a_past_poll(self):
"""
Polls with a pub_date in the past should be displayed on the index page.
"""
create_poll(question="Past poll.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_poll_list'],
['<Poll: Past poll.>']
) def test_index_view_with_a_future_poll(self):
"""
Polls with a pub_date in the future should not be displayed on the
index page.
"""
create_poll(question="Future poll.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available.", status_code=200)
self.assertQuerysetEqual(response.context['latest_poll_list'], []) def test_index_view_with_future_poll_and_past_poll(self):
"""
Even if both past and future polls exist, only past polls should be
displayed.
"""
create_poll(question="Past poll.", days=-30)
create_poll(question="Future poll.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_poll_list'],
['<Poll: Past poll.>']
) def test_index_view_with_two_past_polls(self):
"""
The polls index page may display multiple polls.
"""
create_poll(question="Past poll 1.", days=-30)
create_poll(question="Past poll 2.", days=-5)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_poll_list'],
['<Poll: Past poll 2.>', '<Poll: Past poll 1.>']
)
  1. create_poll是为了减少代码冗余;
  2. assertEqual判断变量相等,assertQuerysetEqual判断列表等集合相等;
  3. assertContains(response, "No polls are available.")判断返回值,也可增加self.assertContains(response, "No polls are available.", status_code=200);

测试DetailView

为了避免直接通过URL访问未来的测试,我们修改view.py中的相应页面;

class DetailView(generic.DetailView):
...
def get_queryset(self):
"""
Excludes any polls that aren't published yet.
"""
return Poll.objects.filter(pub_date__lte=timezone.now())

增加相应的测试页面

class PollIndexDetailTests(TestCase):
def test_detail_view_with_a_future_poll(self):
"""
The detail view of a poll with a pub_date in the future should
return a 404 not found.
"""
future_poll = create_poll(question='Future poll.', days=5)
response = self.client.get(reverse('polls:detail', args=(future_poll.id,)))
self.assertEqual(response.status_code, 404) def test_detail_view_with_a_past_poll(self):
"""
The detail view of a poll with a pub_date in the past should display
the poll's question.
"""
past_poll = create_poll(question='Past Poll.', days=-5)
response = self.client.get(reverse('polls:detail', args=(past_poll.id,)))
self.assertContains(response, past_poll.question, status_code=200)

未来测试的建议

  1. 不要怕测试多,测试越多越好;
  2. 每个model or view,都有独立的TestClass;
  3. 每个测试方法,都有一个你想要测试的独立环境;
  4. 测试方法的名字要描述他们的功能;

Django初级手册5-自动化测试的更多相关文章

  1. Django初级手册6-静态文件

    用Django加载外部文件 在Django中iamges,JS或者CSS通称为static文件 定制APP的外观 一般放在应用目录下的static/polls/目录下,下为polls/static/p ...

  2. Django初级手册4-表单与通用视图

    表单的编写 1. detail.html模版的编写 <h1>{{ poll.question }}</h1> {% if error_message %}<p>&l ...

  3. Django初级手册3-视图层与URL配置

    设计哲学 在Django中一个视图有指定函数和指定模版组成.对于某些特定的应用应该分成若干视图.例如博客系统 Blog主页面 详细页面入口 基于年的页面展示 基于月的页面展示 基于天的页面展示 评论行 ...

  4. Django初级手册2-管理界面的使用及定制

    管理界面的使用 管理界面的URL,帐号和密码在第一次输入syncdb时建立 http://127.0.0.1:8000/admin/ 将app加入管理界面 编辑polls/admin.py from ...

  5. Django初级手册1-项目和应用的创建与简单的数据库操作

    创建项目 django-admin.py startproject mysite 1. 目录结构 mysite/ #项目的名称 manage.py #可通过命令和项目进行交互的文件 mysite/ # ...

  6. django+appium实现UI自动化测试平台---构思版

             背景 UI自动化,在进行的过程中,难免会遇到平台化, 在实际的工作中,有的领导也会想要实现自动化测试的平台化.自动化平台化后,有了更为实际的成果, 在做UI自动化,很想吧现在的自动化 ...

  7. django 初级(一) 配置与周边

    一.下载安装 从 https://www.djangoproject.com/download/ 下载最新的 django 版本,写本文时最新版本为 django 1.7,官方说只需要 python6 ...

  8. Django 学习手册 - 下载数据库表格(XLS/CSV)

    下载XLS表格方式: 前置: 需要安装xlwt模块 views : def export_users_xls(request): response = HttpResponse(content_typ ...

  9. Django学习手册 - 基于requests API验证(二)

    原理分析: API接口验证 1.一个认证的key server端 和 client端都必须有这么一个认证key. 2.认证登录的时间限定 3.保存已验证的信息,在以后的验证不能再次登录 client ...

随机推荐

  1. RedHat 简易配置 VNC Server 与VNC View详细说明

    首先下载Linux版本的VNC文件. 下载地址:http://www.realvnc.com/download/vnc/ 如:VNC-5.0.2-Linux-x86-RPM.tar.gz(其实解压出来 ...

  2. .NET 高性能WEB架构-比较容易改造方式 - .NET架构

    下面列出的一些,是我们常见而且比较容易去优化的方式,当然细节方面非常多,仅供参考: 1.数据库依然选择SQL Server数据库(最新的sqlserver功能是很强大的)和使用订阅发布进行单写多读的读 ...

  3. jenkins使用Publish Over SSH中遇到的问题

    在jenkins中想使用publish over ssh来在构建后发送XML或PNG文件至服务器,以便做其它的操作,安装完publish over ssh后,填加构建,发现在构建失败时,不传送文件,老 ...

  4. 一个简单web系统的接口性能分析及调优过程

    在测试一个简单系统接口性能压力时,压到一定数量,程序总是崩溃,查看相关机器相关数据时,CPU.内存.IO占用均不高,问题自然出现在其它地方先介绍下系统部件架构 Resin版本为:[root@local ...

  5. CodeFirst Update-Database 出现对象'DF__**__**__**' 依赖于 列'**'。

    今天在使用Mirgration更新数据表时,出现这样一个错误 经排查,是由于CodeFirst在创建数据库时会为不可为null的字段创建默认值约束 只要在数据库中删除这个约束就可以解决

  6. ABP之仓储

    一.仓储的简单介绍 仓储(Repository):这是属于领域层的重要组成部分,它的作用就是完成和数据库的交互工作,仓储里封装了很多操作数据库的方法.所以说仓储是数据映射层和领域层的交互中介.ABP针 ...

  7. SQL Fundamentals || Single-Row Functions || 通用函数 General function || (NVL,NVL2,NULLIF,DECODE,CASE,COALESCE)

    SQL Fundamentals || Oracle SQL语言 SQL Fundamentals: Using Single-Row Functions to Customize Output使用单 ...

  8. Python哈希表的例子:dict、set

    dict(字典) Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. 和list比较,dic ...

  9. cordova-ios 升级到4.4.0 无法真机跑iOS8 报错: dyld`dyld_fatal_error: -> 0x120085088 <+0>: brk #0x3

    项目进入测试阶段,马上要上线了,同事拿了自己的iOS8系统5s跑真机,无缘无故报错,之前跑她的手机完全没有问题的.Xcode 8.x中最低部署版本是iOS8.0,按理说完全能够跑真机的. 但是报了一个 ...

  10. JMeter(十四)-自动生成测试报告

    很多朋友都在问jmeter如何生成测试报告,这里随便说两句. 环境要求 1:jmeter3.0版本之后开始支持动态生成测试报表 2:jdk版本1.7以上 3:需要jmx脚本文件 基本操作 1:在你的脚 ...