Python monkeypatching未执行类导入

Python monkeypatching未执行类导入,python,pytest,monkeypatching,Python,Pytest,Monkeypatching,我正在尝试使用pytest测试一些代码,需要更改某个模块中的函数。我的一个导入也导入了该函数,但当我使用monkeypatch更改方法时,该操作失败。以下是我所拥有的: util.py def foo(): raise ConnectionError # simulate an error return 'bar' from proj import util need_this = util.foo() print(need_this) import pytest @p

我正在尝试使用
pytest
测试一些代码,需要更改某个模块中的函数。我的一个导入也导入了该函数,但当我使用
monkeypatch
更改方法时,该操作失败。以下是我所拥有的:

util.py

def foo():
    raise ConnectionError  # simulate an error
    return 'bar'
from proj import util

need_this = util.foo()
print(need_this)
import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

import proj.something
import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

def test_test():
    import proj.something
something.py

def foo():
    raise ConnectionError  # simulate an error
    return 'bar'
from proj import util

need_this = util.foo()
print(need_this)
import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

import proj.something
import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

def test_test():
    import proj.something
测试这个.py

def foo():
    raise ConnectionError  # simulate an error
    return 'bar'
from proj import util

need_this = util.foo()
print(need_this)
import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

import proj.something
import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

def test_test():
    import proj.something
这会引发
ConnectionError
。如果我改变

测试这个.py

def foo():
    raise ConnectionError  # simulate an error
    return 'bar'
from proj import util

need_this = util.foo()
print(need_this)
import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

import proj.something
import pytest

@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
    monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')

def test_test():
    import proj.something

然后导入时,monkeypatch将按预期工作。我已经阅读并尝试从中建模测试,但除非在测试内部导入,否则这是行不通的。如果monkeypatch只是测试文件中的正常导入,为什么它不做任何事情?

这是因为夹具应用于测试函数,而不是整个代码
autouse=True
属性只是说应该在每个测试中使用它