PythonTip >> 博文 >> chinaunix

python单元测试初探

zihua 2014-01-13 18:01:34 点击: 666 | 收藏


今天下午看完BeautifulSoup的相关内容,顺便看到了select/pol的内容,感觉压力比较大,因此换了一个简单点的topic,单元测试。
单元测试的功能与重要性我们就不说了,这里仅对python中的单元测试进行假单的实现
1 入门级别的dcotest
The doctest
module searches for pieces of text that look like interactive Python sessions
即该模块仅是珍针对模块中的Docstring中的类似交互式的TEXt进行测试,一发现问题之所在,
主要的功能有:

点击(此处)折叠或打开

  1. To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented.
  2. To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.
  3. To write tutorial documentation for a package, liberally illustrated with input-output examples. Depending on whether the examples or the expository text are emphasized, this has the flavor of “literate testing” or “executable documentation”.
具体的用如下:

点击(此处)折叠或打开

  1. # this is another module
  2. def product(x,y):
  3.     '''
  4.     >>> product(5,9)
  5.      45
  6.     >>> product(0.5,2)
  7.     1.1
  8.     '''
  9.     45
  10.     return x*y
  11. print __name__
  12. if __name__ == '__main__':
  13.     import doctest
  14.     doctest.testmod()
程序的结果如下


C:\Python27>python kk.py -v
__main__
Trying:
    product(5,9)
Expecting:
    45
ok
Trying:
    product(0.5,2)
Expecting:
    1.1
**********************************************************************
File "kk.py", line 6, in __main__.product
Failed example:
    product(0.5,2)
Expected:
    1.1
Got:
    1.0
1 items had no tests:
    __main__
**********************************************************************
1 items had failures:
   1 of   2 in __main__.product
2 tests in 2 items.
1 passed and 1 failed.
***Test Failed*** 1 failures.

需要注意的地方有:
1 该函数仅是针对交互式的语法进行test
2 在进行记过比较的时候,它以你交互式的结果为准,正如0.5*2 =1 ,但是docstring的结果为1.1,因此判断test failture
3 注意一个模块直接运行是,其__name__=__main__
貌似上面的测试有点小儿科了,现在来点猛料----单元测试
单元测试要比DOCtest复杂点,编写的代码多点而已,但是检测方面也更加的详细:

点击(此处)折叠或打开

  1. import kk
  2. import unittest
  3. class ProductTestCase(unittest.TestCase):
  4.     def setUp(self):
  5.         print 'units test begin'+'#'*20
  6.     def tearDown(self):
  7.         print 'unittest end'+'#'*20
  8.     def testxx(self):
  9.         print 'this is just test'
  10.     def testIntegerProduct(self):
  11.         for x in xrange(-10,10):
  12.             for y in xrange(-10,10):
  13.                 p = kk.product(x,y)
  14.                 self.failUnless(p == x*y,'integer multiplication failture')
  15.     def testFractalProduct(self):
  16.         for x in xrange(-10,10):
  17.             for y in xrange(-10,10):
  18.                 x = x/10.0
  19.                 y = y/10.0
  20.                 p = kk.product(x,y)
  21.                 self.failUnless(p == x*y,'fractal multiplication failture')

  22. if __name__ == '__main__':
  23.     unittest.main()
结果输出:


点击(此处)折叠或打开

  1. C:\Python27>python abctest.py -v
  2. kk
  3. testFractalProduct (__main__.ProductTestCase) ... units test begin##############
  4. ######
  5. unittest end####################
  6. ok
  7. testIntegerProduct (__main__.ProductTestCase) ... units test begin##############
  8. ######
  9. unittest end####################
  10. ok
  11. testxx (__main__.ProductTestCase) ... units test begin####################
  12. this is just test
  13. unittest end####################
  14. ok

  15. ----------------------------------------------------------------------
  16. Ran 3 tests in 0.016s

  17. OK
需要注意到地方有:
1 KK为我们导入的模块名称,这也就解释了一个模块如果直接运行,其模块名为__name__==__main__,如果被其他模块导入,则__name__==模块名
这里多说一点,为什么要使用这么奇怪的名字,本来使用的名字为abc,使用WINGIDE,也提示正常,但是在
运行的时候老是包错:
AttributeError: 'module' object has no attribute 'product'
检查了一下,难道是模块路径不对?


import sys
for path in sys.path:
  print path


C:\Python27\lib\site-packages\pip-1.2.1-py2.7.egg
C:\Python27\lib\site-packages\distribute-0.6.27-py2.7.egg
C:\Windows\system32\python27.zip
C:\Python27\DLLs
C:\Python27\lib
C:\Python27\lib\plat-win
C:\Python27\lib\lib-tk
C:\Python27
C:\Python27\lib\site-packages
C:\Python27\lib\site-packages\setuptools-0.6c11-py2.7.egg-info

发现,即使将模块移入C:\Python27,仍是包同样的错误,直接运行abc.py ,结果又是正确的,
因此在abc.py 加入调试信息,print ’this is abc'

发现在导入该模块的时候,该该信息根本就没有输出,因此判断是该模块出了问题,想来想去,如此简单的语法,难道是模块重名的问题?
百度一把发现http://docs.python.org/2/py-modindex.html

abc Abstract base classes according to PEP 3119.
,因此白白的浪费了好些时间,真是郁闷,这才是无妄之灾啊,因此悄悄的告诫自己要养成良好的习惯
第二点就是,需要关注即时如何编写unittest
其实也很简单,就是继承与unittest.TestCase,然后针对需要测试的方法以TEST开始命名函数

test case
A test case is the smallest unit of testing. It checks
for a specific response to a particular set of inputs. unittest provides a base class, TestCase, which may be used to create new test cases.
setUp()

Method called to prepare the test fixture. This is called immediately before
calling the test method; any exception raised by this method will be considered
an error rather than a test failure. The default implementation does
nothing.

tearDown()
Method called immediately after the test method has been called and the
result recorded. This is called even if the test method raised an exception, so
the implementation in subclasses may need to be particularly careful about
checking internal state. Any exception raised by this method will be considered
an error rather than a test failure. This method will only be called if the setUp()
succeeds, regardless of the outcome of the test method. The default
implementation does nothing.
需要注意的是,setup,teardown方法是珍针对需要测试的每一个函数,从输出我们也可以看出。
ref:
python manual
原文链接:http://blog.chinaunix.net/uid-23062171-id-3888889.html

作者:zihua | 分类: chinaunix | 标签: python | 阅读: 666 | 发布于: 2014-01-13 18时 |
上一篇:python常用模块资料
下一篇: python点滴