[TIP] Issue with "mock" package and isinstance()
tom at recursivedream.com
Fri Jul 29 09:31:44 PDT 2011
I've been using Michael Foord's awesome /mock/ package and I've loved
it... now I'm running into an issue. I'm patching a class, pretty simple:
from my.module.path import Class
patch = mock.patch('my.module.path.Class', spec=Class)
mocked = patch.start()
mocked.return_value = MyReplacementClass()
I'm doing things this way because I need to mock out a class, but
provide an alternate implementation that uses similar logic to the real
class (basically mocking an external API by turning it into a
Somewhere else, my code gets this mock client and a function calls:
isinstance(client, my.module.path.Class): ...
This call fails with:
TypeError: isinstance() arg 2 must be a class, type, or tuple of
classes and type
This was confusing to me, so I did a bit of digging to figure out what
/Class/ really was, but all was well. Here's what I got:
<MagicMock spec='Class' id='50389456'>
Seems right to me! Additionally, if I change the instance check in the
production code to:
isinstance(client, my.module.path.Class._spec_class): ...
It works just fine! I can't do this for obvious reasons, but it seems to
prove that the MagicMock at least has the correct information somewhere,
it's just not being properly inspected by isinstance().
Any thoughts? I really need this to work.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the testing-in-python