问题
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