Pytest如何向setup_class传递参数

2024-04-28 06:38:44 发布

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

我有一些代码如下所示。 当我运行它时,出现了一个too few args错误。 我没有显式调用setup_class,所以不知道如何向它传递任何参数。 我尝试用@classmethod装饰方法,但仍然看到相同的错误。

我看到的错误是-E TypeError: setup_class() takes exactly 2 arguments (1 given)

需要注意的一点是——如果我不向类传递任何参数,并且只传递cls,那么我就看不到错误。

任何帮助都非常感谢。

在发帖之前,我确实复习了这些问题question #1question #2。我不明白这些问题的解决方法,也不明白它们是如何工作的。

class A_Helper:
    def __init__(self, fixture):
        print "In class A_Helper"

    def some_method_in_a_helper(self):
        print "foo"

class Test_class:
    def setup_class(cls, fixture):
        print "!!! In setup class !!!"
        cls.a_helper = A_Helper(fixture)

    def test_some_method(self):
        self.a_helper.some_method_in_a_helper()
        assert 0 == 0

Tags: 方法selfhelper参数def错误setupsome
2条回答

出现此错误是因为您试图混合py.test支持的两种独立测试样式:经典单元测试和pytest的fixture。

我建议不要将它们混合起来,而是简单地定义一个类范围的fixture,如下所示:

import pytest

class A_Helper:
    def __init__(self, fixture):
        print "In class A_Helper"

    def some_method_in_a_helper(self):
        print "foo"

@pytest.fixture(scope='class')
def a_helper(fixture):
    return A_Helper(fixture)

class Test_class:
    def test_some_method(self, a_helper):
        a_helper.some_method_in_a_helper()
        assert 0 == 0

因为您在pytest中使用它,所以它将只调用带有一个参数和一个参数的setup_class,看起来您不能在不更改pytest calls this方式的情况下更改它。

您只需遵循documentation并按照指定定义setup_class函数,然后在该方法中使用该函数中所需的自定义参数设置类,这看起来像

class Test_class:
    @classmethod
    def setup_class(cls):
        print "!!! In setup class !!!"
        arg = '' # your parameter here
        cls.a_helper = A_Helper(arg)

    def test_some_method(self):
        self.a_helper.some_method_in_a_helper()
        assert 0 == 0

相关问题 更多 >