关于python:Pytest-如何将参数传递给setup_class?

Pytest - How to pass an argument to setup_class?

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

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

需要注意的一点-如果我不将任何参数传递给类,而仅传递cls,则我看不到错误。

我们非常感谢您的帮助。

在发布之前,我确实审核了这些问题#1和问题#2。我不了解针对这些问题发布的解决方案或它们如何工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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


之所以会出现此错误,是因为您试图混合使用py.test支持的两种独立测试样式:经典单元测试和pytest的固定装置。

我建议不要混合使用它们,而是简单地定义一个类范围的灯具,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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调用方式的情况下进行更改。

您应该只遵循文档并按指定定义setup_class函数,然后在该方法中使用您需要在该函数中使用的自定义参数来设置类,该类类似于

1
2
3
4
5
6
7
8
9
10
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