Python 模拟glob的问题不需要循环
我正在使用mock来测试我开发的东西。在应用程序中,我使用循环查找目录中的某些内容,例如:'/tmp/*.png'。它将收集目录中的所有.png文件,并返回这些文件的列表 当我模拟glob时,它会返回调用。但是,当用于Python 模拟glob的问题不需要循环,python,mocking,python-unittest,python-unittest.mock,Python,Mocking,Python Unittest,Python Unittest.mock,我正在使用mock来测试我开发的东西。在应用程序中,我使用循环查找目录中的某些内容,例如:'/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): ima
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后,其返回值不会反映图像的情况。因此,for循环不会开始,也不会调用bar(i)
,因此mock\u os
不会返回调用。如果我理解了您的问题,您似乎没有为mock设置返回值
生成MagicMock对象时,其默认返回值是模拟实例本身,如前所述。此实例不是迭代器,因此在由for循环迭代时不会执行任何操作
您可以按如下方式提供返回值,将mock更改为您正在调用的特定函数:
@mock.patch('stack.os')
@mock.patch('stack.hashlib')
@mock.patch('stack.glob.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)
如果我在glob.glob上调用了两个实例呢?如何为每个调用设置不同的值?要为不同的调用设置不同的值,可以向属性side\u effect
传递迭代器。有一个例子。