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()
Looking at the docs:
You are mocking the
get
function of therequests
module. Theget
method is supposed to return aresponse
object which later you assert itsstatus_code
. Therefore you're telling theget
mock function to return a mockresponse
. According to the docs,return_value
by default returns aMock
object, hence there should be no difference between 1 and 2 except that 1 is explicitly creating aMock
and 2 uses the default behavior.As a side note, that unit test is testing nothing because you set the
status_code
on theMock
object and then assert it. It's like: