[TIP] mock os.walk

Andrea Crotti andrea.crotti.0 at gmail.com
Thu Mar 22 07:47:11 PDT 2012


On 03/22/2012 02:36 PM, Andrea Crotti wrote:
>
> Ok I understood that error
>
> from mock import MagicMock, patch
> import os
>
> test_dir = [
>     ('root', ['d1, .git'], []),
> ]
>
> my_mock = MagicMock()
> my_mock.__iter__ = lambda _: iter(test_dir)
>
>
> @patch('os.walk', new=my_mock)
> def myfun():
>     for r, ds, df in os.walk('.'):
>         print(r, ds, df)
>
> myfun()
>
>
> and I have to actually assign __iter__ to a function, not just the 
> iterable..
> Now everything works but still os.walk('.') doesn't return anything, 
> even if I really think it shoud,
> anything else missing/ wrong??

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..



More information about the testing-in-python mailing list