我写了一个名为Parametrize From File的库,它可以像这样从数据文件中加载测试参数。但我不确定我是否完全理解你的例子。如果这是您的数据文件...
用户 |
密码 |
项目编号 |
项目名 |
一个 |
乙 |
C |
D |
乙 |
F |
G |
H |
...这些是您要运行的测试吗?
@pytest.mark.parametrize(
'user, password',
[('A', 'B'), ('E', 'F')],
)
def test_1(user, password):
assert ...
@pytest.mark.parametrize(
'iterm_number, item_name',
[('C', 'D'), ('G', 'H')],
)
def test_2(user, password):
assert ...
换句话说, / 列是否与/user
列password
完全无关?如果不是,我误解了你的问题。如果是,那么这不是非常可扩展的。很容易想象编写 100 个测试,每个测试有 2 个以上的参数,总共超过 200 列!这种格式也打破了行中的每个值都应该以某种方式相关的惯例。我建议将每个测试的参数放入他们自己的文件/工作表中,或者使用更匹配 pytest 预期的元组列表/字典列表结构的文件格式,例如 YAML、TOML、NestedText,等等item_number
item_name
综上所述,以下是使用 Parametrize From File 从 xlsx 文件加载参数的方法:
import pandas as pd
from collections import defaultdict
import parametrize_from_file as pff
def load_xlsx(path):
"""
Load an xlsx file and return the data structure expected by Parametrize
From File, which is a map of test names to test parameters. In this case,
the xlsx file doesn't specify any test names, so we use a `defaultdict` to
make all the parameters available to any test.
"""
df = pd.read_excel(path)
return defaultdict(lambda: df)
def get_cols(cols):
"""
Extract specific columns from the parameters loaded from the xlsx file.
The parameters are loaded as a pandas DataFrame, and need to be converted
into a list of dicts in order to be understood by Parametrize From File.
"""
def _get_cols(df):
return df[cols].to_dict('records')
return _get_cols
# Use the function we defined above to load xlsx files.
pff.add_loader('.xlsx', load_xlsx)
@pff.parametrize(preprocess=get_cols(['user', 'password']))
def test_1(user, password):
pass
@pff.parametrize(preprocess=get_cols(['item_number', 'item_name']))
def test_2(item_number, item_name):
pass
请注意,如果以我上面推荐的格式之一组织参数,则此代码会简单得多。