I have found the following solution for your problem (I have tested it in my system):
import gitlab
from unittest.mock import patch
def get_all_iters():
#gl = gitlab.Gitlab(url='test_url', private_token)
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
# here remains only a patch() instruction
@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()
The execution of the test method on my system is:
['a', 'b']
that is the desired value for result
set by your instruction mockList.return_value = ['a', 'b']
.
Some notes about the test
Note the instructions:
instance_gl = mockGitlab.return_value
instance_get = mock_get.return_value
By those instructions we can get the right Mock objects.
Furthermore note the presence of the instructions patch.object()
and not only of the patch()
instruction.
May be can be exist a easier solution but because you desire to mock the complex instruction gl.groups.get(1).iterations.list()
I haven't been able to.
About this topic, this post is old but useful.