背景
为了更好地管理自动化测试用例,同时对用例输入进行参数化,并且生成好看的测试报告,对题目中的几个框架进行了组合使用。
思路
- parameterized 参数化让单元测试更好管理用例输入变量
- unittest便于管理测试用例
- HTMLReport生成便于查看的HTML测试报告
- nose让用例更好编写,更好执行
代码
# test_math.py
# best suitable for nose framework: nosetests -v test_math.py
from nose.tools import assert_equal
from parameterized import parameterized, parameterized_class
import unittest
import math
import HTMLReport
@parameterized([
(2, 2, 4),
(2, 3, 8),
(1, 9, 1),
(0, 9, 0),
])
def test_pow(base, exponent, expected):
assert_equal(math.pow(base, exponent), expected)
class TestMathUnitTest(unittest.TestCase):
@parameterized.expand([
("negative", -1.5, -2.0),
("integer", 1, 1.0),
("large fraction", 1.6, 1),
])
def test_floor(self, name, input, expected):
assert_equal(math.floor(input), expected)
@parameterized_class(('a', 'b', 'expected_sum', 'expected_product'), [
(1, 2, 3, 2),
(5, 5, 10, 25),
])
class TestMathClass(unittest.TestCase):
def test_add(self):
assert_equal(self.a + self.b, self.expected_sum)
def test_multiply(self):
assert_equal(self.a * self.b, self.expected_product)
@parameterized_class([
{"a": 3, "expected": 2},
{"b": 5, "expected": -4},
])
class TestMathClassDict(unittest.TestCase):
a = 1
b = 1
def test_subtract(self):
assert_equal(self.a - self.b, self.expected)
if __name__ == '__main__':
cases = unittest.defaultTestLoader.discover('./', pattern='test_math.py')
runner = HTMLReport.TestRunner(report_file_name='test',
output_path='../report',
description='no descriptions',
thread_count=1,
thread_start_wait=3,
sequential_execution=False,
lang='en'
)
runner.run(cases)
运行
方法一
python test_math.py
运行结果
方法二
nosetests -v test_math.py
运行结果
参考
- parameterized模块:https://pypi.org/project/parameterized/
- unittest模块:https://docs.python.org/3/library/unittest.html
- HTMLReport模块:https://pypi.org/project/HTMLReport/