在Python的pytest框架中,实现测试数据驱动的方法主要有以下几种:
@pytest.mark.parametrize装饰器这是最常用的方法,通过@pytest.mark.parametrize装饰器,你可以为测试函数提供多组测试数据。
import pytest
# 定义测试数据
test_data = [
(1, 2, 3),
(4, 5, 9),
(7, 8, 15)
]
# 使用parametrize装饰器
@pytest.mark.parametrize("a, b, expected", test_data)
def test_addition(a, b, expected):
assert a + b == expected
pytest.fixture和参数化你也可以结合pytest.fixture来创建可重用的测试数据,并通过params参数进行参数化。
import pytest
# 定义fixture并参数化
@pytest.fixture(params=[(1, 2), (3, 4), (5, 6)])
def addend(request):
return request.param
def test_addition(addend):
a, b = addend
assert a + b == sum(addend)
你可以将测试数据存储在外部文件(如CSV、JSON、YAML等)中,然后在测试中使用这些数据。
data.csv
a,b,expected
1,2,3
4,5,9
7,8,15
test_addition.py
import csv
import pytest
def read_csv(file_path):
with open(file_path, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
yield int(row['a']), int(row['b']), int(row['expected'])
@pytest.mark.parametrize("a, b, expected", read_csv('data.csv'))
def test_addition(a, b, expected):
assert a + b == expected
data.json
[
{"a": 1, "b": 2, "expected": 3},
{"a": 4, "b": 5, "expected": 9},
{"a": 7, "b": 8, "expected": 15}
]
test_addition.py
import json
import pytest
def read_json(file_path):
with open(file_path) as f:
data = json.load(f)
for item in data:
yield item['a'], item['b'], item['expected']
@pytest.mark.parametrize("a, b, expected", read_json('data.json'))
def test_addition(a, b, expected):
assert a + b == expected
还有一些第三方库可以帮助你更方便地进行数据驱动测试,例如pytest-datadir、pytest-csv等。
pytest-datadir安装
pip install pytest-datadir
conftest.py
import pytest
def pytest_generate_tests(metafunc):
if 'data_dir' in metafunc.fixturenames:
metafunc.parametrize('data_dir', [pytest.fixture('datadir')])
test_addition.py
import pytest
@pytest.fixture
def datadir(tmpdir):
return tmpdir.mkdir("data")
def test_addition(datadir):
data_file = datadir.join("data.csv")
data_file.write("a,b,expected\n1,2,3\n4,5,9\n7,8,15\n")
with open(data_file) as f:
reader = csv.DictReader(f)
for row in reader:
a, b, expected = int(row['a']), int(row['b']), int(row['expected'])
assert a + b == expected
通过这些方法,你可以灵活地实现测试数据驱动,提高测试代码的可维护性和可读性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。