python mock what is return_value in the following

倾然丶 夕夏残阳落幕 提交于 2019-12-13 09:39:22

问题


i am very new to python mock and so just trying to understand the same. In the below code what is the difference between 1 and 2 statements indicated below,because in the end i can set mock_response.status_code with either of the statements

   import requests

    def get_data():
        response = requests.get('https://www.somesite.com')
        return response.status_code

    if __name__ == '__main__':
        print get_data()

Now what is the difference between the following codes,

    from call import get_data
    import unittest
    from mock import Mock,patch
    import requests

    class TestCall(unittest.TestCase):
        def test_get_data(self):
            with patch.object(requests,'get') as get_mock:
                1.get_mock.return_value = mock_response = Mock()
                  # OR 
                2.mock_response = get_mock.return_value
                mock_response.status_code = 200
                assert get_data() == 200

    unittest.main()

回答1:


Looking at the docs:

return_value: The value returned when the mock is called. By default this is a new Mock (created on first access). See the return_value attribute.

You are mocking the get function of the requests module. The get method is supposed to return a response object which later you assert its status_code. Therefore you're telling the get mock function to return a mock response. According to the docs, return_value by default returns a Mock object, hence there should be no difference between 1 and 2 except that 1 is explicitly creating a Mock and 2 uses the default behavior.

As a side note, that unit test is testing nothing because you set the status_code on the Mock object and then assert it. It's like:

status_code = 200
assert status_code == 200


来源:https://stackoverflow.com/questions/44984887/python-mock-what-is-return-value-in-the-following

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!