[TIP] Mock and function namespace
Jonathan Hartley
tartley at tartley.com
Thu Mar 15 12:37:40 PDT 2012
On 15/03/2012 18:30, Mathieu Drapeau wrote:
> Hi all,
> I am fairly new to mock and I would like to know how to fix an issue
> during module imports and scope of functions.
> Here is a snippet that explain problem I am dealing with:
>
> from mock import MagicMock
> import sys
> sys.func = lambda: 'x'
> from sys import func
> print func()
> # outputs 'x'
> sys.func = MagicMock(return_value='mocked_x')
> print func()
> # outputs 'x', it is not mocked
>
> How could I fix this?
>
> Thanks,
> Mat
>
>
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python
Hey Mathieu,
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.)
From the code you've posted, it's not clear to me what you're trying to
achieve.
Perhaps you meant to write:
>>> func = Mock(return_value='mocked')
>>> func()
mocked
or
>>> sys.func = Mock(return_value='mocked')
>>> sys.func()
mocked
Best regards,
Jonathan
--
Jonathan Hartley tartley at tartley.com http://tartley.com
Made of meat. +44 7737 062 225 twitter/skype: tartley
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20120315/4c820e50/attachment.htm>
More information about the testing-in-python
mailing list