【问题标题】:Pytest: making global fixture for entire test runPytest:为整个测试运行制作全局夹具
【发布时间】:2019-01-03 10:24:40
【问题描述】:

我有以下模块结构:

.
├── conftest.py
└── test
    ├── test_one.py
    └── test_two.py

我的 conftest.py 包含一个夹具:

import pytest

@pytest.fixture(scope='session')
def sophisticated_fixture():
    print('\nFixture init')
    yield 42
    print('\nFixture kill')

我的test_{one,two}.py 测试如下所示:

from conftest import sophisticated_fixture


def test_a(sophisticated_fixture):
    assert sophisticated_fixture == 42


def test_b(sophisticated_fixture):
    assert sophisticated_fixture == 42

我希望在顶级目录中运行pytest -s 将使用相同的夹具运行所有测试,因为我已将其定义为会话级别。但是,会发生这种情况:

============================= test session starts ==============================
platform linux -- Python 3.6.6, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: /home/tomasz/example, inifile:
collected 4 items

test/test_one.py 
Fixture init
..
test/test_two.py 
Fixture init
..
Fixture kill

Fixture kill


=========================== 4 passed in 0.01 seconds ===========================

很明显,每个测试模块都会调用两次fixture函数,并且fixture在测试运行结束时退出。

如何在整个测试会话期间使我的夹具全局化?

【问题讨论】:

  • 可笑丑陋的解决方案:使全局变量保存夹具值,仅当它为 None 时才对其进行初始化。无论如何,我希望 pytest 有一些更聪明的方法来处理这个问题。

标签: python unit-testing pytest fixtures


【解决方案1】:

您不必在测试文件中导入夹具。 Fixtures 由 pytest 自动发现。从测试文件中删除以下行后尝试。

from conftest import sophisticated_fixture

【讨论】:

  • 我要补充一点,从 conftest 模块导入 anything 是个坏主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多