学习笔记五:数据参数化
parameterized
安装插件:pip install parameterized
使用方式:https://github.com/wolever/parameterized
```py
import unittest
from parameterized import parameterized
class AddTestCase(unittest.TestCase):
@parameterized.expand([
("2 and 3", 2, 3, 5),
("3 and 5", 2, 3, 5),
])
def test_add(self, _, a, b, expected):
print(_, a, b, expected)
```
ddt
安装插件:pip install ddt
使用方式:https://github.com/datadriventests/ddt/
```py
import unittest
from ddt import ddt, data, file_data, unpack
@ddt
class FooTestCase(unittest.TestCase):
@data(3, 4, 12, 23)
def test_larger_than_two(self, value):
print(value)
@data([3, 2], [4, 3], [5, 3])
@unpack
def test_list_extracted_with_doc(self, first_value, second_value):
print(first_value, second_value)
@unpack
@data({'first': 1, 'second': 3, 'third': 2},
{'first': 4, 'second': 6, 'third': 5})
def test_dicts_extracted_into_kwargs(self, first, second, third):
print(first, third, second)
@file_data('test_data_dict.json')
def test_file_data_json_dict(self, value):
print(value)
@file_data('test_data_dict.yaml')
def test_file_data_yaml_dict(self, value):
print(value)
FooTestCase()
```
自己封装ddt,读取csv文件
```py
import csv
from itertools import islice
from parameterized import parameterized
def file_ddt(f):
file_data = csv.reader(open(f, 'r'))
data = []
for d in islice(file_data, 1, None):
data.append(d)
return parameterized.expand(data)
```

浙公网安备 33010602011771号