我有一个测试模块有一个autouse fixture
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 fixture中导入类
非常感谢
答案 0 :(得分:0)
我猜你正在期待以下内容:
@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'
不幸的是在fixture中进行导入(第一个例子)会将B添加到fixture函数的命名空间中,而不是测试函数的命名空间。
同样,这也不会出于同样的原因:
@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
被导入到fixture的命名空间中,这与测试的命名空间不同。你可以这样做:
@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'