簡體   English   中英

數據驅動 - 如何在 Python 中使用選擇性 args/params 作為參數化的一部分?

[英]Data Driven - How can I use selective args/params as part of parameterize in Python?

我正在尋找為我的 python selenium 項目設置數據驅動的方法(目前沒有)。 計划將數據文件設為 xlsx

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

我能夠讀取我的 excel 值,並通過 @data-unpack 或參數化傳遞它。 但是,就我而言,我的每個測試都將使用我的數據文件中選定的列 - 不是全部。

例如)我的數據列表將是這樣的(用戶,密碼,item_number,item_name)[('user1', 'abc', 1, 'it1234')('user2', 'def',2, 'it5678')]

我的函數 1(測試 1)只需要參數化用戶和密碼列。 我的函數 2(測試 2)只需要參數化 item_number 和 item_name 列。

我可以使用什么庫或方法來滿足我的需要? 基本上我需要能夠從我的數據文件中為我的測試參數化特定的列

感謝您對此提出建議。

我編寫了一個名為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列是否與item_number / item_name列完全無關? 如果不是,我誤解了你的問題。 如果是,這不是很可擴展。 很容易想象編寫 100 個測試,每個測試有 2 個以上的參數,總共超過 200 列! 這種格式也打破了行中的每個值都應該以某種方式相關的約定。 我建議將每個測試的參數放入他們自己的文件/工作表中,或者使用更符合 pytest 預期的元組列表/字典列表結構的文件格式,例如 YAML、TOML、NestedText,等等。

綜上所述,以下是您如何使用 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

請注意,如果參數以我上面推薦的格式之一組織,則此代碼會簡單得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM