双参数化

时间:2016-05-31 18:00:24

标签: python unit-testing pytest

所以我有一组测试,我想测试多个版本的解决方案。目前我有

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'])

1 个答案:

答案 0 :(得分:2)

我最终使用的解决方案就是这个

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