#练习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. ACM-选人问题(救济金发放)

    n(n<20)个人站成一圈,逆时针编号为1-n.有两个官员,A从1开始逆时针数,B从n开 始顺时针数.在每一轮中,官员A数k个就停下来,官员B数m个就停下来(注意有可能两个 官员停在同一个人上) ...

  2. 了解一下express中间件的意思以及next()

    app.use()就是通常所说的使用中间件 一个请求发送到服务器后,它的生命周期是 先收到request(请求),然后服务端处理,处理完了以后发送response(响应)回去,而这个服务端处理的过程就 ...

  3. Git冲突:commit your changes or stash them before you can merge.

    用git pull来更新代码的时候,遇到了下面的问题: error: Your local changes to the following files would be overwritten by ...

  4. Day2----Jmeter 压测

    一.jmeter 压测1.一般压测时间为10-15分钟就行,设置时间在调度器配置--持续时间中设置,例如:想压10分钟,则持续时间输入:600 1.线程数:发送请求的用户数,即并发数 2.Ram-up ...

  5. P标签莫名有了margin-top值的原因

    p标签默认 -webkit-margin-after: 1em; -webkit-margin-before: 1em;元素上下边距数值为1倍字体高度 设置-webkit-margin-after: ...

  6. Python学习之路【第一篇】-Python简介和基础入门

    1.Python简介 1.1 Python是什么 相信混迹IT界的很多朋友都知道,Python是近年来最火的一个热点,没有之一.从性质上来讲它和我们熟知的C.java.php等没有什么本质的区别,也是 ...

  7. mysql 数据库的CUDR

    mysql删表和建表语句: DROP TABLE IF EXISTS `t_blog_user`;CREATE TABLE `t_blog_user` ( `id` int(11) NOT NULL ...

  8. CentOS配置教程

    1.配置网卡开机自动启动 查看/etc/sysconfig/network-scripts/ifcfg-eth0的初始内容: cat /etc/sysconfig/network-scripts/if ...

  9. axios API速查表

    原来jq自带ajax方法,但是近期项目用vue,在vue项目中发送ajax请求原来用vue resource,现在更推荐使用axios,因为axios和vue更配! GET 请求 // Make a ...

  10. tp框架 php ajax 登陆

    html 文件 <form class="form-signin loginform" role="form"> <input type=&q ...