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
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 .
Yep_It's_Me Feb 21 '14 at 6:37 2014-02-21 06:37
source share