1.使用doctest模块测试代码

[root@node1 tmp]# vim qwe.py

#!/bin/env python
#!-*- coding:UTF-8 -*-

def abc():
    print 4;

[root@node1 tmp]# vim doctest.py
#!/bin/env python
#!-*- coding:UTF-8 -*-
import doctest,qwe             #加载doctest模块,加载qwe文件名
if __name__=="__main__":
    doctest.testmod(qwe)

[root@node1 tmp]# python doctest.py           #检查python语法
[root@node1 tmp]# python doctest.py -v       #查看代码的执行过程
2 items had no tests:
    qwe
    qwe.abc
0 tests in 2 items.
0 passed and 0 failed.
Test passed.
[root@node1 tmp]#


2.使用unittest模块测试代码

    unittest.main()函数负责实际运行测试.它会实例化所有TestCase的子类,运行所有名字以test方法的方法.

[root@node1 tmp]# vim unittest.py

#!/bin/env python
#!-*- coding:UTF-8 -*-
import unittest

class tong(unittest.TestCase):        #继承unittest模块

    def testa(self):             #函数名必须test开头
        print 'a'

    def testb(self):           #函数名必须test开头

        print 'b'

if __name__=="__main__":
    unittest.main()          #检查所有以TestCase类,test开头的函数是否有异常
[root@node1 tmp]# python doctest1.py
a
.b
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
[root@node1 tmp]#