用Python搭建自动化测试框架,我们需要组织用例以及测试执行,推荐Python的标准库——unittest。
unittest是xUnit系列框架中的一员,如果你了解xUnit的其他成员,那你用unittest来应该是很轻松的,它们的工作方式都差不多。
官方说明文档: https://docs.python.org/3/library/unittest.html
The unittest module is actually a testing framework that was originally inspired by JUnit. It currently supports test automation, the sharing of setup and shutdown code, aggregating tests into collections and the independence of tests from the reporting framework.
Unittest框架支持以下4个概念:
我们使用PYTHON的单元测试的主要方法是:
In [21]:
# 一个简单例子, 将该脚本保存为 mymath.py
# 建立一个自己的脚本,定义了 add substract multiply divide 四个数学功能,我们用单元测试来检查它们是否与预期的功能一致!
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(numerator, denominator):
return float(numerator) / denominator
In [ ]:
# 将以下脚本保存为 test_mymath.py,并运行
"""
构建unittest基本使用方法
1.import unittest 导入unittest库
2.定义一个继承自unittest.TestCase的测试用例类
3.定义setUp和tearDown,在每个测试用例前后做一些辅助工作
4.定义测试用例,函数名字以test开头
5.一个测试用例应该只测试一个方面,测试目的和测试内容应很明确。主要是调用assertEqual、assertRaises等断言方法判断程序执行结果和预期值是否相符。
6.调用unittest.main()启动测试
7.如果测试未通过,会输出相应的错误提示。如果测试全部通过则不显示任何东西,这时可以添加-v参数显示详细信息。
"""
import mymath
import unittest
class TestAdd(unittest.TestCase):
"""
Test the add function from the mymath library
"""
def test_add_integers(self):
"""
Test that the addition of two integers returns the correct total
"""
result = mymath.add(1, 2)
self.assertNotEqual(result, 555)
self.assertEqual(result, 3)
def test_add_floats(self):
"""
Test that the addition of two floats returns the correct result
"""
result = mymath.add(10.5, 2)
self.assertEqual(result, 12.5)
def test_add_strings(self):
"""
Test the addition of two strings returns the two string as one
concatenated string
"""
result = mymath.add('abc', 'def')
self.assertEqual(result, 'abcdef')
if __name__ == '__main__':
unittest.main()
In [ ]: