代码之家  ›  专栏  ›  技术社区  ›  4c74356b41

如何对其他夹具每次运行一次夹具

  •  1
  • 4c74356b41  · 技术社区  · 7 年前

    混杂的事物

    @pytest.fixture(scope="module")
    def fixture2(request):
        do something
    
    @pytest.fixture(scope="session", params=[ 1, 2, 3 ])
    def fixture1(request):
        do something else
    

    测试文件

    @pytest.mark.usefixtures('fixture2', 'fixture1')
    class TestSomething1(object):
        def test_1(self):
            pass
    
        def test_2(self):
            pass
    
    @pytest.mark.usefixtures('fixture1')
    class TestSomething2(object):
        def test_3(self):
            pass
    
        def test_4(self):
            pass
    

    结果是我得到了3组测试(每调用一个fixture1就有1组),但是fixture2对于所有3组测试只运行一次(至少这是我的理解)。我不知道如何使它在每次运行Fixture1时运行一次(不是每次测试都运行一次)。

    我最后做的是:

    @pytest.fixture(scope="module")
    def fixture2(request, fixture1):
        do something
    
    @pytest.fixture(scope="session", params=[ 1, 2, 3 ])
    def fixture1(request):
        do something else
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   4c74356b41    7 年前

    变化 @pytest.fixture(scope="module") 去别的地方,比如 @pytest.fixture(scope="class") @pytest.fixture(scope="function") . 模块范围是指每个模块运行一次。

    从fixture参数文档中:

    scope_ (默认)、“class”、“module”、“package”或“session”。

    “包装”目前被认为是实验性的。

    Pytest documentation on scopes

    使fixture1依赖于fixture2,如果希望每次调用一个fixture,则使用相同的作用域。

    推荐文章