[pytest-dev] monkeypatch.setattr of functions and from imports
Daniel Nouri
daniel.nouri at gmail.com
Wed Oct 23 19:30:31 CEST 2013
Dear all
I have a function 'somefunc' in module 'a'. Another module 'b' imports
that function with a "from import":
a.py:
def somefunc():
return 'hey!'
b.py:
from a import somefunc
def someotherfunc():
return somefunc() + 'there'
I want to now test 'someotherfunc' while patching away 'somefunc':
def test_someotherfunc(monkeypatch):
from b import someotherfunc
monkeypatch.setattr('a.somefunc', lambda: 'eh?')
someotherfunc()
But this will fail, since 'b' imported somefunc from 'a' before we
monkey patched the module's attribute. Without a "from import", this
would work:
b.py:
import a
def someotherfunc():
return a.somefunc() + 'there'
What I would normally resort to is patch somefunc's func_code, so that
even code that used a "from import" before I could patch will use the
patched version.
Thoughts?
Cheers
Daniel
More information about the Pytest-dev
mailing list