Pytest - 如何将参数传递给setup_class?

Mut*_*amy 6 python pytest

我有一些代码如下所示.我运行时遇到too few args错误.我没有setup_class明确地调用,所以不确定如何传递任何参数.我试过装饰方法@classmethod,但仍然看到相同的错误.

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

需要注意的一点 - 如果我没有将任何参数传递给类,只传递cls,那么我没有看到错误.

任何帮助是极大的赞赏.

在发布之前,我确实在问题#1问题#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
Run Code Online (Sandbox Code Playgroud)

fre*_*ish 9

你得到这个错误是因为你试图混合py.test支持的两种独立测试样式:经典单元测试和pytest的固定装置.

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

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
Run Code Online (Sandbox Code Playgroud)


met*_*ter 6

由于您将 this 与 pytest 一起使用,因此它只会setup_class使用一个参数和一个参数进行调用,看起来您无法在不更改pytest 调用 this 的方式的情况下更改

您应该只按照文档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
Run Code Online (Sandbox Code Playgroud)