1

我正在为我的 python selenium 项目设置一个数据驱动的方法(目前没有)。计划将数据文件作为 xlsx。

我在我的项目中使用 pytest。因此,我探索了 ddt、@data、@unpack 和 pytest.mark.parametrize。

我可以通过@data-unpack 或参数化来读取我的 excel 值。但是,就我而言,我的每个测试都将使用我的数据文件中的选定列 - 不是全部。

eg) 我的数据列表是这样的 (user, password, item_number, item_name)[('user1', 'abc', 1, 'it1234')('user2', 'def',2, 'it5678')]

我的函数 1(测试 1)只需要参数化用户和密码列。我的函数 2(测试 2)只需要参数化 item_number 和 item_name 列。

我可以使用什么库或方法来满足我的需要?基本上,我需要能够为我的测试参数化我的数据文件中的特定列。

4

1 回答 1

0

我写了一个名为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 ...

换句话说, / 列是否与/userpassword完全无关?如果不是,我误解了你的问题。如果是,那么这不是非常可扩展的。很容易想象编写 100 个测试,每个测试有 2 个以上的参数,总共超过 200 列!这种格式也打破了行中的每个值都应该以某种方式相关的惯例。我建议将每个测试的参数放入他们自己的文件/工作表中,或者使用更匹配 pytest 预期的元组列表/字典列表结构的文件格式,例如 YAML、TOML、NestedText,等等item_numberitem_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

请注意,如果以我上面推荐的格式之一组织参数,则此代码会简单得多。

于 2021-11-03T23:28:47.417 回答