问题描述
我正在尝试测试一个使它遍历列表的函数,并为列表中的每个项目调用os.path.exists
.我的测试是通过该函数的2个对象的列表.我需要os.path.exists
为其中一个返回True
,为另一个返回False
.我已经尝试过了:
I'm trying to test a function that I made that iterates through a list, and calls os.path.exists
for each item in the list. My test is passing the function a list of 2 objects. I need os.path.exists
to return True
for one of them and False
for the other. I have 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)
使用#1和#2行中的一个但不同时使用NameError: global name 'side_effect' is not defined
Using either but not both of line #1 and #2 give NameError: global name 'side_effect' is not defined
我发现了这个问题,并这样修改了我的代码:
I found this question and modified my code like so:
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)
这将产生TypeError: 'module' object is not callable
.我也尝试过切换这些行:
And this produces TypeError: 'module' object is not callable
.I also tried switching these lines:
mockobj = mock(spec=os.path.exists)
mockobj.side_effect = side_effect
为此
mockobj = mock(spec=os.path)
mockobj.exists.side_effect = side_effect
还有这个
mockobj = mock(spec=os)
mockobj.path.exists.side_effect = side_effect
,并产生相同的错误.谁能指出我做错了什么,我可以做些什么才能使它正常工作?
with the same error being produced. Can anyone point out what it is that I am doing wrong and what I can do to get this to work?
在下面发布我的答案后,我意识到我的第一段代码实际上也可以正常工作,我只需要m.side_effect = TestClass.side_effect
而不是m.side_effect = side_effect
.
After posting my answer below I realised that my first bit of code actually works as well, I just needed m.side_effect = TestClass.side_effect
instead of m.side_effect = side_effect
.
推荐答案
因此,在经过更多研究和反复试验之后,此处提供了大多数示例: http://www.voidspace.org.uk/python/mock/patch.html ,我解决了我的问题.
So after a bit more research and trial and error, with most of the 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
为arg_list
中的每个项目调用os.path.exist
,并返回os.path.exist
返回了True
的所有项目的列表.现在该测试通过了我想要的测试.
test
calls os.path.exist
for each item in arg_list
, and returns a list of all items that os.path.exist
returned True
for. This test now passes how I want it.
这篇关于模拟/补丁os.path.exists具有多个返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!