zoukankan      html  css  js  c++  java
  • python单元测试之unittest框架使用总结

     

    一、什么是单元测试

    单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作。

    比如对于函数abs(),我们可以编写的测试用例为:

    (1)输入正数,比如1、1.2、0.99,期待返回值与输入相同

    (2)输入复数,比如-1、-1.2、-0.99,期待返回值与输入相反

    (3)输入0,期待返回0

    (4)输入非数值类型,比如None、[]、{}、期待抛出TypeError

    把上面这些测试用例放到一个测试模块里,就是一个完整的单元测试

     

    二、unittest工作原理

    unittest中最核心的四部分是:TestCase,TestSuite,TestRunner,TestFixture

    (1)一个TestCase的实例就是一个测试用例。测试用例就是指一个完整的测试流程,包括测试前准备环境的搭建(setUp),执行测试代码(run),以及测试后环境的还原(tearDown)。元测试(unit test)的本质也就在这里,一个测试用例是一个完整的测试单元,通过运行这个测试单元,可以对某一个问题进行验证。

    (2)而多个测试用例集合在一起,就是TestSuite,而且TestSuite也可以嵌套TestSuite。

    (3)TestLoader是用来加载TestCase到TestSuite中的。

    (4)TextTestRunner是来执行测试用例的,其中的run(test)会执行TestSuite/TestCase中的run(result)方法

    (5)测试的结果会保存到TextTestResult实例中,包括运行了多少测试用例,成功了多少,失败了多少等信息。

     

    综上,整个流程就是首先要写好TestCase,然后由TestLoader加载TestCase到TestSuite,然后由TextTestRunner来运行TestSuite,运行的结果保存在TextTestResult中,整个过程集成在unittest.main模块中。

     

    三、下面举两个实例,来看看unittest如何测试一个简单的函数

    (1)编写一个Dict类,这个类的行为和dict一致,但是可以通过属性来访问例如

     

    [python] view plain copy
     
    1. >>> d = Dict(a=1, b=2)  
    2. >>> d['a']  
    3. 1  
    4. >>> d.a  
    5. 1  

    mydict.py代码如下:

     

    [python] view plain copy
     
    1. class Dict(dict):  
    2.     def __init__(self, **kw):  
    3.         super(Dict, self).__init__(**kw)  
    4.    
    5.     def __getattr__(self, key):  
    6.         try:  
    7.             return self[key]  
    8.         except KeyError:  
    9.             raise AttributeError(r"'Dict' object has no attribute '%s'" % key)  
    10.    
    11.     def __setattr__(self, key, value):  
    12.         self[key] = value  
    13.    


    用于测试的文件mydict_test.py代码如下:

     

    [python] view plain copy
     
    1. import unittest  
    2. from mydict import Dict  
    3.    
    4.    
    5. class TestDict(unittest.TestCase):  
    6.     def test_init(self):  
    7.         d = Dict(a=1, b='test')  
    8.         self.assertEqual(d.a, 1)  # 判断d.a是否等于1  
    9.         self.assertEqual(d.b, 'test')  # 判断d.b是否等于test  
    10.         self.assertTrue(isinstance(d, dict))  # 判断d是否是dict类型  
    11.    
    12.     def test_key(self):  
    13.         d = Dict()  
    14.         d['key'] = 'value'  
    15.         self.assertEqual(d.key, 'value')  
    16.    
    17.     def test_attr(self):  
    18.         d = Dict()  
    19.         d.key = 'value'  
    20.         self.assertTrue('key' in d)  
    21.         self.assertEqual(d['key'], 'value')  
    22.    
    23.     def test_keyerror(self):  
    24.         d = Dict()  
    25.         with self.assertRaises(KeyError):  # 通过d['empty']访问不存在的key时,断言会抛出keyerror  
    26.             value = d['empty']  
    27.    
    28.     def test_attrerror(self):  
    29.         d = Dict()  
    30.         with self.assertRaises(AttributeError):  # 通过d.empty访问不存在的key时,我们期待抛出AttributeError  
    31.             value = d.empty  
    32.    
    33.    
    34. if __name__ == '__main__':  
    35.     unittest.main()  


    直接把mydict_test.py当普通的Python脚本运行即可

    输出:

     

    [python] view plain copy
     
    1. .....  
    2. ----------------------------------------------------------------------  
    3. Ran 5 tests in 0.000s  
    4.    
    5. OK  


    (2)测一个简单的加减乘除接口

    mathfunc.py文件代码如下:

     

    [python] view plain copy
     
    1. def add(a, b):  
    2.     return a + b  
    3.    
    4. def minus(a, b):  
    5.     return a - b  
    6.    
    7. def multi(a, b):  
    8.     return a * b  
    9.    
    10. def divide(a, b):  
    11.     return a / b  

    test_mathfunc.py文件代码如下:

     

    [python] view plain copy
     
    1. import unittest  
    2. from mathfunc import *  
    3.    
    4.    
    5. class TestMathFunc(unittest.TestCase):  
    6.    
    7.     def test_add(self):  
    8.         self.assertEqual(3, add(1, 2))  
    9.         self.assertNotEqual(3, add(2, 2))  
    10.    
    11.     def test_minus(self):  
    12.         self.assertEqual(1, minus(3, 2))  
    13.    
    14.     def test_multi(self):  
    15.         self.assertEqual(6, multi(3, 2))  
    16.    
    17.     def test_divide(self):  
    18.         self.assertEqual(2, divide(6, 3))  
    19.         self.assertEqual(2.5, divide(5, 2))  
    20.    
    21. if __name__ == '__main__':  
    22. <span style="white-space:pre;"> </span>unittest.main()  

    输出:

     

    [python] view plain copy
     
    1. .F..  
    2. ======================================================================  
    3. FAIL: test_divide (__main__.TestDict)  
    4. ----------------------------------------------------------------------  
    5. Traceback (most recent call last):  
    6.   File "D:/pythonWorkspace/test_mathfunc.py", line 20, in test_divide  
    7.     self.assertEqual(2.5, divide(5, 2))  
    8. AssertionError: 2.5 != 2  
    9.    
    10. ----------------------------------------------------------------------  
    11. Ran 4 tests in 0.000s  
    12.    
    13. FAILED (failures=1)  

    可以看到一共运行了4个测试,失败了1个,并且给出了失败原因,2.5!=2,也就是说我们的divide方法是有问题的。

     

    关于输出的几点说明:

    1、在第一行给出了每一个用例执行的结果的标识,成功是.,失败是F,出错是E,跳过是S。从上面可以看出,测试的执行跟方法的顺序没有关系,divide方法写在了第4个,但是却在第2个执行。

    2、每个测试方法均以test开头,否则不能被unittest识别

    3、在uniitest.main()中加verbosity参数可以控制输出的错误报告的详细程度,默认是1,如果设为0, 则不输出每一用例的执行结果,即没有上面的结果中的第1行,如果设为2,则输出详细的执行结果,如下所示:

     

     

    [python] view plain copy
     
    1. test_add (__main__.TestMathFunc) ... ok  
    2. test_divide (__main__.TestMathFunc) ... FAIL  
    3. test_minus (__main__.TestMathFunc) ... ok  
    4. test_multi (__main__.TestMathFunc) ... ok  
    5.    
    6. ======================================================================  
    7. FAIL: test_divide (__main__.TestMathFunc)  
    8. ----------------------------------------------------------------------  
    9. Traceback (most recent call last):  
    10.   File "D:/pythonWorkspace/test_mathfunc.py", line 20, in test_divide  
    11.     self.assertEqual(2.5, divide(5, 2))  
    12. AssertionError: 2.5 != 2  
    13.    
    14. ----------------------------------------------------------------------  
    15. Ran 4 tests in 0.000s  
    16.    
    17. FAILED (failures=1)  


    四、组织TestSuite

    上面的测试用例在执行的时候没有按照顺序执行,如果想要让用例按照你设置的顺序执行就用到了TestSuite。我们添加到TestSuite中的case是会按照添加的顺序执行的。

    现在我们只有一个测试文件,如果有多个测试文件,也可以用TestSuite组织起来。

    继续上面第二加减乘除的例子,现在再新建一个文件,test_suite.py,代码如下:

     

    [python] view plain copy
     
    1. # coding=utf-8  
    2. import unittest  
    3. from test_mathfunc import TestMathFunc  
    4.    
    5. if __name__ == '__main__':  
    6.     suite = unittest.TestSuite()  
    7.    
    8.     tests = [TestMathFunc("test_add"), TestMathFunc("test_minus"), TestMathFunc("test_divide")]  
    9.     suite.addTests(tests)  
    10.    
    11.     runner = unittest.TextTestRunner(verbosity=2)  
    12.     runner.run(suite)  

    执行结果如下:

     

    [python] view plain copy
     
    1. test_add (test_mathfunc.TestMathFunc) ... ok  
    2. test_minus (test_mathfunc.TestMathFunc) ... ok  
    3. test_divide (test_mathfunc.TestMathFunc) ... FAIL  
    4.    
    5. ======================================================================  
    6. FAIL: test_divide (test_mathfunc.TestMathFunc)  
    7. ----------------------------------------------------------------------  
    8. Traceback (most recent call last):  
    9.   File "D:pythonWorkspaceHTMLTest est_mathfunc.py", line 20, in test_divide  
    10.     self.assertEqual(2.5, divide(5, 2))  
    11. AssertionError: 2.5 != 2  
    12.    
    13. ----------------------------------------------------------------------  
    14. Ran 3 tests in 0.000s  
    15.    
    16. FAILED (failures=1)  

    五、将结果输出到文件

    现在我们的测试结果只能输出到控制台,现在我们想将结果输出到文件中以便后续可以查看。

    将test_suite.py进行一点修改,代码如下:

     

    [python] view plain copy
     
    1. # coding=utf-8  
    2.    
    3. import unittest  
    4. from test_mathfunc import TestMathFunc  
    5.    
    6. if __name__ == '__main__':  
    7.     suite = unittest.TestSuite()  
    8.    
    9.     tests = [TestMathFunc("test_add"), TestMathFunc("test_minus"), TestMathFunc("test_divide")]  
    10.     suite.addTests(tests)  
    11.    
    12.     with open('UnittestTextReport.txt', 'a') as  f:  
    13.         runner = unittest.TextTestRunner(stream=f, verbosity=2)  
    14.         runner.run(suite)  
    15.    

    运行该文件,就会发现目录下生成了'UnittestTextReport.txt,所有的执行报告均输出到了此文件中。

     

    六、test fixture的setUp和tearDown

    当遇到要启动一个数据库这种情况时,只想在开始时连接上数据库,在结束时关闭连接。那么可以使用setUp和tearDown函数。

     

    [python] view plain copy
     
    1. class TestDict(unittest.TestCase):  
    2.    
    3.     def setUp(self):  
    4.         print 'setUp...'  
    5.    
    6.     def tearDown(self):  
    7.         print 'tearDown...'  


    这两个方法在每个测试方法执行前以及执行后执行一次,setUp用来为测试准备环境,tearDown用来清理环境,以备后续的测试。

     

    如果想要在所有case执行之前准备一次环境,并在所有case执行结束之后再清理环境,我们可以用setUpClass()与tearDownClass(),代码格式如下:

     

    [python] view plain copy
     
    1. class TestMathFunc(unittest.TestCase):  
    2.     @classmethod  
    3.     def setUpClass(cls):  
    4.         print "setUp"  
    5.   
    6.     @classmethod  
    7.     def tearDownClass(cls):  
    8.         print "tearDown"  


    七、跳过某个case

    unittest提供了几种方法可以跳过case

    (1)skip装饰器

     

    代码如下

     

    [python] view plain copy
     
    1. # coding=utf-8  
    2. import unittest  
    3. from mathfunc import *  
    4.    
    5. class TestMathFunc(unittest.TestCase):  
    6.    
    7.      .....  
    8.   
    9.     @unittest.skip("i don't want to run this case.")  
    10.     def test_minus(self):  
    11.         self.assertEqual(1, minus(3, 2))  


    输出:

     

    [python] view plain copy
     
    1. test_add (test_mathfunc.TestMathFunc) ... ok  
    2. test_minus (test_mathfunc.TestMathFunc) ... skipped "i don't want to run this case."  
    3. test_divide (test_mathfunc.TestMathFunc) ... FAIL  
    4.    
    5. ======================================================================  
    6. FAIL: test_divide (test_mathfunc.TestMathFunc)  
    7. ----------------------------------------------------------------------  
    8. Traceback (most recent call last):  
    9.   File "D:pythonWorkspaceHTMLTest est_mathfunc.py", line 28, in test_divide  
    10.     self.assertEqual(2.5, divide(5, 2))  
    11. AssertionError: 2.5 != 2  
    12.    
    13. ----------------------------------------------------------------------  
    14. Ran 3 tests in 0.000s  
    15.    
    16. FAILED (failures=1, skipped=1)  

    skip装饰器一共有三个

    unittest,skip(reason):无条件跳过

    unittest.skipIf(condition, reason):当condition为True时跳过

    unittest.skipUnless(condition, reason):当condition为False时跳过

     

    (2)TestCase.skipTest()方法

     

    [python] view plain copy
     
    1. class TestMathFunc(unittest.TestCase):  
    2. ...  
    3. def test_minus(self):  
    4.         self.skipTest('do not run this.')  
    5.         self.assertEqual(1, minus(3, 2))  

     

    输出:

     

    [python] view plain copy
     
    1. test_add (test_mathfunc.TestMathFunc) ... ok  
    2. test_minus (test_mathfunc.TestMathFunc) ... skipped 'do not run this.'  
    3. test_divide (test_mathfunc.TestMathFunc) ... FAIL  
    4.    
    5. ======================================================================  
    6. FAIL: test_divide (test_mathfunc.TestMathFunc)  
    7. ----------------------------------------------------------------------  
    8. Traceback (most recent call last):  
    9.   File "D:pythonWorkspaceHTMLTest est_mathfunc.py", line 20, in test_divide  
    10.     self.assertEqual(2.5, divide(5, 2))  
    11. AssertionError: 2.5 != 2  
    12.    
    13. ----------------------------------------------------------------------  
    14. Ran 3 tests in 0.000s  
    15.    
    16. FAILED (failures=1, skipped=1)  


    八、用HTMLTestRunner输出漂亮的HTML报告

    txt格式的文本执行报告过于简陋,这里我们学习一下借助HTMLTestRunner生成HTML报告。首先需要下载HTMLTestRunner.py,并放到当前目录下,或者python目录下的Lib中,就可以导入运行了。

    下载地址:http://tungwaiyip.info/software/HTMLTestRunner.html

     

    将test_suite.py代码修改如下:

     

    [python] view plain copy
     
    1. # coding=utf-8  
    2.    
    3. import unittest  
    4. from test_mathfunc import TestMathFunc  
    5. from HTMLTestRunner import HTMLTestRunner  
    6.    
    7.    
    8. if __name__ == '__main__':  
    9.     suite = unittest.TestSuite()  
    10.    
    11.     tests = [TestMathFunc("test_add"), TestMathFunc("test_minus"), TestMathFunc("test_divide")]  
    12.     suite.addTests(tests)  
    13.    
    14.     with open('HTMLReport.html', 'w') as f:  
    15.         runner = HTMLTestRunner(stream=f,  
    16.                                 title = 'MathFunc Test Report',  
    17.                                 description='generated by HTMLTestRunner.',  
    18.                                 verbosity=2  
    19.                                 )  
    20.         runner.run(suite)  


    执行后,控制台输出如下:

     

    [python] view plain copy
     
    1. ok test_add (test_mathfunc.TestMathFunc)  
    2. F  test_divide (test_mathfunc.TestMathFunc)  
    3.    
    4. Time Elapsed: 0:00:00.001000  

    生成的html:

     

     

    九、总结

    1、unittest是python自带的单元测试框架,我们可以用其来作为我们自动化测试框架的用例组织执行框架。

    2、unittest的流程:写好TestCase,然后由TestLoader加载TestCase到TestSuite,然后由TextTestRunner来运行TestSuite,运行的结果保存在TextTestResult中,我们通过命令行或者unittest.main()执行时,main会调用TextTestRunner中的run来执行,或者我们可以直接通过TextTestRunner来执行用例。

    3、一个class继承unittest.TestCase即是一个TestCase,其中以 test 开头的方法在load时被加载为一个真正的TestCase。

    4、verbosity参数可以控制执行结果的输出,0 是简单报告、1 是一般报告、2 是详细报告。

    5、可以通过addTest和addTests向suite中添加case或suite,可以用TestLoader的loadTestsFrom__()方法。

    6、用 setUp()、tearDown()、setUpClass()以及 tearDownClass()可以在用例执行前布置环境,以及在用例执行后清理环境

    7、我们可以通过skip,skipIf,skipUnless装饰器跳过某个case,或者用TestCase.skipTest方法。

    8、参数中加stream,可以将报告输出到文件:可以用TextTestRunner输出txt报告,以及可以用HTMLTestRunner输出html报告。

     

  • 相关阅读:
    程序员的四个阶段
    2010Year Plans
    HttpHandler HttpModule入门篇
    Lucene.net索引文件的并发访问和线程安全性
    stream流写到MemoryStream内存流引发得问题
    ASP.NET 2.0 多文件上传小经验
    HTML 迷魂灯
    如何在Windows下搭建Android开发环境
    利用Lucene.net搭建站内搜索(4)数据检索
    数据加密和解密
  • 原文地址:https://www.cnblogs.com/xc1234/p/9154645.html
Copyright © 2011-2022 走看看