[TIP] mock os.walk

Andrea Crotti andrea.crotti.0 at gmail.com
Thu Mar 22 08:04:51 PDT 2012


On 03/22/2012 02:47 PM, Andrea Crotti wrote:
>
> Looking around I found out that this:
> my_mock = Mock(return_value=iter(test_dir))
>
> actually works perfectly, even if I'm not sure why...
> I would still like to know why my MagicMock is not returning anything 
> though..

Puff I finally solved all my problems and all the tests are passing :)

I found another thing which I think is at least counter-intuitive.

This below will not work as expected:

my_mock = Mock(return_value=iter(test_dir))

@patch('os.walk', new=my_mock)
def myfun2():
     for r, ds, df in os.walk('.'):
         print(r, ds, df)


@patch('os.walk', new=my_mock)
def myfun3():
     for r, ds, df in os.walk('.'):
         print(r, ds, df)


myfun2()
myfun3()

because the iterator is consumed the first run and in the second run 
there it will just
return the empty list.
Is it the desired behaviour?



More information about the testing-in-python mailing list