[TIP] Mock and function namespace

Mathieu Drapeau matdrapeau at gmail.com
Thu Mar 15 12:45:22 PDT 2012


This is exactly what I wanted to highlight, is how can I also mock
functions that have been previously defined?
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.

Is it possible?

Thanks,
Mathieu

Le 15 mars 2012 15:37, Jonathan Hartley <tartley at tartley.com> a écrit :

>  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 listtesting-in-python at lists.idyll.orghttp://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/9cb17e31/attachment.htm>


More information about the testing-in-python mailing list