python ddt实现数据驱动一

ddt是第三方模块,需安装,pip install ddt,ddt包含类的装饰器ddt和两个方法装饰器data(直接输入测试数据),通常情况下,data中的数据按照一个参数传递给测试用例,如果data中含有多个数据,如元组,列表,字典等数据,需要自行在脚本中对数据进行分解或者使用unpack分解数据

import unittest
from ddt import data, unpack, ddt


@ddt
class MyTesting(unittest.TestCase):
def setUp(self):
print('this is setUp')

# @data(a,b),那么a和b各运行一次用例,下面的代码会打印出this is setUp,1,this is setUp,2,this is setUp,3
@data(1, 2, 3)
def test_1(self, value):
print(value)

# 如果没有@unpack,那么[a,b]当成一个参数传入用例运行,如果有@unpack,那么[a,b]被分解开,按照用例中的两个参数传递
@data([3, 2, 1], [5, 3, 2], [10, 4, 6])
@unpack
def test_minus(self, a, b, expected):
actual = int(a) - int(b)
expected = int(expected)
self.assertEqual(actual, expected)

# test_compare的测试结果是fail的,由于没有加@unpack, 虽然还是会被理解成2组测试数据,
# 但是[2,3]作为一个整体被传给了a, 因为b就没有值传入了,
# 所以一执行后报了TypeError: test_compare() missing 1 required positional argument: 'b'
@data([2, 3], [4, 5])
def test_compare(self, a, b):
self.assertEqual(a, b)

def tearDown(self):
print('this is tearDown')


# 这里的verbosity是一个选项,表示测试结果的信息复杂度,有三个值
# 0 (静默模式) 1 (默认模式) 2 (详细模式):测试结果会显示每个测试用例的所有相关的信息
if __name__ == '__main__':
unittest.main(verbosity=2)

@ddt
class MyTest(unittest.TestCase):
# @data()里的数据组可以为元组,list,字典
@data((8, 6), (4, 0), (15, 6))
@unpack
def test_tuples(self, first, second):
self.assertTrue(first > second)

@data([30, 29], [40, 30], [5, 3])
@unpack
def test_list(self, first, second):
self.assertTrue(first > second)

@data({'first': 1, 'second': 3, 'third': 5},
{'first': 4, 'second': 7, 'third': 8})
@unpack
def test_dicts(self, first, second, third):
self.assertTrue(first < second < third)


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

import unittest, csv
from ddt import ddt, data, unpack

def get_csv(filename):
rows = []
with open(filename, encoding='utf8') as f:
readers = csv.reader(f)
for row in readers:
rows.append(row)
return rows


@ddt
class MyTest(unittest.TestCase):
# *get_csv('new.csv')是一个二维list,通过unpack分解成多个一维list
@data(*get_csv('new.csv'))
@unpack
def test_data_csv(self, v1, v2, v3):
print(v1)
print(v2)
print(v3)


if __name__ == '__main__':
unittest.main(verbosity=2)
posted @ 2019-12-10 17:32  laosun0204  阅读(395)  评论(0编辑  收藏  举报