如何使用Pytest将数据列表传递给测试函数?除了此输入参数外,每个测试用例都非常相似。我尝试过以下但无济于事:
import pytest
@pytest.fixture
def List_of_Numbers():
list = [1,2,3,4,5,6,7,8]
@pytest.parametrize("number", [i for item in list])
def test_eval(number):
assert eval(number%2) == 0
pytest
输出:
==================================== ERRORS ====================================
_________________________ ERROR collecting sample4.py __________________________
sample4.py:8: in <module>
@pytest.parametrize("number", [i for item in list])
E AttributeError: module 'pytest' has no attribute 'parametrize'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.30 seconds ============================
答案 0 :(得分:0)
您的代码有问题:
@pytest.parametrize
,而应为@pytest.mark.parametrize
: @pytest.mark.parametrize("number", [i for item in list])
def test_eval(number):
assert eval(number%2) == 0
您试图到达在另一个函数的本地范围内定义的变量list
。最好不要根据常识和PEP-8使用Python中为内置变量和函数保留的变量和函数名。
您只需要数字列表而无需任何逻辑就不需要额外的固定装置。我建议您改用常量:
TEST_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8]
将它们放在一起:
import pytest
TEST_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8]
@pytest.parametrize("number", TEST_NUMBERS)
def test_eval(number):
assert eval(number % 2) == 0