gpt4 book ai didi

python-3.x - 使用 "@pytest.mark.parametrize"fixture 调用类级变量

转载 作者:行者123 更新时间:2023-12-04 16:45:50 25 4
gpt4 key购买 nike

我正在尝试对我在测试类的另一个方法中生成的值列表进行 pytest 测试。

问题是我得到: "@pytest.mark.parametrize("number",TestScratch.list_testing)NameError: name 'TestScratch' is not defined" 当我尝试运行时出错。我知道当我将列表作为硬编码列表传递时,即 [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.class.list_testing但我得到了同样的错误

环境细节:

python :3.6.8

Pytest:5.2.1

最佳答案

您不能在类定义中使用该类。当在导入时读取装饰器时,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

你在装饰器中使用的任何参数在加载时只被读取一次,所以试图在运行时初始化它是行不通的。例如here您可以找到参数化工作原理的解释以及为什么无法在运行时添加参数。

关于python-3.x - 使用 "@pytest.mark.parametrize"fixture 调用类级变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61039186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com