Mock / patch os.path.exists with multiple return values

I am trying to test a function that I did, iterate through a list, and call os.path.exists for each item in the list. My test passes the function a list of two objects. I need os.path.exists to return True for one of them and False for the other. I tried this:

 import mock import os import unittest class TestClass(unittest.TestCase): values = {1 : True, 2 : False} def side_effect(arg): return values[arg] def testFunction(self): with mock.patch('os.path.exists') as m: m.return_value = side_effect # 1 m.side_effect = side_effect # 2 arglist = [1, 2] ret = test(argList) 

Using either, but not both lines # 1 and # 2, give NameError: global name 'side_effect' is not defined

I found this question and changed my code like this:

 import mock import os class TestClass(unittest.TestCase): values = {1 : True, 2 : False} def side_effect(arg): return values[arg] def testFunction(self): mockobj = mock(spec=os.path.exists) mockobj.side_effect = side_effect arglist = [1, 2] ret = test(argList) 

And this creates a TypeError: 'module' object is not callable . I also tried switching these lines:

 mockobj = mock(spec=os.path.exists) mockobj.side_effect = side_effect 

for this

 mockobj = mock(spec=os.path) mockobj.exists.side_effect = side_effect 

and this one

 mockobj = mock(spec=os) mockobj.path.exists.side_effect = side_effect 

with the same error. Can someone point out what I'm doing wrong and what can I do to make this work?

EDIT: After posting my answer below, I realized that my first bit of code really works, I just need m.side_effect = TestClass.side_effect instead of m.side_effect = side_effect .

+3
python mocking python-unittest
Feb 21 '14 at 6:37
source share
2 answers

So, after a bit more research and trial and error, with most examples here: http://www.voidspace.org.uk/python/mock/patch.html , I solved my problem.

 import mock import os def side_effect(arg): if arg == 1: return True else: return False class TestClass(unittest.TestCase): patcher = mock.patch('os.path.exists') mock_thing = patcher.start() mock_thing.side_effect = side_effect arg_list = [1, 2] ret = test(arg_list) self.assertItemsEqual([1], ret) 

test calls os.path.exist for each element in arg_list and returns a list of all elements for which os.path.exist returned True for. This test now passes as I want.

+3
Feb 24 '14 at 0:30
source share

you could do self.side_effect I believe. since the initial definition was not global, calling side_effect scans the global scope

0
Sep 15 '16 at 20:32
source share



All Articles