python 模拟下面的 return_value 是什么
python mock what is return_value in the following
我对 python mock 还很陌生,所以只是想了解一下。在下面的代码中,下面指示的 1 和 2 语句之间的区别是什么,因为最后我可以使用语句
中的任何一个设置 mock_response.status_code
import requests
def get_data():
response = requests.get('https://www.somesite.com')
return response.status_code
if __name__ == '__main__':
print get_data()
现在下面的代码有什么区别,
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()
查看 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.
您正在模拟 requests
模块的 get
函数。 get
方法应该 return 一个 response
对象,稍后您可以断言它的 status_code
。因此,您将 get
模拟函数告诉 return 一个模拟 response
。根据文档,return_value
默认情况下 return 是一个 Mock
对象,因此 1 和 2 之间应该没有区别,除了 1 明确创建一个 Mock
和 2 使用默认行为。
附带说明一下,该单元测试未测试任何内容,因为您在 Mock
对象上设置了 status_code
,然后断言了它。就像:
status_code = 200
assert status_code == 200
我对 python mock 还很陌生,所以只是想了解一下。在下面的代码中,下面指示的 1 和 2 语句之间的区别是什么,因为最后我可以使用语句
中的任何一个设置mock_response.status_code
import requests
def get_data():
response = requests.get('https://www.somesite.com')
return response.status_code
if __name__ == '__main__':
print get_data()
现在下面的代码有什么区别,
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()
查看 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.
您正在模拟 requests
模块的 get
函数。 get
方法应该 return 一个 response
对象,稍后您可以断言它的 status_code
。因此,您将 get
模拟函数告诉 return 一个模拟 response
。根据文档,return_value
默认情况下 return 是一个 Mock
对象,因此 1 和 2 之间应该没有区别,除了 1 明确创建一个 Mock
和 2 使用默认行为。
附带说明一下,该单元测试未测试任何内容,因为您在 Mock
对象上设置了 status_code
,然后断言了它。就像:
status_code = 200
assert status_code == 200