代码之家  ›  专栏  ›  技术社区  ›  CIsForCookies

pytest:使用“会话”范围固定装置和默认范围固定装置

  •  0
  • CIsForCookies  · 技术社区  · 7 年前

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

    conftest文件:

    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)
    

    baz 使用 install 固定装置我只希望有一个安装,并且对所有安装后测试使用相同的安装(不理想,但测试是最小的,目前我不想在重新安装上浪费太多时间)。

    我如何实现所有测试的一次安装,并且仍然使用我的其他固定装置,我希望保留它们的默认范围?

    安装 一个自动使用的fixture,但我实际上需要在当前默认范围的其他fixture之后调用它,并且应该保持这种方式

    0 回复  |  直到 7 年前
        1
  •  1
  •   Gabriel Cappelli    7 年前

    我能想到的唯一解决方案是使用一个标志来控制是否已经运行了安装代码,然后将fixture保留为默认范围。

    
    import pytest
    
    installed = False
    
    @pytest.fixture()
    def install():
        global installed
        if not installed:
            print('installing')
            installed = True
    
        2
  •  0
  •   msudder    5 年前

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

    使用会话范围的tmpdir\u工厂安装和删除tmp\u目录,使用内置tmpdir,因为pytest 3。x。