【问题标题】:Can not use autouse fixture to import module无法使用 autouse 夹具导入模块
【发布时间】:2015-07-17 15:21:40
【问题描述】:

我有一个测试模块有一个自动使用装置

import pytest

@pytest.fixture(autouse=True):
def set_env_config(monkeypatch):
    palladium_config =   os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), 'config.py')
    monkeypatch.setenv('PALLADIUM_CONFIG', palladium_config)
    from A import B

并且在此测试模块中的每个后续测试中都需要 B 类,但是对于任何测试都无法实现此导入。

另外,我只修补环境变量

@pytest.fixture(autouse=True):
def set_env_config(monkeypatch):
    palladium_config =   os.path.join(os.path.dirname(os.path.dirname(os.getcwd())), 'config.py')
    monkeypatch.setenv('PALLADIUM_CONFIG', palladium_config)

并在每个测试用例中导入B类,它成功了。

这是为什么呢?为什么我不能在 autouse 夹具中导入类

非常感谢

【问题讨论】:

  • 您看到了什么错误或堆栈跟踪(如果有)?

标签: pytest fixture


【解决方案1】:

我猜你会期待类似下面的内容:

@pytest.fixture(autouse=True)
def do_an_import():
    from A import B

def test_foo():
    assert B.do_my_thing() == 'foo'

这不起作用,而执行以下操作可以满足您的要求:

def test_foo():
    from A import B
    assert B.do_my_thing() == 'foo'

不幸的是,在夹具中进行导入(第一个示例)会将 B 添加到该夹具函数的命名空间中,而不是测试函数的命名空间中。

同样,出于同样的原因,这也行不通:

@pytest.fixture
def not_an_autouse_fixture():
    from A import B

def test_foo(not_an_autouse_fixture):
    assert B.do_my_thing() == 'foo'

B 被导入到夹具的命名空间中,这与测试的命名空间不同。你可以这样做:

@pytest.fixture
def Cls():
    from A import B
    return B

def test_foo(Cls):
    assert Cls.do_my_thing() == 'foo'

或者您可以在模块的顶层导入它,例如:

from A import B

def test_foo(B):
    assert B.do_my_thing() == 'foo'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多