【问题标题】:pytest: Using a "session" scope fixture along with default scope fixturespytest:使用“会话”范围夹具以及默认范围夹具
【发布时间】:2020-01-16 07:00:41
【问题描述】:

我正在构建一个 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

conf测试文件:

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 设为自动使用装置,但实际上我需要在当前默认作用域的其他一些装置之后调用它,并且应该保持这种方式

【问题讨论】:

  • 使用“范围”会话参数可以解决我的问题,但这将禁止我使用任何其他夹具,例如“tmp_dir” - 你的意思是,禁止使用 @ 987654326@ 在install?除此之外(以及install 夹具中错误放置的范围参数),我看不出您的代码有任何问题。
  • 您可以随时引入另一个夹具,例如real_install 是会话范围的,并将install 更改为类似def install(tmp_dir, real_install): return real_install 的默认函数范围。这样,安装仍将运行一次,您可以将其结果与功能范围的固定装置结合起来。
  • @hoefling 对于您的第一条评论 - 是的,但我实际上有很多这样的固定装置.. 对于您的第二条 - 考虑一下,但这会让我将很多固定装置更改为函数调用(例如,我有一个显示 pkg 路径的夹具 - 所以它必须是对函数的调用)
  • @CIsForCookies,你的意思是说你想在install 夹具中使用tmp_dir 和许多这样的功能范围夹具?或者您只是希望在 install 固定装置之前调用它们。

标签: python scope pytest fixtures


【解决方案1】:

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


import pytest

installed = False

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

【讨论】:

  • Fixtures 不应该真正保存状态机。我也想过这个,但我不会用这个,即使它解决了我的基本问题,因为我不想去全局
【解决方案2】:

ScopeMismatch on using session scoped fixture with pytest-mozwebqa plugin for py.test中所述

使用会话范围的 tmpdir_factory 安装和删除 tmp_dir,使用内置 tmpdir,因为 pytest 3.x。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 2022-06-12
    • 2022-01-21
    • 1970-01-01
    • 2018-01-30
    • 2020-02-24
    • 1970-01-01
    相关资源
    最近更新 更多