首页 > 解决方案 > pytest:使用“会话”范围夹具以及默认范围夹具

问题描述

我正在构建一个 pytest 测试套件,测试我正在构建的一个包。测试应该验证有关 pkg 的一些内容,例如次要功能检查、次要完整性检查等。一些检查是在安装前完成的,一些是在安装后完成的(示例代码):


测试文件:

import pytest

class PreInstallTests(object):
    def test_foo(self, bar):
        assert bar > 2

class PostInstallTests(object):
    def test_goo(self, baz):
        assert baz < 3

    def test_hoo(self, baz):
        assert baz > 1

测试文件:

import pytest
@pytest.fixture
def tmp_dir():
    os.mkdir('tmp')
    yield
    shutil.rmtree('tmp')

@pytest.fixture
def bar(tmp_dir):
    yield 3

@pytest.fixture
def baz(install, tmp_dir):
    yield 2

@pytest.fixture(scope='session')
def install():
    # installs the pkg... (takes a lot of time)

从这里可以看出,我有 2 个安装后测试,每个测试都使用一个名为的夹具,该夹具baz使用该install夹具。我只想安装一个,并且对所有安装后测试使用相同的安装(不理想,但测试很少,我不想在当前重新安装上浪费太多时间)。

使用“范围”会话参数可以解决我的问题,但这将禁止我使用任何其他固定装置,例如“tmp_dir”(它代表我需要的固定装置,并且必须保持默认范围......)

我怎样才能为所有测试实现一次安装,并且仍然使用我想要保留其默认范围的其他固定装置?

我想制作install一个 autouse 固定装置,但我实际上需要在当前默认作用域的其他一些固定装置之后调用它,并且应该保持这种方式

标签: pythonscopepytestfixtures

解决方案


我能想到的唯一解决方案是设置一个标志来控制您是否已经运行了安装代码,然后将夹具保持在默认范围内。


import pytest

installed = False

@pytest.fixture()
def install():
    global installed
    if not installed:
        print('installing')
        installed = True

推荐阅读