[TIP] mock and patch

Michael Foord michael at voidspace.org.uk
Thu Mar 22 07:42:36 PDT 2012


On 22/03/2012 13:28, Andrea Crotti wrote:
> On 03/22/2012 11:51 AM, Michael Foord wrote:
>>
>>
>> Look in globals() and locals() where? patch needs to know *where* to 
>> do the patching, it's about as magic as it can usefully get. Python 
>> modules are nicely separated as namespaces, patch allows you patch 
>> names within a namespace - but you have to specify the namespace.
>>
>> All the best,
>>
>> Michael
>>
>
> Ok sure I didn't dig enough in the topic to understand if it would be 
> possible...
>
> This is related to the next question, I was trying something with 
> patch but I can't get it working properly:
>
> What I want to do is to make sure that inside a certain unittest 
> TestCase the walk function is a mock that I
> declare, so I thought I can do this patch
>
> @patch('utils.walk.walk', new=walk_mock)
> class TestWalkerClass(unittest.TestCase):
>
> where the mock is:
>
> test_dir = [
>     ('root', ['d1, .git'], []),
>     ('root/d1', [], ['setup.py']),
>     ('root/test', ['subdir'], ['test1.py']),
>     ('root/test/subdir', [], ['setup.py']),
>     ('root/.git', [], [])
> ]
>
> walk_mock = MagicMock()
> walk_mock.__iter__.return_value = iter(test_dir)
>
> where the idea is to mock the __iter__ method
>
>
> and it's actually used in real code as
>
>         for root, _, files in walk(self.src):
>             len_path = path_length(root)
>
>
>
> But there is still something clearly  wrong, as I get
> [andrea at precision utils]$ nosetests -m walk
> .FEE
> ======================================================================
> ERROR: Directory tree generator.
> ----------------------------------------------------------------------
> Traceback (most recent call last):
>   File "/usr/lib/python2.7/site-packages/nose/case.py", line 197, in 
> runTest
>     self.test(*self.arg)
>   File "/usr/lib/python2.7/site-packages/nose/util.py", line 622, in 
> newfunc
>     return func(*arg, **kw)
> TypeError: walk() takes at least 1 argument (0 given)
>
>
> Any hint on what I am doing wrong?
> Why does the mock which I pass would complain that it needs an argument?
>
The error is not from a mock, but from your actual walk function - which 
indicates that the patching is not in place. So it's likely that the 
patch is in the wrong place. It looks like you're patching the walk 
function in the walk module - but using it somewhere else. So changing 
your patch to "module_importing_and_using_walk.walk" instead should work.

All the best,

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