This is exactly what I wanted to highlight, is how can I also mock functions that have been previously defined?<br>I wanted to skim off the code but sometimes in libs, a function can be namespaced or not... and I would like to trap every possible uses of such function.<br>
<br>Is it possible?<br><br>Thanks,<br>Mathieu<br><br><div class="gmail_quote">Le 15 mars 2012 15:37, Jonathan Hartley <span dir="ltr"><<a href="mailto:tartley@tartley.com">tartley@tartley.com</a>></span> a écrit :<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div bgcolor="#FFFFFF" text="#000000"><div><div class="h5">
On 15/03/2012 18:30, Mathieu Drapeau wrote:
</div></div><blockquote type="cite"><div><div class="h5">Hi all,<br>
I am fairly new to mock and I would like to know how to fix an
issue during module imports and scope of functions.<br>
Here is a snippet that explain problem I am dealing with:<br>
<br>
from mock import MagicMock<br>
import sys<br>
sys.func = lambda: 'x'<br>
from sys import func<br>
print func()<br>
# outputs 'x'<br>
sys.func = MagicMock(return_value='mocked_x')<br>
print func()<br>
# outputs 'x', it is not mocked<br>
<br>
How could I fix this?<br>
<br>
Thanks,<br>
Mat<br>
<br>
<fieldset></fieldset>
<br>
</div></div><pre>_______________________________________________
testing-in-python mailing list
<a href="mailto:testing-in-python@lists.idyll.org" target="_blank">testing-in-python@lists.idyll.org</a>
<a href="http://lists.idyll.org/listinfo/testing-in-python" target="_blank">http://lists.idyll.org/listinfo/testing-in-python</a>
</pre>
</blockquote>
<br>
Hey Mathieu,<br>
<br>
Your 7th line changes the value of sys.func (the 'func' attribute on
local variable 'sys') but you haven't changed the value of local
variable 'func'. Modifying one won't affect the other. You'd see the
same behaviour even if MagicMock wasn't involved (e.g assigning
'sys.func' to 0 will not affect the value of 'func' either.)<br>
<br>
From the code you've posted, it's not clear to me what you're trying
to achieve.<br>
<br>
Perhaps you meant to write:<br>
<br>
>>> func = Mock(return_value='mocked')<br>
>>> func()<br>
mocked<br>
<br>
or<br>
<br>
>>> sys.func = Mock(return_value='mocked')<br>
>>> sys.func()<br>
mocked<br>
<br>
Best regards,<br>
<br>
Jonathan<span class="HOEnZb"><font color="#888888"><br>
<br>
<pre cols="72">--
Jonathan Hartley <a href="mailto:tartley@tartley.com" target="_blank">tartley@tartley.com</a> <a href="http://tartley.com" target="_blank">http://tartley.com</a>
Made of meat. <a href="tel:%2B44%207737%20062%20225" value="+447737062225" target="_blank">+44 7737 062 225</a> twitter/skype: tartley
</pre>
</font></span></div>
</blockquote></div><br>