【Python】unittest-4
#练习1:
import random
import unittest
from TestCalc import TestCalcFunctions
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range() def tearDown(self):
pass def test_choice(self):
# 从序列seq中随机选取一个元素
element = random.choice(self.seq)
# 验证随机元素确实属于列表中
self.assertTrue(element in self.seq) def test_sample(self):
# 验证执行的语句是否抛出了异常
with self.assertRaises(ValueError):
random.sample(self.seq, )
for element in random.sample(self.seq, ):
self.assertTrue(element in self.seq) class TestDictValueFormatFunctions(unittest.TestCase):
def setUp(self):
self.seq = range() def tearDown(self):
pass def test_shuffle(self):
# 随机打乱原seq的顺序
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range())
# 验证执行函数时抛出了TypeError异常
self.assertRaises(TypeError, random.shuffle, (, , )) if __name__ == '__main__':
# 根据给定的测试类,获取其中的所有以“test”开头的测试方法,并返回一个测试套件
suite1 = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
suite2 = unittest.TestLoader().loadTestsFromTestCase(TestDictValueFormatFunctions)
suite3 = unittest.TestLoader().loadTestsFromTestCase(TestCalcFunctions)
# 将多个测试类加载到测试套件中
suite = unittest.TestSuite([suite2, suite1,suite3]) #通过调整suit2和suite1的顺序,可以设定执行顺序
# 设置verbosity = ,可以打印出更详细的执行信息
unittest.TextTestRunner(verbosity = ).run(suite)
#练习2:
#会生成一个test.html文件
import unittest
import HTMLTestRunner
import math #被测试类
class Calc(object): def add(self, x, y, *d):
# 加法计算
result = x + y
for i in d:
result += i
return result def sub(self, x, y, *d):
# 减法计算
result = x - y
for i in d:
result -= i
return result #单元测试
class SuiteTestCalc(unittest.TestCase):
def setUp(self):
self.c = Calc() @unittest.skip("skipping")
def test_Sub(self):
print "sub"
self.assertEqual(self.c.sub(, , ), , u'求差结果错误!') def testAdd(self):
print "add"
self.assertEqual(self.c.add(, , ), , u'求和结果错误!') class SuiteTestPow(unittest.TestCase):
def setUp(self):
self.seq = range() # @unittest.skipIf()
def test_Pow(self):
print "Pow"
self.assertEqual(pow(, ), , u'求幂结果错误!') def test_hasattr(self):
print "hasattr"
# 检测math模块是否存在pow属性
self.assertTrue(hasattr(math, 'pow1'), u"检测的属性不存在!") if __name__ == "__main__":
suite1 = unittest.TestLoader().loadTestsFromTestCase(SuiteTestCalc)
suite2 = unittest.TestLoader().loadTestsFromTestCase(SuiteTestPow)
suite = unittest.TestSuite([suite1, suite2])
#unittest.TextTestRunner(verbosity=).run(suite)
filename = "c:\\test.html" # 定义个报告存放路径,支持相对路径。
# 以二进制方式打开文件,准备写
fp = file(filename, 'wb')
# 使用HTMLTestRunner配置参数,输出报告路径、报告标题、描述,均可以配
runner = HTMLTestRunner.HTMLTestRunner(stream = fp,
title = u'测试报告', description = u'测试报告内容')
# 运行测试集合
runner.run(suite)
#练习3:
import unittest
import random # 被测试类
class MyClass(object):
@classmethod
def sum(self, a, b):
return a + b @classmethod
def div(self, a, b):
return a / b @classmethod
def retrun_None(self):
return None # 单元测试类
class MyTest(unittest.TestCase): # assertEqual()方法实例
def test_assertEqual(self):
# 断言两数之和的结果
try:
a, b = ,
sum =
self.assertEqual(a + b, sum, '断言失败,%s + %s != %s' %(a, b, sum))
except AssertionError, e:
print e # assertNotEqual()方法实例
def test_assertNotEqual(self):
# 断言两数之差的结果
try:
a, b = ,
res =
self.assertNotEqual(a - b, res, '断言失败,%s - %s != %s' %(a, b, res))
except AssertionError, e:
print e # assertTrue()方法实例
def test_assertTrue(self):
# 断言表达式的为真
try:
self.assertTrue( == , "表达式为假")
except AssertionError, e:
print e # assertFalse()方法实例
def test_assertFalse(self):
# 断言表达式为假
try:
self.assertFalse( == , "表达式为真")
except AssertionError, e:
print e # assertIs()方法实例
def test_assertIs(self):
# 断言两变量类型属于同一对象
try:
a =
b = a
self.assertIs(a, b, "%s与%s不属于同一对象" %(a, b))
except AssertionError, e:
print e # test_assertIsNot()方法实例
def test_assertIsNot(self):
# 断言两变量类型不属于同一对象
try:
a =
b = "test"
self.assertIsNot(a, b, "%s与%s属于同一对象" %(a, b))
except AssertionError, e:
print e # assertIsNone()方法实例
def test_assertIsNone(self):
# 断言表达式结果为None
try:
result = MyClass.retrun_None()
self.assertIsNone(result, "not is None")
except AssertionError, e:
print e # assertIsNotNone()方法实例
def test_assertIsNotNone(self):
# 断言表达式结果不为None
try:
result = MyClass.sum(, )
self.assertIsNotNone(result, "is None")
except AssertionError, e:
print e # assertIn()方法实例
def test_assertIn(self):
# 断言对象B是否包含在对象A中
try:
strA = "this is a test"
strB = "is"
self.assertIn(strA, strB, "%s不包含在%s中" %(strB, strA))
except AssertionError, e:
print e # assertNotIn()方法实例
def test_assertNotIn(self):
# 断言对象B不包含在对象A中
try:
strA = "this is a test"
strB = "Selenium"
self.assertNotIn(strA, strB, "%s包含在%s中" %(strB, strA))
except AssertionError, e:
print e # assertIsInstance()方法实例
def test_assertIsInstance(self):
# 测试对象A的类型是否是指定的类型
try:
x = MyClass
y = object
self.assertIsInstance(x, y, "%s的类型不是%s".decode("utf-8") %(x, y))
except AssertionError, e:
print e # assertNotIsInstance()方法实例
def test_assertNotIsInstance(self):
# 测试对象A的类型不是指定的类型
try:
a =
b = str
self.assertNotIsInstance(a, b, "%s的类型是%s" %(a, b))
except AssertionError, e:
print e # assertRaises()方法实例
def test_assertRaises(self):
# 测试抛出的指定的异常类型
# assertRaises(exception)
with self.assertRaises(ValueError) as cm:
random.sample([,,,,], "j")
# 打印详细的异常信息
#print "===", cm.exception # assertRaises(exception, callable, *args, **kwds)
try:
self.assertRaises(ZeroDivisionError, MyClass.div, , )
except ZeroDivisionError, e:
print e # assertRaisesRegexp()方法实例
def test_assertRaisesRegexp(self):
# 测试抛出的指定异常类型,并用正则表达式具体验证
# assertRaisesRegexp(exception, regexp)
with self.assertRaisesRegexp(ValueError, 'literal') as ar:
int("xyz")
# 打印详细的异常信息
#print ar.exception
# 打印正则表达式
#print "re:",ar.expected_regexp # assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
try:
self.assertRaisesRegexp(ValueError, "invalid literal for.*XYZ'$",int,'XYZ')
except AssertionError, e:
print e if __name__ == '__main__':
# 执行单元测试
unittest.main()
【Python】unittest-4的更多相关文章
- 【python】unittest中常用的assert语句
下面是unittest模块的常用方法: assertEqual(a, b) a == b assertNotEqual(a, b) a != b assertTrue(x) b ...
- 【Python②】python之首秀
第一个python程序 再次说明:后面所有代码均为Python 3.3.2版本(运行环境:Windows7)编写. 安装配置好python后,我们先来写第一个python程序.打开IDLE (P ...
- 【python】多进程锁multiprocess.Lock
[python]多进程锁multiprocess.Lock 2013-09-13 13:48 11613人阅读 评论(2) 收藏 举报 分类: Python(38) 同步的方法基本与多线程相同. ...
- 【python】SQLAlchemy
来源:廖雪峰 对比:[python]在python中调用mysql 注意连接数据库方式和数据操作方式! 今天发现了个处理数据库的好东西:SQLAlchemy 一般python处理mysql之类的数据库 ...
- 【python】getopt使用
来源:http://blog.chinaunix.net/uid-21566578-id-438233.html 注意对比:[python]argparse模块 作者:limodou版权所有limod ...
- 【Python】如何安装easy_install?
[Python]如何安装easy_install? http://jingyan.baidu.com/article/b907e627e78fe146e7891c25.html easy_instal ...
- 【Python】 零碎知识积累 II
[Python] 零碎知识积累 II ■ 函数的参数默认值在函数定义时确定并保存在内存中,调用函数时不会在内存中新开辟一块空间然后用参数默认值重新赋值,而是单纯地引用这个参数原来的地址.这就带来了一个 ...
- 【Python】-NO.97.Note.2.Python -【Python 基本数据类型】
1.0.0 Summary Tittle:[Python]-NO.97.Note.2.Python -[Python 基本数据类型] Style:Python Series:Python Since: ...
- 【Python】-NO.99.Note.4.Python -【Python3 条件语句 循环语句】
1.0.0 Summary Tittle:[Python]-NO.99.Note.4.Python -[Python3 条件语句 循环语句] Style:Python Series:Python Si ...
- 【Python】-NO.98.Note.3.Python -【Python3 解释器、运算符】
1.0.0 Summary Tittle:[Python]-NO.98.Note.3.Python -[Python3 解释器] Style:Python Series:Python Since:20 ...
随机推荐
- node模块之net模块——socket
当我们去面试的时候,常常会遇到这样一个问题:当用户在浏览器地址栏输入一段url发出资源请求后,到服务端返回数据呈现给用户的这个过程都发生了什么? 我们把进行通信的这两个端(这里指的是,浏览器和资源获取 ...
- SpringBoot项目Shiro的实现(二)
在看此小节前,您可能需要先看:http://www.cnblogs.com/conswin/p/7478557.html 紧接上一篇,在上一篇我们简单实现了一个Springboot的小程序,但我们发现 ...
- CRS添加、删除节点
一.如何删除一个节点: 1.1 在存活的节点上操作,使用dbca删除DB实例 1.2 清除ASM实例 在存活的节点上做如下操作 1.2.1 停止ASM实例 export ORACLE_HOM ...
- UI基础七:给普通其他界面的PRODUCT 添加标准的搜索帮助
在使用的组件中添加组件对象 Outbound Plug中添加外向连接:OP_PRODUCT METHOD op_product. DATA: lv_title TYPE string, lr_cont ...
- 62. Unique Paths不同路径
网址:https://leetcode.com/problems/unique-paths/ 第一思路是动态规划 通过观察,每一个格子的路线数等于相邻的左方格子的路线数加上上方格子的路线数 于是我们就 ...
- [contest 781] 9.6
[contest 781] 9.6 - XJOI czx的温暖题... T1 军训
- 深入浅出php socket编程
对TCP/IP.UDP.Socket编程这些词你不会很陌生吧?随着网络技术的发展,这些词充斥着我们的耳朵.那么我想问: 1.什么是TCP/IP.UDP?2.Socket在哪里呢?3.Socket是什么 ...
- [x] 封装、继承,多态
那么多态的作用是什么呢,封装可以使得代码模块化,继承可以扩展已存在的代码,他们的目的都是为了代码重用. 而多态的目的则是为了接口重用.也就是说,不论传递过来的究竟是那个类的对象,函数都能够通过同一个接 ...
- bzoj5016
题解: 吧询问变成前缀形式 然后莫队 代码: #include<bits/stdc++.h> ; using namespace std; ]; ,L=,R=; ,Ans[N]; bool ...
- HTML(五)选择器--伪类选择器
HTML代码 <body> <a href="www.baidu.com">www.baidu.com</a> </body> CS ...