Django单元测试

一.前言/准备

  测Django的东西仅限于在MTV模型。哪些可以测?哪些不可以。

1.html里的东西不能测。
①Html里的HTML代码大部分都是写死的
②嵌套在html中的Django模板语言也不能测,即使有部分逻辑。
但写测试用例时至少要调用一个类或者方法。模板语言没有出参也没有入参,不能测
2.models模型可测。属于数据库层
3.views,视图层可以测。有入参、有方法。
综上:根据Django语言特点,可测models和views

二.Django单元测试具体步骤----【测试模型models中的内容】

# coding=utf-8
from django.test import TestCase #导入Django测试包
from sign.models import Guest, Event #导入models中的发布会、嘉宾类

#首先创建测试类
class ModelTest(TestCase):

#初始化:分别创建一条发布会(Event)和一条嘉宾(Guest)的数据。
def setUp(self):
Event.objects.create(id=1, name="oneplus 3 event", status=True, limit=2000,
address='shenzhen', start_time='2016-08-31 02:18:22')
Guest.objects.create(id=1, event_id=1, realname='alen',
phone='13711001101', email='alen@mail.com', sign=False)

#下面开始写测试用例了
#1.通过get的方法,查询插入的发布会数据,并根据地址判断
def test_event_models(self):
result = Event.objects.get(name="oneplus 3 event")
self.assertEqual(result.address, "shenzhen")
self.assertTrue(result.status)

#2.通过get的方法,查询插入的嘉宾数据,并根据名字判断
def test_guest_models(self):
result = Guest.objects.get(phone='13711001101')
self.assertEqual(result.realname, "alen")
self.assertFalse(result.sign)

#写完测试用例后,执行测试用例。这里与unittest的运行方法也不一样。
#Django提供了“test”命令来运行测试。(用cmd执行 见下截图)

注意:刚刚在setup()部分操作时,其实并不会真正向数据库表中插入数据。所以,不用担心测试完后产生垃圾数据的问题。

如果:插入了表中没有定义的字段时,也是会报错提醒的! 

三。Django测试框架首选方法是使用python标准库中的unittest模块。




尽早进行单元测试(UnitTest)是比较好的做法,极端的情况甚至强调“测试先行”。现在我们已经有了第一个model类和Form类,是时候开始写测试代码了。

Django支持python的单元测试(unit test)和文本测试(doc test),我们这里主要讨论单元测试的方式。这里不对单元测试的理论做过多的阐述,假设你已经熟悉了下列概念:test suite, test case, test/test action,  test data, assert等等。

在单元测试方面,Django继承python的unittest.TestCase实现了自己的django.test.TestCase,编写测试用 例通常从这里开始。测试代码通常位于app的tests.py文件中(也可以在models.py中编写,但是我不建议这样做)。在Django生成的 depotapp中,已经包含了这个文件,并且其中包含了一个测试用例的样例:

depot/depotapp/tests.py

?
1
2
3
4
5
6
7
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1+ 1,2)

你可以有几种方式运行单元测试:

  • python manage.py test:执行所有的测试用例
  • python manage.py test app_name, 执行该app的所有测试用例
  • python manage.py test app_name.case_name: 执行指定的测试用例

用第三种方式执行上面提供的样例,结果如下:

?
1
$ python manage.pytest depotapp.SimpleTest
?
1
2
3
4
5
6
7
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.012s
  
OK
Destroying test database for alias 'default'...

你可能会主要到,输出信息中包括了创建和删除数据库的操作。为了避免测试数据造成的影响,测试过程会使用一个单独的数据库,关于如何指定测试数据库 的细节,请查阅Django文档。在我们的例子中,由于使用sqlite数据库,Django将默认采用内存数据库来进行测试。

下面就让我们来编写测试用例。在《Agile Web Development with Rails 4th》中,7.2节,最终实现的ProductTest代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class ProductTest < ActiveSupport::TestCase
test "product attributes must not be empty"do
product =Product.new
assert product.invalid?
assert product.errors[:title].any?
assert product.errors[:description].any?
assert product.errors[:price].any?
assert product.errors[:image_url].any?
end
test "product price must be positive"do
product =Product.new(:title =>"My Book Title",
:description => "yyy",
:image_url => "zzz.jpg")
product.price = -1
assert product.invalid?
assert_equal "must be greater than or equal to 0.01",
product.errors[:price].join('; ')
product.price = 0
assert product.invalid?
assert_equal "must be greater than or equal to 0.01",
product.errors[:price].join('; ')
product.price = 1
assert product.valid?
end
def new_product(image_url)
Product.new(:title=> "My Book Title",
:description => "yyy",
:price =>1,
:image_url => image_url)
end
test "image url"do
ok =%w{ fred.gif fred.jpg fred.png FRED.JPG FRED.Jpg
http://a.b.c/x/y/z/fred.gif }
bad =%w{ fred.doc fred.gif/more fred.gif.more }
ok.eachdo |name|
assert new_product(name).valid?, "#{name} shouldn't be invalid"
end
bad.eachdo |name|
assert new_product(name).invalid?, "#{name} shouldn't be valid"
end
end
test "product is not valid without a unique title"do
product =Product.new(:title => products(:ruby).title,
:description => "yyy",
:price =>1,
:image_url => "fred.gif")
assert !product.save
assert_equal "has already been taken", product.errors[:title].join('; ')
end
test "product is not valid without a unique title - i18n"do
product =Product.new(:title => products(:ruby).title,
:description => "yyy",
:price =>1,
:image_url => "fred.gif")
assert !product.save
assert_equal I18n.translate('activerecord.errors.messages.taken'),
product.errors[:title].join('; ')
end
end

对Product测试的内容包括:

1.title,description,price,image_url不能为空;

2. price必须大于零;

3. image_url必须以jpg,png,jpg结尾,并且对大小写不敏感;

4. titile必须唯一;

让我们在Django中进行这些测试。由于ProductForm包含了模型校验和表单校验规则,使用ProductForm可以很容易的实现上述测试:

depot/depotapp/tests.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#/usr/bin/python
#coding: utf8
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from forms import ProductForm
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1+ 1,2)
class ProductTest(TestCase):
def setUp(self):
self.product= {
'title':'My Book Title',
'description':'yyy',
'image_url':'http://google.com/logo.png',
'price':1
}
f =ProductForm(self.product)
f.save()
self.product['title']= 'My Another Book Title'
#### title,description,price,image_url不能为空
def test_attrs_cannot_empty(self):
f =ProductForm({})
self.assertFalse(f.is_valid())
self.assertTrue(f['title'].errors)
self.assertTrue(f['description'].errors)
self.assertTrue(f['price'].errors)
self.assertTrue(f['image_url'].errors)
####  price必须大于零
def test_price_positive(self):
f =ProductForm(self.product)
self.assertTrue(f.is_valid())
self.product['price']= 0
f =ProductForm(self.product)
self.assertFalse(f.is_valid())
self.product['price']= -1
f =ProductForm(self.product)
self.assertFalse(f.is_valid())
self.product['price']= 1
####  image_url必须以jpg,png,jpg结尾,并且对大小写不敏感;
def test_imgae_url_endwiths(self):
url_base ='http://google.com/'
oks =('fred.gif','fred.jpg', 'fred.png','FRED.JPG', 'FRED.Jpg')
bads =('fred.doc','fred.gif/more', 'fred.gif.more')
for endwith in oks:
self.product['image_url']= url_base+endwith
f =ProductForm(self.product)
self.assertTrue(f.is_valid(),msg='error when image_url endwith '+endwith)
for endwith in bads:
self.product['image_url']= url_base+endwith
f =ProductForm(self.product)
self.assertFalse(f.is_valid(),msg='error when image_url endwith '+endwith)
self.product['image_url']= 'http://google.com/logo.png'
###  titile必须唯一
def test_title_unique(self):
self.product['title']= 'My Book Title'
f =ProductForm(self.product)
self.assertFalse(f.is_valid())
self.product['title']= 'My Another Book Title'

然后运行 python manage.py test depotapp.ProductTest。如同预想的那样,测试没有通过:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Creating test database for alias 'default'...
.F..
======================================================================
FAIL: test_imgae_url_endwiths (depot.depotapp.tests.ProductTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/holbrook/Documents/Dropbox/depot/../depot/depotapp/tests.py", line 65, in test_imgae_url_endwiths
self.assertTrue(f.is_valid(),msg='error when image_url endwith '+endwith)
AssertionError: False is not True : error when image_url endwith FRED.JPG
  
----------------------------------------------------------------------
Ran 4 tests in 0.055s
  
FAILED (failures=1)
Destroying test database for alias 'default'...

因为我们之前并没有考虑到image_url的图片扩展名可能会大写。修改ProductForm的相关部分如下:

?
1
2
3
4
5
def clean_image_url(self):
url =self.cleaned_data['image_url']
ifnot endsWith(url.lower(),'.jpg', '.png','.gif'):
raise forms.ValidationError('图片格式必须为jpg、png或gif')
return url

然后再运行测试:

?
1
$ python manage.pytest depotapp.ProductTest
?
1
2
3
4
5
6
7
Creating test database for alias 'default'...
....
----------------------------------------------------------------------
Ran 4 tests in 0.060s
  
OK
Destroying test database for alias 'default'...

测试通过,并且通过单元测试,我们发现并解决了一个bug。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/473591.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Telegraf安装及使用

1 安装 1.1 创建用户 &#xff08;1&#xff09;添加用户 # useradd tigk # passwd tigk Changing password for user tigk. New password: BAD PASSWORD: The password is shorter than 8 characters Retype new password: passwd: all authentication tokens updated suc…

天池 在线编程 中位数

文章目录1. 题目2. 解题1. 题目 描述 给定一个长度为N的整数数组arr 返回一个长度为N的整数答案数组ans ans[i] 表示删除arr数组第i个数后&#xff0c;arr数组的中位数 N为偶数 2 < N < 10^5 示例 输入:[1,2,3,4,5,6] 输出:[4,4,4,3,3,3] 解释:删去1后 剩下的数组为[…

自动化运维Shell课堂笔记

1、课程回顾 2、课程大纲 1、shell编程 开发和运维 shell基础知识 shell变量 shell表达式 shell流程控制语句 2、代码发布 项目周期 代码部署的方式 代码部署流程 服务器环境部署 手工方式部署代码 脚本方式部署代码 3、shell 3.1、开发和运维 3.1.1 开发 开发是什么&…

InfluxDB安装及使用

1 安装 1.1 Tar包安装 &#xff08;1&#xff09;获取tar包 wget https://dl.influxdata.com/influxdb/releases/influxdb-1.8.0_linux_amd64.tar.gz&#xff08;2&#xff09;解压tar包   tar xvfz influxdb-1.8.0_linux_amd64.tar.gz $ su - tigk $ tar xvfz /opt/packa…

倒排索引原理和实现

关于倒排索引 搜索引擎通常检索的场景是&#xff1a;给定几个关键词&#xff0c;找出包含关键词的文档。怎么快速找到包含某个关键词的文档就成为搜索的关键。这里我们借助单词——文档矩阵模型&#xff0c;通过这个模型我们可以很方便知道某篇文档包含哪些关键词&#xff0c;某…

天池 在线编程 Character deletion

文章目录1. 题目2. 解题1. 题目 描述 Enter two strings and delete all characters in the second string from the first string 字符串长度&#xff1a;[1, 10^5] Example 1: Input: str”They are students”&#xff0c;sub”aeiou” Output: ”Thy r stdnts”来源&am…

【翻译】在Ext JS中创建特定主题的重写

Ext JS提供了大量的功能来使类的创建和处理变得简单&#xff0c;还提供了一系列的功能来扩展和重新现有的Javascript类。这意味着可以为类添加行为和创建属于自己的类&#xff0c;或者重写某些函数的行为。在本文&#xff0c;将展示如何实现特定主题类的重写。原文&#xff1a;…

Kapacitor安装及使用

1 安装 1.1 Tar包安装 &#xff08;1&#xff09;下载 wget https://dl.influxdata.com/kapacitor/releases/kapacitor-1.5.5_linux_amd64.tar.gz&#xff08;2&#xff09;安装 $ tar xvfz /opt/package/kapacitor-1.5.5-static_linux_amd64.tar.gz -C /home/tigk/.local/ …

Python答题:LinteCode简单题库(一)

366. 斐波纳契数列&#xff1a;查找斐波纳契数列中第 N 个数。 所谓的斐波纳契数列是指&#xff1a; 前2个数是 0 和 1 。 第 i 个数是第 i-1 个数和第i-2 个数的和。 斐波纳契数列的前10个数字是&#xff1a; 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ... 给定 1&#xff0c;返回 …

天池 在线编程 扫雷(BFS)

文章目录1. 题目2. 解题1. 题目 描述 现在有一个简易版的扫雷游戏&#xff0c;你将得到一个n*m大小的二维数组作为游戏地图。 每个位置上有一个值&#xff08;0或1&#xff0c;1代表此处没有雷&#xff0c;0表示有雷&#xff09;。 你将获得一个起点的位置坐标&#xff08;x&a…

Linux搭建高并发高可用Redis集群

安装Redis Redis 是一个高性能的key-value数据库。常用作缓存服务器使用。 1. 下载redis安装包&#xff0c;redis-3.2.11.tar.gz&#xff08;http://download.redis.io/releases/redis-3.2.11.tar.gz&#xff09; > wget http://download.redis.io/releases/redis-3.2.11.…

Flink简介

1 什么是Flink Apache Flink 是一个框架和分布式处理引擎&#xff0c;用于在无边界和有边界数据流上进行有状态的计算。Flink 能在所有常见集群环境中运行&#xff0c;并能以内存速度和任意规模进行计算。 它的主要特性包括&#xff1a;批流一体化、精密的状态管理、事件时间支…

Winform datagridview相关操作

datagridview显示行号的2种方法: 方法一&#xff1a; 网上最常见的做法是用DataGridView的RowPostPaint事件在RowHeaderCell中绘制行号&#xff1a; privatevoiddataGridView1_RowPostPaint(objectsender, DataGridViewRowPostPaintEventArgs e){try{e.Graphics.DrawString((e.…

天池 在线编程 旅行计划(暴力回溯)

文章目录1. 题目2. 解题1. 题目 描述 有n个城市&#xff0c;给出邻接矩阵arr代表任意两个城市的距离。 arr[i][j]代表从城市i到城市j的距离。Alice在周末制定了一个游玩计划&#xff0c;她从所在的0号城市开始&#xff0c;游玩其他的1 ~ n-1个城市&#xff0c;最后回到0号。 A…

初始化环境配置:CentOS 7.4x64 系统安装及基础配置

1.安装CentOS操作系统 ① 在进入系统引导后&#xff0c;会进入文字界面&#xff0c;选择install CentOS7 &#xff08;用键盘上的方向键↑、↓来选择要执行的操作&#xff0c;白色字体表示选中&#xff0c;按下回车&#xff0c;进入下一步操作&#xff09; ② 按回车执行安…

天池 在线编程 拿走瓶子(区间DP)

文章目录1. 题目2. 解题1. 题目 描述 有n个瓶子排成一列&#xff0c;用arr表示。 你每次可以选择能够形成回文连续子串的瓶子拿走&#xff0c;剩下的瓶子拼接在一起。 返回你能拿走所有的瓶子的最小次数。 n<500 arr[i]<1000示例 例1: 输入&#xff1a;[1,3,4,1,5] …

Flink运行时架构

1 运行时相关的组件 Flink运行时架构主要包括四个不同的组件&#xff1a;作业管理器&#xff08;JobManager&#xff09;、资源管理器&#xff08;ResourceManager&#xff09;、任务管理器&#xff08;TaskManager&#xff09;&#xff0c;以及分发器&#xff08;Dispatcher&a…

大型网站电商网站架构案例和技术架构的示例

大型网站架构是一个系列文档&#xff0c;欢迎大家关注。本次分享主题&#xff1a;电商网站架构案例。从电商网站的需求&#xff0c;到单机架构&#xff0c;逐步演变为常用的&#xff0c;可供参考的分布式架构的原型。除具备功能需求外&#xff0c;还具备一定的高性能&#xff0…

Spring JPA

http://files.cnblogs.com/weishuai90/spring.rar转载于:https://www.cnblogs.com/weishuai90/p/3567794.html

天池 在线编程 删除字符(单调栈)

文章目录1. 题目2. 解题1. 题目 描述 给定一个字符串str&#xff0c;现在要对该字符串进行删除操作&#xff0c; 保留字符串中的 k 个字符且相对位置不变&#xff0c;并且使它的字典序最小&#xff0c;返回这个子串。 示例 例1: 输入:str"fskacsbi",k2 输出:&quo…