我已经浏览了页面 https://docs.python.org/3/library/unittest.mock-examples.html我看到他们列出了一个关于如何模拟生成器的例子
我有一个代码,我调用生成器给我一组值,我将这些值保存为字典。我想在我的单元测试中模拟对该生成器的调用。
我已经写了下面的代码,但它不起作用。
我哪里错了?
In [7]: items = [(1,'a'),(2,'a'),(3,'a')]
In [18]: def f():
print "here"
for i in [1,2,3]:
yield i,'a'
In [8]: def call_f():
...: my_dict = dict(f())
...: print my_dict[1]
...:
In [9]: call_f()
"here"
a
In [10]: import mock
In [18]: def test_call_f():
with mock.patch('__main__.f') as mock_f:
mock_f.iter.return_value = items
call_f()
....:
In [19]: test_call_f()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-19-33ca65a4f3eb> in <module>()
----> 1 test_call_f()
<ipython-input-18-92ff5f1363c8> in test_call_f()
2 with mock.patch('__main__.f') as mock_f:
3 mock_f.iter.return_value = items
----> 4 call_f()
<ipython-input-8-a5cff08ebf69> in call_f()
1 def call_f():
2 my_dict = dict(f())
----> 3 print my_dict[1]
KeyError: 1
最佳答案
改变这一行:
mock_f.iter.return_value = items
对此:
mock_f.return_value = iter(items)
关于python - 如何使用 mock.patch 模拟生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36165929/