在open(file)中模拟行: [英] Mock for line in open(file):
问题描述
我想对应用程序的组件进行单元测试.该代码如下所示.
I am wanting to unittest a component of my application. The code looks a little like below.
def read_content_generator(myfile):
for line in open(myfile):
# do some string manipulation.
yield result
我遇到的问题是我无法在for
循环中模拟open()
功能.
The problem I am having is that I cannot mock the open()
functionality within a for
loop.
我想要的是这样的unittest
:(我知道这段代码不正确,但这只是我要执行的操作的一个示例):
What I am aiming for is a unittest
like this: (I know this code is not right but its just an example of what I am trying to do):
def test_openiteration(self):
with mock.patch('open') as my_openmock:
my_openmock.return_value = ['1','2','3']
response = myfunction()
self.assertEquals([1,2,3], response)
推荐答案
您可以模拟open()
返回StringIO对象.
You can mock open()
to return StringIO object.
mymodule.py:
def read_content_generator(myfile):
with open(myfile) as f:
for line in f:
yield '<{}>'.format(line)
请注意,我在此处使用了带有语句.
Note that I've used with statement there.
test_mymodule.py:
import io
import unittest
import unittest.mock as mock
import mymodule
class Tests(unittest.TestCase):
def test_gen(self):
fake_file = io.StringIO('foo\nbar\n')
with mock.patch('mymodule.open', return_value=fake_file, create=True):
result = list(mymodule.read_content_generator('filename'))
self.assertEqual(result, ['<foo\n>' , '<bar\n>'])
适用于python3.4.
Works for python3.4.
起初我尝试使用mock.mock_open(read_data='1\n2\n3\n')
,但是对迭代的支持似乎被破坏了.
At first I tried to use mock.mock_open(read_data='1\n2\n3\n')
but iteration support seems to be broken.
这篇关于在open(file)中模拟行:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!