python - module level code run twice when patching -
consider next simple code:
test_code.py
def f(): homecoming 'unpatched' import patch_stuff patch_stuff.patch_it_up() print f()
patch_stuff.py
from mock import patch def patch_it_up(): p = patch('test_code.f') m = p.start() m.return_value = 'patched'
i expect output of running python test_code.py
be
patched
however output is:
unpatched patched
how come?
there 2 problems in code. first, test_code.py file called twice - first when phone call it, , 1 time again when mock
imports purpose of creating patch. should alter follows:
def f(): homecoming 'unpatched' import patch_stuff if __name__ == "__main__": patch_stuff.patch_it_up() print f()
this print 'unpatched'
string. leads sec thing: the documentation suggests not how patchers work. when phone call start
method returns patched object used. expected output can achieved next modifications:
patch_stuff.py
from mock import patch def patch_it_up(): p = patch('test_code.f') m = p.start() m.return_value = 'patched' homecoming m
test_code.py
def f(): homecoming 'unpatched' import patch_stuff if __name__ == "__main__": m = patch_stuff.patch_it_up() print m()
this print expected 'patched'
string.
this makes scenario not practical, examples in documentation show possibility of modifying modules imported in current context. e.g., work:
from mock import patch def patch_it_up(): import test_code p = patch('test_code.f') m = p.start() m.return_value = 'patched' print "inside patch_it_up:", test_code.f()
python mocking python-mock patching
No comments:
Post a Comment