Py.test monkeypatch.setattr (...) does not work in some cases

In conftest (in standalone device):

monkeypatch.setattr('collector.util.download_data', lambda url:"Winning" )

In collector / util.py :

def download_data(url):
    assert False

In the_caller.py :

from collector.util import download_data
def some_function():
    download_data("blah")

When I call some_function (), I get assert. However, if I change the_caller.py to:

import collector
def some_function():
    collector.util.download_data("blah")

then I get "Victory".

Why does this behave differently, and how can I make monkeypatch work for both scenarios?

+4
source share
1 answer

In general, the problem seems to be related to how the import works in python. I am not sure there is a good solution.

, , :

monkeypatch.setattr('collector.util.download_data.func_code', replacement_function.func_code )

. , .


​​ :

from _pytest.monkeypatch import monkeypatch

monkeypatch.setcode = lambda self, func_str, replacement_func : \
    monkeypatch.setattr( self, func_str + ".func_code", replacement_func.func_code )

: https://mail.python.org/pipermail/pytest-dev/2013-October/002386.html

+5

All Articles