[TIP] mock os.walk

Michael Foord michael at voidspace.org.uk
Thu Mar 22 08:30:20 PDT 2012


On 22/03/2012 15:24, Andrea Crotti wrote:
> On 03/22/2012 03:13 PM, Michael Foord wrote:
>>
>> Well, it may or may not be desired - but it is what you have told 
>> mock to do. :-)
>>
>> If you're using mock 0.8 you can do:
>>
>>     @patch('os.walk', return_value=iter(test_dir))
>>     def test(mock_walk):
>>         ...
>>
>> This creates a new mock instead of a pre-created one. If you really 
>> *want* to use a single mock for all your tests then you can use a 
>> side_effect to create and return a fresh iterator every time:
>>
>>     my_mock = Mock(side_effect=lambda *a, **kw: iter(test_dir))
>>
>> HTH,
>>
>> Michael
>>
> Yes sure it makes sense, but actually it's not a problem because 
> passing the list
> my_mock = Mock(return_value=test_dir)
>
> works perfectly, so I don't need to create an extra function..
>
> The annoying thing was that I got this problem also using the mock 
> once, *but* patching
> the TestCase class instead of the single modules, and in that case I 
> think it's counter-intuitive..
>
If you apply patch to a class it is the same as applying it to every 
test method in the class. So although it may look like you were only 
using it once you were actually calling it several times.

How would you expect Mock to be able to deal with this - you have given 
it an iterator object as the return value and it has no way of knowing 
that you actually want a *new* iterator every time it is called.

I think it's really just a question of understanding the tools and what 
they're doing. Mock is flexible enough to allow you to return a 
different object every time it is called (using side_effect), or you can 
have patch create a new mock for every test. They will only do what you 
tell them though.

In your place I would prefer to have patch create the mock for you, 
there's less danger of problems caused by re-using mocks.

Michael

-- 
http://www.voidspace.org.uk/

May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html




More information about the testing-in-python mailing list