[TIP] mock can't address a class by class name

Yang teddyyyy123 at gmail.com
Wed Dec 12 14:08:54 PST 2012


if I have mymodule.py:

class MyClass:
       def run():
             return 1



then I try to mock it in test:


with patch('mymodule.MyClass') as mock:
      instance = mock.return_value

      mock.run.return_value =2


this works fine. but if in my test code, I import the MyClass first:

from mymodule import MyClass

with patch('MyClass') as mock:
 ......

it fails to find 'MyClass'



even more serious is that if I refer to the mock class with full name
mymodule.Myclass in the patch() line, but the production code refers to it
as simply Myclass after importing it first, the mock does not take effect,
 so I have to modify production code to mock it out. this completely does
not work for real testing cases.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20121212/b769b267/attachment.htm>


More information about the testing-in-python mailing list