import unittest

class UTest(unittest.TestCase):
def test_upper(self):
  self.assertEqual('foo'.upper(), 'FOO')   def test_isupper(self):
    self.assertTrue('FOO'.isupper())
    self.assertFalse('Foo'.isupper()) if __name__ == '__main__':
unittest.main()
注:
0. unnitest 是 python 自带的库,不需要额外的安装即可用
 
1. 测试用例 (testcase) 都是由 unittest.TestCase 类创建的,对应的 test 开头的 测试方法, 如上例的 test_upper
 
2. setUp() and tearDown() 方法用来定义一些初始化和清理的 指令, 这两个方法分别在 每个测试用例 开始前和结束后执行。
如果只要在所有的测试用例之前和之后只执行一次,则用 setUpClass() 和 tearDownClass()
如果所有的测试用例都需要执行的一些共同步骤可以放在setUp(), 如果做一次就对所有的测试用例生效的就放在setUpClass(),譬如登陆(coolie对所有的测试用例都可以共享)
setupClass() 和 tearDownClass() 必需加上装饰器 @classmethod, 否则会出错。 setUp() 和 tearDown() 则不用。
 
3. unittest.main()提供了一个测试脚本的命令行接口。
 
4. 其他途径运行测试用例有:
suite = unittest.TestLoader().loadTestsFromTestCase(UTest)
unittest.TextTestRunner(verbosity=2).run(suite)
5. 命令行: python -m unittest test_module.TestClass 和 python -m unittest test_module.TestClass.test_method
如上面的例子:python -m unittest UTest.UTest
python -m unittest UTest.UTest.test_upper
 
还可以传一个 -v 标志 来获取 更详细的测试结果:python -m unittest -v test_module
如上例: D:\Python>python -m unittest -v UTest
结果: test_isupper (UTest.UTest) ... ok
test_upper (UTest.UTest) ... ok
 
6. 要运行一个class 里的 所有测试用例(所有test开头的方法),有以下几种方法:
A. unittest.main() 对应的命令行 是 ptyon module.py
B. suite = unittest.TestLoader().loadTestsFromTestCase(UTest)
unittest.TextTestRunner(verbosity=2).run(suite)
对应的命令行是 python -m unittest test_module.TestClass
C. 新建一个TestSuite 实例,然后一个一个的把所有的测试用例加到这个测试集,最后通过 TextTestRunner 这个对象的run方法运行测试集
如,此方法比较繁琐,加入有50个测试用例,需要手动的把50个用例一个一个的加到TestSuite 里
suite = unittest.TestSuite()
suite.addTest(UTest('test_isupper'))
suite.addTest(UTest('test_upper'))
runner = unittest.TextTestRunner()
runner.run(suite)

但是,如果是class 里只有一个测试方法,但测试时需要不同的测试数据,C 的方法派上用场:

a.首先,重写TestCase类的构造函数,把input 作为构造函数的参数(由于测试方法不能传参数,所以只能在构造函数里传入需要的input),如:
def __init__(self, marketcode, stockcode, stocktype,methodName):
super(Comparison, self).__init__(methodName)
self.marketcode = marketcode
self.stockcode = stockcode
self.stocktype = stocktype
 
b. 然后是测试用例方法对input的引用
def test_getPriceInfo(self):
stime = Utils.getTimestamp()
mkt_price = ParseResponse.getMarketLastPrice(self.marketcode,self.stockcode,self.stocktype)
position_price = ParseResponse.getPositionLastPrice(self.loginKey,self.loginCookie,self.stockcode,self.marketcode)
self.infoDir["timestamp"] = stime
self.infoDir["ticker"] = self.marketcode + self.stockcode
self.infoDir["postionprice"] = position_price
self.infoDir["marketprice"] = mkt_price
AlertRecorder.cmpMktPosition(self.infoDir)
print self.infoDir

c. 最后在class 外定义一个运行的方法,其中 Comparison(stockInfo[0],stockInfo[1],stockInfo[2], "test_getPriceInfo") 即是创建一个测试类示例,test_getPriceInfo为测试用例方法名,这个是 unittest.TestCase类需要的参数。

def run():
suite = unittest.TestSuite()
stockInfoList = Scheduler.get_mktPostion_stocks()
for stockInfo in stockInfoList:
suite.addTest(Comparison(stockInfo[0],stockInfo[1],stockInfo[2], "test_getPriceInfo"))
runner = unittest.TextTestRunner()
runner.run(suite)
综上,封装起来为:
A. .main(verbosity=2), 其中verbosity=2 是使得结果输出时更详细
B.
def run():
  suite = unittest.TestLoader().loadTestsFromTestCase(testCaseClassName)
  runner = unittest.TextTestRunner(verbosity=2)
  runner.run(suite)
C.
def run():
  suite = unittest.TestSuite()
  suite.addTest(testCaseClassName('test_method'))
  runner = unittest.TextTestRunner(verbosity=2)
  runner.run(suite)
注意:上述三个运行测试的方法,在IDE上的输出结果有点差别。A 和 C 输出的结果:
set up for class
test_isupper (__main__.UTest) ... ok
test_sum (__main__.UTest) ... ok
test_upper (__main__.UTest) ... ok
 
而B输出结果为:
test_sum (__main__.UTest) ... ok
test_upper (__main__.UTest) ... ok
set up for class
test_isupper (__main__.UTest) ... ok
 
优先还是用 unittest.main() 和 unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(testCaseClassName))
 
 
7. 如果要跳过测试,则可以用到 装饰器 @unittest.skip("reason") 和 @unittest.skipIf(condition,'reason'). 如果是针对个别测试用例,则在 测试用例方法加装饰器。如果需要跳过所有的测试(譬如节假日)则在 setUpClass 上加装饰器。这种情况下得注意两个装饰器的先后顺序,先@classmethod 后 @unittest.skipIf()。如:
@classmethod
@unittest.skipIf(True, "To skip the test")
def setUpClass(cls):
print 'set up for class'
 
另外,setUp()也可以跳过所有的测试,不过和 setUpClass 有区别: setUpClass 是一次性跳过所有的测试,运行结果显示运行0个测试: Ran 0 tests in 0.000s OK (skipped=1)
但setUp 则是每个测试用例都跳过运行,显示结果是跑了N 个,跳过N 个:
test_isupper (__main__.UTest) ... skipped '...reason...'
test_sum (__main__.UTest) ... skipped '...reason...'
test_upper (__main__.UTest) ... skipped '...reason...'
 
 
8. 如果要获得测试结果中运行的测试用例的总数以及成功和失败的总数,可以从unittest.TestResult 中获得 失败的个数和运行的总数
suite = unittest.TestLoader().loadTestsFromTestCase(UTest)
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
print result.testsRun #运行的测试用例的总数
print len(result.failures) #失败的测试用例的数目
关于 failures: A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test where a failure was explicitly
signalled using the TestCase.assert*() methods.

Python unittest 学习的更多相关文章

  1. XUnit测试框架-Python unittest

    选择 语言选择 本次个人作业我选择的语言是Python,了解学习Python有一段时间了但是一直没有练习,所以这次玩蛇,使用的版本是Python3.6. 开发工具选择 我选择的IDE是Pycharm, ...

  2. python+appium学习总结

    经过了这个月的学习,今天终于完成了公司APP系统的自动化的脚本的编写. 通过单元测试框架UNITTEST,进行脚本的连跑,本来还想把测试数据统一写到EXCEL表格内,实现脚本与数据的分离. 后来发现增 ...

  3. 【原】Learning Spark (Python版) 学习笔记(三)----工作原理、调优与Spark SQL

    周末的任务是更新Learning Spark系列第三篇,以为自己写不完了,但为了改正拖延症,还是得完成给自己定的任务啊 = =.这三章主要讲Spark的运行过程(本地+集群),性能调优以及Spark ...

  4. 60分钟Python快速学习(给发哥一个交代)

    60分钟Python快速学习 之前和同事谈到Python,每次下班后跑步都是在听他说,例如Python属于“胶水语言啦”,属于“解释型语言啦!”,是“面向对象的语言啦!”,另外没有数据类型,逻辑全靠空 ...

  5. python爬虫学习(1) —— 从urllib说起

    0. 前言 如果你从来没有接触过爬虫,刚开始的时候可能会有些许吃力 因为我不会从头到尾把所有知识点都说一遍,很多文章主要是记录我自己写的一些爬虫 所以建议先学习一下cuiqingcai大神的 Pyth ...

  6. python爬虫学习 —— 总目录

    开篇 作为一个C党,接触python之后学习了爬虫. 和AC算法题的快感类似,从网络上爬取各种数据也很有意思. 准备写一系列文章,整理一下学习历程,也给后来者提供一点便利. 我是目录 听说你叫爬虫 - ...

  7. Python正则表达式学习摘要及资料

    摘要 在正则表达式中,如果直接给出字符,就是精确匹配. {m,n}? 对于前一个字符重复 m 到 n 次,并且取尽可能少的情况 在字符串'aaaaaa'中,a{2,4} 会匹配 4 个 a,但 a{2 ...

  8. python 线程学习

    彩照 一.学习[1] # -*- coding: utf-8 -*- import time import thread def timer(no, interval): cnt = 0 while ...

  9. Openstack python api 学习文档 api创建虚拟机

    Openstack python api 学习文档 转载请注明http://www.cnblogs.com/juandx/p/4953191.html 因为需要学习使用api接口调用openstack ...

随机推荐

  1. HDU4576 Robot(概率)

    题意 抄袭自https://www.cnblogs.com/Paul-Guderian/p/7624039.html  多组输入n,m,l,r.表示在一个环上有n个格子.接下来输入m个w表示连续的一段 ...

  2. 安卓6.0之前的系统 判断app是否有录音权限

    public static synchronized boolean isVoicePermission() { AudioRecord record = null; try { record = n ...

  3. css水平垂直居中的几个方法和技巧/居中之美

    水平居中设置-行内元素     我们在实际工作中常会遇到需要设置水平居中场景,今天我们就来看看怎么设置水平居中的. 如果被设置元素为文本.图片等行内元素时,水平居中是通过给父元素设置 text-ali ...

  4. mysql同步出现1062错误

    SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;slave start;show slave status \G执行多次,直到不会出现1062错误为止 或者: my.cnf s ...

  5. IOS拉伸之底盖设置

    1.选定拉伸 UIImageView *fieldImage=[[UIImageViewalloc]initWithFrame:CGRectMake(37,48+35,240, 32)]; field ...

  6. red5 重新分配 ip

    root@hett-OptiPlex-7040:~# ll /usr/local/src/red5/conf/total 144drwxr-xr-x 2 root root  4096  1月  9 ...

  7. Android的Activity之间传对象的方法

    传值代码块 //Serializeable传递对象的方法 public void SerializeMethod(){ Person mPerson = new Person(); mPerson.s ...

  8. iOS 随机数(Fixed)

    ios 有如下三种随机数方法: 1.    srand((unsigned)time(0));  //不加这句每次产生的随机数不变         int i = rand() % 5; 2.     ...

  9. pb2.text_format.Merge(f.read(), self.solver_param) AttributeError: 'module' object has no attribute 'text_format'

    http://blog.csdn.net/qq_33202928/article/details/72526710

  10. Linux文件的IO操作 一

    系统调用 系统调用: 操作系统提供给用户程序调用的一组“特殊”接口,用户程序可以通过这组“特殊”接口来获得操作系统内核提供的服务 为什么用户程序不能直接访问系统内核提供的服务 为了更好地保护内核空间, ...