如何使用setup\u类定义要在类的所有方法中访问的变量

2024-09-29 01:38:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在一个fixture方法setup\u类中为pytest-like定义一个变量

class testClassForPytest:
  @classmethod
  def setup_class(cls):
    m = aClassInstance(classInput)

  def test_case_1(self):
    #use of the instance m with a method of its class

我尝试了上述方法,但无法使用实例m


Tags: of方法test定义pytestdefsetupfixture
2条回答

pytest的测试套件(类)的设置似乎是从标准python库unittest继承的。有了这个库,这个方法被称为setUpClass,可能应该在其父类上调用相同的方法。但是,由于您使用的是pytest,它似乎没有遵循测试套件的思想,所以我不完全确定这是一个问题。尽管如此,如果该方法应该被调用其他东西,那么它可能是问题的一个根源。你知道吗

在方法setup_class的代码中,将变量m设置为一个值,但该变量仅限于方法的局部范围。只有以前在类的作用域上定义了变量,或者在类的作用域中显式引用了变量,以后才能再次访问该值。你知道吗

例如,您可以简单地将声明移动到类范围中:

class testClassForPytest:
  m = aClassInstance(classInput) 

  def test_case_1(self):
    #use of the instance m with a method of its class

在这种情况下,您根本不需要设置方法。如果需要在类声明中不可用的特定输入,也可以直接设置变量:

  @classmethod
  def setup_class(cls):
    cls.m = aClassInstance(classInput)

我想你的意思是,在setup_class中,你的意思是做cls.m = aClassInstance(classInput),而不仅仅是m = ...

为此,您可以修改代码以使用pytest的类作用域fixture来实现相同的结果:

@pytest.fixture(scope='class')
def setup_class(request):
  m = aClassInstance(classInput)
  request.cls.m = m # makes pytest to add created instance to class to which fixture is applied to

@pytest.mark.usefixtures("setup_class")
class testClassForPytest:
  def test_case_1(self):
    #use of the instance m as self.m

相关问题 更多 >