Python 3.x 使用";调用类级变量@pytest.mark.parametrize“;固定装置

Python 3.x 使用";调用类级变量@pytest.mark.parametrize“;固定装置,python-3.x,pytest,Python 3.x,Pytest,我试图在测试类的另一个方法中生成的值列表上迭代pytest测试 问题是我得到了: “@pytest.mark.parametrize(“数字”,TestScratch.list\u测试) NameError:name'TestScratch'未定义“当我尝试运行时出错。我知道一个事实,当我将列表作为硬编码列表(即[0,3,54,90])传递时,它会工作。 下面是我的代码: class TestScratch(object): @classmethod def setup_cla

我试图在测试类的另一个方法中生成的值列表上迭代pytest测试

问题是我得到了: “@pytest.mark.parametrize(“数字”,TestScratch.list\u测试) NameError:name'TestScratch'未定义“当我尝试运行时出错。我知道一个事实,当我将列表作为硬编码列表(即[0,3,54,90])传递时,它会工作。 下面是我的代码:

class TestScratch(object):

    @classmethod
    def setup_class(cls):
        cls.list_testing = []

    @classmethod
    def setup_method(cls):
        pass


    def test_populate_list(self):
        for i in range(100):
            self.list_testing.append(i)

    @pytest.mark.parametrize("number",TestScratch.list_testing)
    def test_pytest_param(self, number):
        assert type(number) == int

    @classmethod
    def teardown_class(cls):
        '''
        pass
        '''
我也试过self..list\u测试 但我也犯了同样的错误

环境详细信息:

Python:3.6.8


Pytest:5.2.1

您不能在类定义中使用该类。在导入时读取decorator时,e。G加载类定义时,而不是在运行时,此时不知道该类。您必须在类之外定义列表:

import pytest

def populate_list():
    test_list = []
    for i in range(100):
        test_list.append(i)
    return test_list


list_testing = populate_list()


class TestScratch:
    def test_populate_list(self):
        # this will fail if list_testing could not be populated
        assert len(list_testing) > 50

    @pytest.mark.parametrize("number", list_testing)
    def test_pytest_param(self, number):
        # this will be skipped if list_testing could not be populated
        assert type(number) == int

在decorator中使用的任何参数在加载时都只读取一次,所以在运行时尝试初始化它是行不通的。例如,您可以找到一个解释,说明参数化是如何工作的,以及为什么不能在运行时添加参数。

Thank解决了这个问题。尽管我似乎面临的另一个问题是“test_pytest_param”测试方法没有迭代列表中的项:
code scratch.py::TestScratch::test_populate_list PASSED scratch.py::TestScratch::test_pytest_param[number0]已跳过
正确[我还注意到,如果我在它工作的类之外填充列表,问题是当我在其中一个测试方法中填充列表时,不幸的是,这是我必须做的,因为我需要对列表的源运行测试。啊,好的,现在我看到了。您仍然在运行时填充列表-正如我所写的,这将不起作用。它必须被填充在加载时被重新编译,所以您不能在方法或函数中执行此操作。好的,我对答案进行了一些编辑以使其更清晰。通常,测试不应该相互依赖,尽管我不知道您的具体设置。如果您不能相应地重构它,您只需在单个测试中迭代测试数据。如果您的测试数据仅在runti中已知我,你真的被卡住了,不知道你的实际代码,我不能说是否有可能改变它-对不起。