[TIP] mock and patch

Andrea Crotti andrea.crotti.0 at gmail.com
Thu Mar 22 06:28:41 PDT 2012


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?



More information about the testing-in-python mailing list