首页 文章

在每个方法上运行范围“class”的Pytest fixture

提问于
浏览
2

我正在尝试用Pytest创建一个测试环境 . 我们的想法是将测试方法分组到类中 .

对于每个类/组,我想附加一个将要参数化的 config 夹具 . 这样我就可以使用"configuration A"运行所有测试,然后使用"configuration B"进行所有测试,依此类推 .

而且,我想要一个 reset fixture,可以在特定方法或类的所有方法之前执行 .

The problem I have there is, once I apply my reset fixture (to a method or to a whole class), the config fixture seems to work in the function scope instead of the class scope. So, once I apply the reset fixture, the config fixture is called before/after every method in the class.

下面的代码重现了这个问题:

import pytest
from pytest import *

@fixture(scope='class')
def config(request):
    print("\nconfiguring with %s" % request.param)
    yield
    print("\ncleaning up config")

@fixture(scope='function')
def reset():
    print("\nreseting")

@mark.parametrize("config", ["config-A", "config-B"], indirect=True)
#@mark.usefixtures("reset")
class TestMoreStuff(object):

    def test_a(self, config):
        pass

    def test_b(self, config):
        pass

    def test_c(self, config):
        pass

测试显示 config 夹具应该如何工作,对整个类只执行一次 . 如果取消注释 usefixtures 装饰,您会注意到 config 夹具将在每个测试方法中执行 . Is it possible to use the reset fixture without triggering this behaviour?

2 回答

  • 3

    正如我在评论中提到的,这似乎是Pytest 3.2.5中的一个错误 .

    有一种解决方法,即"force"参数化的范围 . 因此,在这种情况下,如果在 parametrize 装饰器中包含 scope="class" ,则会得到所需的行为 .

    import pytest
    from pytest import *
    
    @fixture(scope='class')
    def config(request):
        print("\nconfiguring with %s" % request.param)
        yield
        print("\ncleaning up config")
    
    @fixture(scope='function')
    def reset():
        print("\nreseting")
    
    @mark.parametrize("config", ["config-A", "config-B"], indirect=True, scope="class")
    @mark.usefixtures("reset")
    class TestMoreStuff(object):
    
        def test_a(self, config):
            pass
    
        def test_b(self, config):
            pass
    
        def test_c(self, config):
            pass
    
  • 0

    这取决于您使用的是哪个版本的pytest .

    在旧版本的 pytest 中实现这一点存在一些语义问题 . 所以,这个想法还没有在旧的 pytest 中实现 . 有人已经提出了实施相同的建议 . 你可以参考this

    "Fixture scope doesn't work when parametrized tests use parametrized fixtures" . 这就是错误 . 你可以参考this

    此问题已在最新版本的pytest中得到解决 . 这是commitpytest 3.2.5 相同

    希望它会对你有所帮助 .

相关问题