6.0 ddt框架

1. ddt框架介绍

数据驱动的单元测试是为数据源中的每一行重复运行的一种单元测试。

2. ddt使用

import unittest
from ddt import ddt, data, unpack

test_data = [{'a': 1, 'b': 2},
             {'a': 3, 'b': 4},
             {'a': 5, 'b': 6},
             {'a': 7, 'b': 8},
             {'a': 9, 'b': 10},]


@ddt  # ddt:装饰测试类
class Testmul(unittest.TestCase):
    @data(*test_data)                 # 装饰测试数据
    def test_mul(self, item):
        x = item['a']
        y = item['b']
        print('两个数的乘积是{}'.format(x*y))


if __name__ == '__main__':
    unittest.main()


>两个数的乘积是2
 两个数的乘积是12
 两个数的乘积是30
 两个数的乘积是56
 两个数的乘积是90
import unittest
from ddt import ddt, data, unpack

test_data = [[1, 2],
             [3, 4],
             [5, 6],
             [7, 8]]

@ddt  # ddt:装饰测试类
class Testmul(unittest.TestCase):
    @data(*test_data)                 # 装饰测试用例
    @unpack
    def test_mul(self, a, b):
        print('两个数的乘积是{0}'.format(a * b))


if __name__ == '__main__':
    unittest.main()
>两个数的乘积是2
 两个数的乘积是12
 两个数的乘积是30
 两个数的乘积是56

3. 出现的问题

1. 报告出现:dict() -> new empty dictionary
解决办法:(https://www.cnblogs.com/yhleng/p/9805125.html)

4. 代码

# test_case.py
import unittest
from ddt import ddt,data,unpack
from zy.code import Sub
from zy.do_excel import DoExcel
from zy.conf import ReadConfig


button = ReadConfig().read_config('case.conf', 'SECTION', 'button')
case_no = eval(ReadConfig().read_config('case.conf', 'SECTION', 'case_id'))  # 配置文件读取的数据默认为字符串

test_data = DoExcel().read_data(button, case_no)


@ddt  # ddt:装饰测试类
class TestSub(unittest.TestCase):
    def setUp(self):
        self.t = Sub()
        self.wb = DoExcel()


    @data(*test_data)
    def test_sub(self, item):
        print('用例标题:{}'.format(item['title']))
        res = self.t.sub(item['param_a'], item['param_b'])
        try:
            self.assertEqual(res, item['ExpectedResult'])
            test_result = 'PASS'
        except AssertionError as e:
            test_result = 'FAIL'
            raise e
        finally:
            self.wb.write_back(item['case_id']+1, res, test_result)

    def tearDown(self):
        print('测试完成了')
# excute_case.py
import unittest
from zy import test_case
import HTMLTestRunnerNew


suite = unittest.TestSuite()
loader = unittest.TestLoader()
suite.addTest(loader.loadTestsFromModule(test_case))  # 加载模块的所有用例

with open('TestResult.html', 'wb+') as file:
    runner = HTMLTestRunnerNew.HTMLTestRunner(file, title='减法测试', description='第二轮整体回归测试减法方法的正确性', tester='华杰-zy')
    runner.run(suite)

发布了114 篇原创文章 · 获赞 7 · 访问量 5381

猜你喜欢

转载自blog.csdn.net/qq_25672165/article/details/89893755
ddt