#练习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. vue项目中引入第三方框架

    element-ui npm install element-ui -- save; main.js中 import Element from 'element-ui'; import 'elemen ...

  2. VMware(虚拟机) 12版安装深度linux系统

    需要的工具: 1.VM ware workstation12虚拟机(可自行百度下载)  参考:VMware Workstation 12.5.5 官方中文正式版,下载地址:http://www.epi ...

  3. opencv 中的mat类(非原创)

    Mat最大的优势跟STL很相似,都是对内存进行动态的管理,不需要之前用户手动的管理内存,Mat这个类有两部分数据.一个是matrix header(矩阵头),这部分的大小是固定的,包含矩阵的大小,存储 ...

  4. html5 meta标签的认知储备

    在开发移动或者PC端的时候除了'<meta charset="UTF-8">'这个设置编码格式的meta标签,还有一些其他方面的设置 一.<meta name=& ...

  5. Oracle查询前几条数据的方法

    在Oracle中实现select top N:由于Oracle不支持select top 语句,所以在Oracle中经常是用order by 跟rownum的组合来实现select top n的查询. ...

  6. Spring注解之BeanPostProcessor与InitializingBean

    /*** BeanPostProcessor 为每个bean实例化时提供个性化的修改,做些包装等*/ package org.springframework.beans.factory.config; ...

  7. CentOS是哪个版本 CentOS版本信息查看技巧

    root@MyMail ~ # uname Linux root@MyMail ~ # uname -r 2.6.18-164.el5 [root@localhost ~]# uname -a Lin ...

  8. \x 和 0x 的区别

    1.0x 表示整型数值 (十六进制) char c = 0x42; 表示的是一个数值(字母B对应的ASCII码——  66),可以认为等价于: int c = 0x42; 2.\x42用于字符表达,或 ...

  9. laravel注册行为的方法和逻辑

    public function register() { //验证: $this->validate(\request(), [ 'name' => 'required|min:3|uni ...

  10. laravel的工厂模式数据填充:

    数据表post中的字段结构. database\factory\UserFactory.php $factory->define(App\Post::class,function (Faker ...