【问题标题】:Call custom function from within Pytest fixture从 Pytest 夹具中调用自定义函数
【发布时间】:2020-01-30 10:29:06
【问题描述】:

我想在conftest.py 中编写一个 Pytest 固定装置,它在自身内部调用一个函数,默认情况下,它什么都不做,但可以在测试模块中重新定义。

#conftest.py

def within_foo():
    pass

@pytest.fixture
def foo():
    if some_condition():
        within_foo()
    something_else()


# test_foo.py

def within_foo():
    print('this should be printed when running test_foo')

def test_foo(foo):
    pass

有没有一种干净的方法来实现这个?

【问题讨论】:

  • 谁来测试你的测试?看起来很复杂。
  • @mrEvgenX 你问谁来编写测试?测试的编写将由几位软件工程师完成,这就是为什么我关心让它尽可能直观和减少开销。
  • 抱歉,我没有回答您的具体问题。但这取决于您实际约束的上下文。请问,在测试中使用复杂的逻辑是否谨慎?您的应用程序具有复杂的逻辑,要对其进行验证,您需要编写测试。如果您的测试有复杂的逻辑,您将不得不在测试中编写测试。
  • @mrEvgenX 我明白你的意思。我们正在从一个已弃用的测试框架转换为 Pytest,虽然这会带来多个好处,但我们有一个硬性限制,即编写测试对工程师来说“感觉”是一样的。最后,逻辑不会太复杂。我们只需要在测试设置的某些步骤之间注入一些代码。

标签: python pytest fixtures


【解决方案1】:

您可以通过继承来实现这一点。为所有测试创建一个基类,然后您可以决定要覆盖哪些测试within_foo()

class BaseTest:

    @pytest.fixture
    def foo(self):
        self.within_foo()

    def within_foo(self):
        pass

@pytest.mark.testing
class TestSomething(BaseTest):

    def within_foo(self):
        print('this should be printed when running test_foo')

    def test_foo(self, foo):
        pass

@pytest.mark.testing
class TestSomethingElse(BaseTest):

    def test_foo_again(self, foo):
        print('test_foo_again')

输出

========================== 2 passed in 0.08 seconds ===========================
this should be printed when running test_foo
.test_foo

.test_foo_again

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    相关资源
    最近更新 更多