[TIP] mock.patch in version 0.5 doesn't mock __exit__ method on open files

Michael Foord fuzzyman at voidspace.org.uk
Thu Jul 23 14:56:29 PDT 2009


> Matthew Wilson wrote:
>   
>> This test passes when I use mock 0.4 and fails with 0.5:
>>
>> @patch('__builtin__.open')
>> def test_to_html(o):
>>
>>     global b
>>     b.to_html('bogus filepath')
>>
>> Here's the definition of b.to_html:
>>
>>     def to_html(self, filepath):
>>         """
>>         Write this bag out as HTML to a file at filepath.
>>         """
>>
>>         with open(filepath, 'w') as f:
>>             f.write(self.html)
>>
>> mock 0.5 has this code:
>>
>>     128     def __getattr__(self, name):
>>     129         if self._methods is not None:
>>     130             if name not in self._methods:
>>     131                 raise AttributeError("Mock object has no
>> attribute '%s'" % name)
>>     132         elif _is_magic(name):
>> --> 133             raise AttributeError(name)
>>
>> When __exit__ gets called, that code raises the AttributError.
>>
>> I can see good reasons fo not mocking magic methods automatically, but
>> can I explicitly say I do want __open__ and __exit__ to be mocked?
>>     


You can actually work around this (it won't work in Python 2.7 where 
__enter__ and __exit__ aren't looked up on the instance - but hopefully 
I have a more permanent fix in place by then):

 >>> import mock
 >>> m = mock.Mock()
 >>> def __enter__(*args):
...  print 'enter', args
...
 >>> def __exit__(*args):
...  print 'exit', args
...
 >>> m.__enter__ = __enter__
 >>> m.__exit__ = __exit__
 >>> with m:
...  raise Exception
...
enter ()
exit (<type 'exceptions.Exception'>, Exception(), <traceback object at 
0x78f08>)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
Exception
 >>>

All the best,

Michael Foord

>> mock is great software by the way.
>>
>> Matt
>>
>>
>>   
>>     
>
>
>   


-- 
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/blog





More information about the testing-in-python mailing list