Home  >  Article  >  Backend Development  >  python 测试实现方法

python 测试实现方法

WBOY
WBOYOriginal
2016-06-06 11:27:041122browse
 1)doctest
使用doctest是一种类似于命令行尝试的方式,用法很简单,如下

代码如下:


def f(n):
"""
>>> f(1)
1
>>> f(2)
2
"""
print(n)

if __name__ == '__main__':
import doctest
doctest.testmod()


应该来说是足够简单了,另外还有一种方式doctest.testfile(filename),就是把命令行的方式放在文件里进行测试。

2)unittest
unittest历史悠久,最早可以追溯到上世纪七八十年代了,C++,Java里也都有类似的实现,Python里的实现很简单。
unittest在python里主要的实现方式是TestCase,TestSuite。用法还是例子起步。

代码如下:


from widget import Widget
import unittest
# 执行测试的类
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget()
def tearDown(self):
self.widget.dispose()
self.widget = None
def testSize(self):
self.assertEqual(self.widget.getSize(), (40, 40))
def testResize(self):
self.widget.resize(100, 100)
self.assertEqual(self.widget.getSize(), (100, 100))
# 测试
if __name__ == "__main__":
# 构造测试集
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase("testSize"))
suite.addTest(WidgetTestCase("testResize"))

# 执行测试
runner = unittest.TextTestRunner()
runner.run(suite)


简单的说,1>构造TestCase(测试用例),其中的setup和teardown负责预处理和善后工作。2>构造测试集,添加用例3>执行测试需要说明的是测试方法,在Python中有N多测试函数,主要的有:
TestCase.assert_(expr[, msg])
TestCase.failUnless(expr[, msg])
TestCase.assertTrue(expr[, msg])
TestCase.assertEqual(first, second[, msg])
TestCase.failUnlessEqual(first, second[, msg])
TestCase.assertNotEqual(first, second[, msg])
TestCase.failIfEqual(first, second[, msg])
TestCase.assertAlmostEqual(first, second[, places[, msg]])
TestCase.failUnlessAlmostEqual(first, second[, places[, msg]])
TestCase.assertNotAlmostEqual(first, second[, places[, msg]])
TestCase.failIfAlmostEqual(first, second[, places[, msg]])
TestCase.assertRaises(exception, callable, ...)
TestCase.failUnlessRaises(exception, callable, ...)
TestCase.failIf(expr[, msg])
TestCase.assertFalse(expr[, msg])
TestCase.fail([msg])
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn