monkeypatching not carrying through class import

非 Y 不嫁゛ 提交于 2019-12-11 12:46:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!