当前位置: 首页 > 图文教程 > 脚本技术 > Python > python 测试实现方法

Python
wxPython 入门教程
Python日期操作学习笔记
Python函数学习笔记
Python转码问题的解决方法
python sqlobject(mysql)中文乱码解决方法
Python 连连看连接算法
Python类的基础入门知识
Python GAE、Django导出Excel的方法
python 参数列表中的self 显式不等于冗余
下载糗事百科的内容_python版
pymssql ntext字段调用问题解决方法
Python 面向对象 成员的访问约束
python 测试实现方法
python 数据加密代码
python zip文件 压缩
python 文件与目录操作
python3.0 字典key排序
Python 学习笔记
Python Mysql数据库操作 Perl操作Mysql数据库
Python MD5文件生成码

Python 中的 python 测试实现方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-11   浏览: 115 ::
收藏到网摘: n/a

使用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])