簡體   English   中英

雙參數化

[英]Double parameterization

所以我有一組測試,我想測試一個解決方案的多個版本。 目前我有

import pytest

import product_not_at_index


functions_to_test = [
    product_not_at_index.product_not_at_index_n_squared,
    product_not_at_index.product_not_at_index,
]

def run_test(function_input, expected_result, test_func):
    actual_result = test_func(function_input)
    assert actual_result == expected_result

@pytest.mark.parametrize("test_func", functions_to_test)
def test_empty_list(test_func):
    input_data = []
    expected_result = []
    run_test(input_data, expected_result, test_func)

@pytest.mark.parametrize("test_func", functions_to_test)
def test_single_item(test_func):
    input_data = [1]
    expected_result = [1]
    run_test(input_data, expected_result, test_func)

@pytest.mark.parametrize("test_func", functions_to_test)
def test_one_times_one(test_func):
    input_data = [1, 1]
    expected_result = [1, 1]
    run_test(input_data, expected_result, test_func)

@pytest.mark.parametrize("test_func", functions_to_test)
def test_normal_use_case(test_func):
    input_data = [1, 7, 3, 4]
    expected_result = [84, 12, 28, 21]
    run_test(input_data, expected_result, test_func)

這很好用。 但是查看我的解決方案,我發現我的所有測試都具有相同的基本代碼集。 我怎樣才能兩次參數化一個函數,這樣我就可以只有一個測試函數並停止重復自己?

我以為我可以做類似的事情

import pytest

import product_not_at_index


functions_to_test = [product_not_at_index.product_not_at_index_n_squared]
test_data = [
    [], [],
    [1], [1],
    [1, 1], [1, 1],
    [1, 7, 3, 4],  [84, 12, 28, 21],
]

@pytest.mark.parametrize("function_input,expected_result", test_data)
@pytest.mark.parametrize("test_func", functions_to_test)
def test_run(function_input, expected_result, test_func):
    actual_result = test_func(function_input)
    assert actual_result == expected_result

但這只會返回此錯誤

E   assert 0 == 2
E    +  where 0 = len([])
E    +  and   2 = len(['function_input', 'expected_result'])

我最終使用的解決方案是這個

import pytest

import product_not_at_index


functions_to_test = [product_not_at_index.product_not_at_index_n_squared]
test_data = [
    ([], []),
    ([1], [1]),
    ([1, 1], [1, 1]),
    ([1, 7, 3, 4],  [84, 12, 28, 21]),
]

# TODO: turn into a list comprehension.
test_paramaters = []
for func in functions_to_test:
    for test_input, expected_result in test_data:
        test_paramaters.append([test_input, expected_result, func])

@pytest.mark.parametrize("function_input,expected_result,test_func", test_paramaters)
def test_run(function_input, expected_result, test_func):
    actual_result = test_func(function_input)
    assert actual_result == expected_result

暫無
暫無

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

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