1

I am trying to mock the return value of the following method

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)

Although I have tried to mock the return value of the method call, it is still returning the mock object instead of what I tried to mock

<MagicMock name='Gitlab().groups.get().iterations.list()' id='1688988996464'>
Songg Tùng
  • 139
  • 8

1 Answers1

3

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.

frankfalse
  • 1,553
  • 1
  • 4
  • 17