我正在尝试模拟以下方法的返回值
import gitlab
from unittest.mock import patch
def get_all_iters():
gl = gitlab.Gitlab(url='test_url', private_token)
result = gl.groups.get(1).iterations.list() # trying to mock the result of this method call
return result
@patch('gitlab.Gitlab')
@patch('gitlab.v4.objects.GroupManager')
@patch('gitlab.mixins.ListMixin.list')
def test_my_code(mockGitlab, mockGroup, mockList):
mockList.return_value = ['a', 'b']
result = get_all_iters()
print(result)
虽然我尝试模拟方法调用的返回值,但它仍然返回模拟对象,而不是我尝试模拟的
<MagicMock name='Gitlab().groups.get().iterations.list()' id='1688988996464'>
我为您的问题找到了以下解决方案(我已在我的系统中测试过):
import gitlab
from unittest.mock import patch
def get_all_iters():
#gl = gitlab.Gitlab(url='test_url', private_token) # <--- Remove your instruction and substitute with the following
gl = gitlab.Gitlab(url='test_url', private_token='test_token_value') # <--- HERE I have set the value for the argument private_token
result = gl.groups.get(1).iterations.list() # trying to mock the result of this method call
return result
# I leave only one patch() as decorator, while other mocks are managed
# by context managers inserted into the body of the test method
@patch('gitlab.Gitlab')
def test_my_code(mockGitlab):
instance_gl = mockGitlab.return_value
with patch.object(instance_gl, 'groups') as mock_groups:
with patch.object(mock_groups, 'get') as mock_get:
instance_get = mock_get.return_value
with patch.object(instance_get, 'iterations') as mock_iterations:
with patch.object(mock_iterations, 'list') as mockList:
# -------> FINALLY here are your test instructions
mockList.return_value = ['a', 'b']
result = get_all_iters()
print(result)
test_my_code()
测试方法在我的系统上的执行是:
['a', 'b']
这是根据您的指令
result
设置的 mockList.return_value = ['a', 'b']
所需值的打印。
注意说明:
instance_gl = mockGitlab.return_value
instance_get = mock_get.return_value
通过这些指令我们可以获得正确的 Mock 对象。
进一步注意指令
patch.object()
的存在,而不仅仅是 patch()
指令。
可能有一个更简单的解决方案,但是由于您希望模拟
list
,因此需要通过复杂的指令:
gl.groups.get(1).iterations.list()
我只能找到这个方法了!
这篇文章很旧,但对于在我的解释中添加更多细节很有用。