[TIP] mock os.walk

Staple, Danny (BSKYB) DStaple at nds.com
Thu Mar 22 08:16:03 PDT 2012


You are only creating the iter once, so it is the correct behavior.  You could create a tiny function to build you the mock with a fresh iter each time, and call it in the patch statement.

-----Original Message-----
From: testing-in-python-bounces at lists.idyll.org [mailto:testing-in-python-bounces at lists.idyll.org] On Behalf Of Andrea Crotti
Sent: 22 March 2012 15:05
To: Testing in Python
Subject: Re: [TIP] mock os.walk

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?

_______________________________________________
testing-in-python mailing list
testing-in-python at lists.idyll.org
http://lists.idyll.org/listinfo/testing-in-python


**************************************************************************************
This message is confidential and intended only for the addressee. If you have received this message in error, please immediately notify the postmaster at nds.com and delete it from your system as well as any copies. The content of e-mails as well as traffic data may be monitored by NDS for employment and security purposes. To protect the environment please do not print this e-mail unless necessary.

NDS Limited. Registered Office: One London Road, Staines, Middlesex, TW18 4EX, United Kingdom. A company registered in England and Wales. Registered no. 3080780. VAT no. GB 603 8808 40-00
**************************************************************************************



More information about the testing-in-python mailing list