简体   繁体   中英

python mock return value not correct

I'm trying to test python mock but my results are not as expected, when I pring the return value it shows the mock object and not the actual result.

import mock
import unittest
import constants
import requests


class GetAddr():
    def __init__(self,name=''):        
        self.name = name

    def call_api(self):
        incr = 1
        self.no_of_calls(incr)
        r = requests.get('http://test.com')
        return r.text

    def no_of_calls(self,incr):
        counter = incr + 1
        return counter

class TestGetAddr(unittest.TestCase):
    maxDiff = None

    def test_case_1(self):                    
        self.getaddr = mock.MagicMock(GetAddr(name='John'))
        self.getaddr.return_value = {
        'return_code':200,
        'text':'CA, USA'
        }
        print self.getaddr.call_api()


if __name__ == '__main__':
    unittest.main()

Output:-

<MagicMock name='mock.call_api()' id='4526569232'>

Expected result: - To print the dictionary

{
        'return_code':200,
        'text':'CA, USA'
        }

You made a small mistake and set up a return_value on the object, not on the call_api method.

Here is a fixed version:

class TestGetAddr(unittest.TestCase):
    maxDiff = None

    def test_case_1(self):                    
        self.getaddr = mock.MagicMock(GetAddr(name='John'))
        self.getaddr.call_api.return_value = {  # <-- notice call_api here
        'return_code':200,
        'text':'CA, USA'
        }
        print self.getaddr.call_api()

Output:

{'text': 'CA, USA', 'return_code': 200}

Updated : As @jonrsharpe figured out there is another issue with these tests - they test nothing as I mocked the actual method that has to be tested.

If we consider current example we want to mock requests here, not the call_api method to do actual unit testing. Please pay attention to assertions and setting up a mock in the updated version:

class TestGetAddr(unittest.TestCase):
    maxDiff = None

    @mock.patch('requests.get')
    def test_case_1(self, requests_get_mock):
        expected_result = 'test.com has been called'
        response = mock.MagicMock()
        response.text = expected_result
        requests_get_mock.return_value = response

        instance = GetAddr(name='John')
        result = instance.call_api()

        self.assertEquals(result, expected_result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM