python 测试实现方法

yipeiwu_com5年前Python基础
 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])

相关文章

Python使用pyshp库读取shapefile信息的方法

通过pyshp库,可以读写Shapefile文件,查询相关信息,github地址为 https://github.com/GeospatialPython/pyshp import...

Python求离散序列导数的示例

Python求离散序列导数的示例

有一组4096长度的数据,需要找到一阶导数从正到负的点,和三阶导数从负到正的点,截取了一小段。 394.0 388.0 389.0 388.0 388.0 392.0 39...

python 字符串和整数的转换方法

数字转成字符串 方法一: 使用格式化字符串: tt=322 tem='%d' %tt tem即为tt转换成的字符串 常用的格式化字符串: %d 整数 %f%F 浮点数 %e%E...

python集合用法实例分析

本文实例讲述了python集合用法。分享给大家供大家参考。具体分析如下: # sets are unordered collections of unique hashable el...

python3利用ctypes传入一个字符串类型的列表方法

c语言里:c_p.c #include <stdio.h> void get_str_list(int n, char *b[2]) { printf("in c s...