Pytest - 如何向setup_class传递参数?

12

我有以下代码。

当我运行它时,我遇到了<code>too few args</code>的错误。
我没有显式调用<code>setup_class</code>方法,因此不知道如何传递任何参数。
我尝试使用<code>@classmethod</code>修饰符修饰该方法,但仍然看到同样的错误。

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

需要注意的一点是 - 如果我没有向类传递任何参数,只传递了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

@metatoaster 我不应该实例化 Test_class。我期望使用我提供的 arg 实例化 A_Helper。然后使用该对象 (a_helper),我希望调用 A_Helper 中的方法。我是否在概念上遗漏了什么?如果我不给 setup_class 提供参数,则相同的代码可以工作,而无需实例化任何内容。 - Muthu Palanisamy
正如@metatoaster所指出的那样,这是不可能的。但是定义一个a_helper fixture(使用scope='class')并将其传递给test_some_method是否更简单呢?通常,只有为了使其与经典的单元测试风格兼容而添加setup_class处理到py.test中。我建议不要混淆这两个东西(即经典风格和py.test fixture风格)。 - freakish
2个回答

16

你之所以会得到这个错误,是因为你正在尝试混合使用两种 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

嗨,我希望使用你的方法,但除了在测试函数中使用fixture之外,还将其传递给类似于setup_classsetup_method的prolog函数。也许你可以扩展你的示例以添加这个功能?谢谢! - Zohar81
这意味着引用的fixture fixture 也应该作为class来范围化,这是一场噩梦。 - VisioN

7

由于您正在使用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

我编辑了问题,并将“arg”替换为“fixture”。我的意图是 - 测试方法中,我想要传递一个或多个fixture 帮助方法,并在帮助方法中对fixture执行一些操作。如果无法传递第二个参数,则我不确定如何在方法体中传递fixture。 - Muthu Palanisamy
文档中的一个评论非常有趣,特别是在最后的“备注”部分:现在xunit风格的函数已经与fixture机制集成,并遵守调用中涉及的fixture的适当作用域规则。我想知道这是否破坏了@freakish在其他答案中提到的那种“混合”技术,在作用域规则不被遵守时可能之前有效。 - jxramos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接