【脚本语言系列】关于Python测试工具unittest, 你需要知道的事
2017-04-19 16:57
1066 查看
如何使用unittest
编写阶乘函数def factorial(n): if n == 0: return 1 if n < 0: raise ValueError, "Don't be so negative" return numpy.arange(1, n+1).cumprod()
2. 编写单元测试
* 正整数,所谓的愉快路径(happy path)
* 边界条件0
* 负整数,将引起错误
class FactorialTest(unittest.TestCase): def test_factorial(self): # 对3的阶乘进行测试,应该能通过 self.assertEqual(6, factorial(3)[-1]) numpy.testing.assert_equal(numpy.array([1, 2, 6]), factorial(3)) def test_zero(self): # 对0的阶乘进行测试,应该能通过 self.assertEqual(1, factorial(0)) def test_negative(self): # 对负整数的阶乘进行测试,应该不能通过 # 阶乘函数会抛出一个ValueError类型的异常,但我们期望得到一个IndexError类型的异常 self.assertRaises(IndexError, factorial(-10))
3. 运行测试
#-*- coding: utf-8 -*-
import numpy
import unittest
def factorial(n): if n == 0: return 1 if n < 0: raise ValueError, "Don't be so negative" return numpy.arange(1, n+1).cumprod()
class FactorialTest(unittest.TestCase): def test_factorial(self): # 对3的阶乘进行测试,应该能通过 self.assertEqual(6, factorial(3)[-1]) numpy.testing.assert_equal(numpy.array([1, 2, 6]), factorial(3)) def test_zero(self): # 对0的阶乘进行测试,应该能通过 self.assertEqual(1, factorial(0)) def test_negative(self): # 对负整数的阶乘进行测试,应该不能通过 # 阶乘函数会抛出一个ValueError类型的异常,但我们期望得到一个IndexError类型的异常 self.assertRaises(IndexError, factorial(-10))
if __name__ == '__main__':
unittest.main()
完整代码
测试结果
什么是unittest
测试驱动开发(TDD)是本世纪以来在软件开发领域出现的一项最重要的技术。TDD的一个非常引人注目的地方,是对单元测试的几近狂热的关注。单元测试用来对一小段代码(通常是一个函数或方法)进行自动化的测试。Python提供了用于单元测试的PyUnit API.
相关文章推荐
- 【脚本语言系列】关于Python测试工具docstrings, 你需要知道的事
- 【脚本语言系列】关于Python测试工具mock, 你需要知道的事
- 【脚本语言系列】关于Python测试工具lettuce, 你需要知道的事
- 【脚本语言系列】关于Python测试工具Pyflakes, 你需要知道的事
- 【脚本语言系列】关于Python测试工具Pylint, 你需要知道的事
- 【脚本语言系列】关于Python游戏工具Pygame,你需要知道的事
- 【脚本语言系列】关于Python性能分析工具timeit, 你需要知道的事
- 【脚本语言系列】关于Python测试,你需要知道的事
- 【脚本语言系列】关于Python代码分析工具line_profiler,你需要知道的事
- 【脚本语言系列】关于Python开发环境搭建,你需要知道的事
- 【脚本语言系列】关于Python数值计算Pandas,你需要知道的事
- 【脚本语言系列】关于Python数值计算NumPy, 你需要知道的事
- 【脚本语言系列】关于Python音频处理WMPlayerOCX,你需要知道的事情
- 【脚本语言系列】关于Python文本解析XML,你需要知道的事
- 【脚本语言系列】关于Python数据库处理MySQL, 你需要知道的事
- 【脚本语言系列】关于Python邮件服务poplib,你需要知道的事
- 【脚本语言系列】关于Python网页服务Apache,你需要知道的事
- 【脚本语言系列】关于PythonGUI界面PyQT,你需要知道的事
- 【脚本语言系列】关于PythonWeb访问urllib,你需要知道的事
- 【脚本语言系列】关于Python图像处理scikits-image, 需要知道的事