[TIP] Should I always provide a return value when writing my test using mock library?

Carl Meyer carl at oddbird.net
Thu Apr 12 12:28:20 PDT 2012


Hi John,

On 04/12/2012 01:18 PM, John Wong wrote:
> Observations:
> 1. mock_reverse was never because `mock_calls` returns []. I've asserted
> with `called` method, and it returns False.
> 2. using render_reverse like this, the name `dummy_views` must exists -
> it must be a view function that actually exists in my Django project.
> Otherwise, it will return an error.
> 3. using render_reverse like this, the speed takes 0.2 - 0.3 seconds, as
> opposed to 0.06 s when I used `mock_reverse`.

All of these observations are consistent with the hypothesis that you
are not successfully patching the "reverse" function that is actually
used by "render_reverse". From what you've provided, your code looks
right (apart from the unnecessary MagicMocks). Are you sure that you are
passing the correct module path to patch? Is it possible that the module
containing render_reverse is actually being imported under two different
names, one with the project-module prefix and one without (this was a
common issue in Django projects prior to Django 1.4)? If so, you may be
patching the wrong instance of the module (and, if this is the case, you
should also upgrade to a 1.4-style manage.py and fix your imports, which
you can do even without upgrading to Django 1.4; see the 1.4 release notes).

It's hard to offer much besides those guesses short of seeing the full
project code tree. It may help in debugging to add "print(__name__)" in
your render_reverse function and see what module name is printed when
you run your test, and if it matches the module name you are patching.

Carl

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: OpenPGP digital signature
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20120412/d5d79d37/attachment.pgp>


More information about the testing-in-python mailing list