我正在使用模拟来测试我开发的东西。在应用程序中,我使用glob循环目录中的某些内容,例如:“ / tmp / *。png”。它将收集目录中的所有.png文件并返回该文件的列表。
当我模拟glob时,它将返回调用。但是,当用于在for
循环中循环时,效果不佳。
#stack.py
import os
import click
import hashlib
import glob
def bar(x):
return os.path.basename(x)
def foo(path):
images = glob.glob(path)
for i in images:
bar(i)
if __name__ == '__main__':
foo()
#test_stack.py
import os
import unittest
import mock
import tempfile
import stack
class StackTest(unittest.TestCase):
temp_dir = tempfile.gettempdir()
temp_rg3 = os.path.join(temp_dir, "testfile.rg3")
@mock.patch('stack.os')
@mock.patch('stack.hashlib')
@mock.patch('stack.glob')
def test_stack(self, mock_glob, mock_hashlib, mock_os):
stack.foo(self.temp_rg3)
print(mock_glob.method_calls)
print(mock_os.method_calls)
这是返回:
[call.glob('/tmp/testfile.rg3')]
[]
[]
在glob.glob(path)
中调用了glob之后,其返回值不反映images
。因此,for循环不会开始,并且不会调用bar(i)
,因此mock_os
不返回任何调用。
如果我理解您的问题,似乎您尚未为模拟对象设置返回值。
当生成MagicMock对象时,其默认返回值是模拟实例本身,如here所述。该实例不是迭代器,因此在通过for循环进行迭代时不会执行任何操作。
您可以提供以下返回值:
@mock.patch('stack.os')
@mock.patch('stack.hashlib')
@mock.patch('stack.glob', return_value=['a.png', 'b.png', 'c.png'])
def test_stack(self, mock_glob, mock_hashlib, mock_os):
stack.foo(self.temp_rg3)
print(mock_glob.method_calls)
print(mock_os.method_calls)