pythonpython-unittestpython-unittest.mock

Python unittest how to mock a passed in class


Trying to unittest a method that receives a class as an argument but unsure how to mock it right

I am trying to unittest this method `

def get_local_path(p4_path, p4):
    if p4_path.endswith('...'):
        p4_path = p4_path.replace('/...', '')
    path = p4.run("where", p4_path)[0]
    for key, value in list(path.items()):
            if key == 'path':
                path = value.replace('\\', '/')
                return path

The method receives p4 as an argument from a different script, and p4 is the p4python class (its already instantiated), so i can run p4 commands. I am trying to learn how to unittest and really unsure how to go about mocking this. I tried to patch it but that didn't work, and then i tried to create a Mock object and pass it in but I have no idea how to deal with when it calls the .run.

def test_get_local_path(self):
    mock_p4 = mock.Mock()
    # not sure what to do here, or how to get it to assign return value to p4.run
    get_local_path('//mypath/test', mock_p4)

Solution

  • Simply assign the desired return value to p4.run.return_value:

    def test_get_local_path(self):
        mock_p4 = mock.Mock()
        p4.run.return_value = "..."
        get_local_path('//mypath/test', mock_p4)