问题
I'm trying to test some code using pytest
and need to change a function from some module. One of my imports also imports that function, but this is failing when I change the method using monkeypatch
. Here is what I have:
util.py
def foo():
raise ConnectionError # simulate an error
return 'bar'
something.py
from proj import util
need_this = util.foo()
print(need_this)
test_this.py
import pytest
@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')
import proj.something
And this raises ConnectionError
. If I change
test_this.py
import pytest
@pytest.fixture(autouse=True)
def fix_foo(monkeypatch):
monkeypatch.setattr('proj.something.util.foo', lambda: 'bar')
def test_test():
import proj.something
Then it imports with the monkeypatch
working as expected. I've read though this and tried to model my testing from it, but that isn't working unless I import inside of a test. Why does the monkeypatch not do anything if it is just a normal import in the testing file?
回答1:
That is because the fixture is applied to the test function not the entire code. autouse=True
attribute just says that it should be used in every test
来源:https://stackoverflow.com/questions/51992496/monkeypatching-not-carrying-through-class-import