python 测试实现方法

yipeiwu_com6年前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的建议和周期预算

如果是报名培训班的话,学习的速度可能会更快一些,毕竟是自己花钱了。 自学python爬虫方法: 首先要掌握一些有关爬虫的基础知识,基本的要知道什么是爬虫?为什么要爬虫?数据是从哪里得来的...

Python提取转移文件夹内所有.jpg文件并查看每一帧的方法

python里面可以将路径里面的\替换成/避免转义。 os.walk方法可以将目标路径下文件的root,dirs,files提取出来。后面对每个文件进行操作。 切片操作[:]判断是否为....

TensorFlow模型保存和提取的方法

TensorFlow模型保存和提取的方法

一、TensorFlow模型保存和提取方法 1. TensorFlow通过tf.train.Saver类实现神经网络模型的保存和提取。tf.train.Saver对象saver的save...

Pytorch提取模型特征向量保存至csv的例子

Pytorch提取模型特征向量 # -*- coding: utf-8 -*- """ dj """ import torch import torch.nn as nn impor...

Python+OpenCV人脸检测原理及示例详解

Python+OpenCV人脸检测原理及示例详解

关于opencv OpenCV 是 Intel 开源计算机视觉库 (Computer Version) 。它由一系列 C 函数和少量 C++ 类构成,实现了图像处理和计算机视觉方面的很...