#练习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的更多相关文章

  1. 【python】unittest中常用的assert语句

    下面是unittest模块的常用方法: assertEqual(a, b)     a == b assertNotEqual(a, b)     a != b assertTrue(x)     b ...

  2. 【Python②】python之首秀

       第一个python程序 再次说明:后面所有代码均为Python 3.3.2版本(运行环境:Windows7)编写. 安装配置好python后,我们先来写第一个python程序.打开IDLE (P ...

  3. 【python】多进程锁multiprocess.Lock

    [python]多进程锁multiprocess.Lock 2013-09-13 13:48 11613人阅读 评论(2) 收藏 举报  分类: Python(38)  同步的方法基本与多线程相同. ...

  4. 【python】SQLAlchemy

    来源:廖雪峰 对比:[python]在python中调用mysql 注意连接数据库方式和数据操作方式! 今天发现了个处理数据库的好东西:SQLAlchemy 一般python处理mysql之类的数据库 ...

  5. 【python】getopt使用

    来源:http://blog.chinaunix.net/uid-21566578-id-438233.html 注意对比:[python]argparse模块 作者:limodou版权所有limod ...

  6. 【Python】如何安装easy_install?

    [Python]如何安装easy_install? http://jingyan.baidu.com/article/b907e627e78fe146e7891c25.html easy_instal ...

  7. 【Python】 零碎知识积累 II

    [Python] 零碎知识积累 II ■ 函数的参数默认值在函数定义时确定并保存在内存中,调用函数时不会在内存中新开辟一块空间然后用参数默认值重新赋值,而是单纯地引用这个参数原来的地址.这就带来了一个 ...

  8. 【Python】-NO.97.Note.2.Python -【Python 基本数据类型】

    1.0.0 Summary Tittle:[Python]-NO.97.Note.2.Python -[Python 基本数据类型] Style:Python Series:Python Since: ...

  9. 【Python】-NO.99.Note.4.Python -【Python3 条件语句 循环语句】

    1.0.0 Summary Tittle:[Python]-NO.99.Note.4.Python -[Python3 条件语句 循环语句] Style:Python Series:Python Si ...

  10. 【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 ...

随机推荐

  1. 我的第一个C语言程序

    从自学开始到现在应该有块一个月了,之前一直想要写博客一直没想好要自己建博客还是找平台来写.现在想想 其实都一样,不论在哪里,都可以记录自己学习的成长记录.这是我的第一篇关于C语言学习的博客,希望这只是 ...

  2. jquery获取和设置值

    1.html html() :   取得第一个匹配元素的html内容. html(value): 设置每一个匹配元素的html内容 2text text() :  取得所有匹配元素的内容,结果是由所有 ...

  3. acl使用示例

    declare   v_count  number;  uprinciple varchar2(20);  principle  varchar2(20);  begin uprinciple := ...

  4. UI基础一:简单的BOL查询

    利用标准的BOL编辑工具,添加BOL对象,重写查询方法,实现简答的BOL查询 1.SE11创建查询对象结构: 2.SE11创建查询结果对象: 3.SE24新建处理类: 重写查询结果方法: METHOD ...

  5. MinGW安装教程( MinGW - Minimalist GNU for Windows)

    首先说明一下 1) MinGw只是其中一种GCC编译环境的安装程序,还有像Cygwin也是差不多的; 2) 还要就是安装MinGw,最好在一个网络比较好的环境中进行,  (有可能导致后来安装其他软件像 ...

  6. [LeetCode] 108. Convert Sorted Array to Binary Search Tree ☆(升序数组转换成一个平衡二叉树)

    108. Convert Sorted Array to Binary Search Tree 描述 Given an array where elements are sorted in ascen ...

  7. Http Header Content-Typ

    Http Header里的Content-Type一般有这三种:application/x-www-form-urlencoded:数据被编码为名称/值对.这是标准的编码格式.multipart/fo ...

  8. weblogic隐藏版本号教程(10.3.6为例)

    隐藏版本号,如同大多数中间件都是取消Server头的发送:weblogic而言其默认就是不发送Server头的(即下边的“发送服务器标头”默认就是没钩选的). 写此教程的原因,一是以防Server头被 ...

  9. SpringBoot的日志

    1.日志框架小张:开发一个大型系统:1.System.out.pringtln("");将关键数据打印在控制台:去掉?写在一个文件?2.框架来记录系统的一些运行信息:日志:zhan ...

  10. centos6.5 安装php-5.6.31

    1 从PHP官网下载所需要的PHP版本 下载地址:  http://php.net/get/php-5.6.31.tar.gz/from/a/mirror  把下载好的文件上传到服务器 2 安装PHP ...