【发布时间】:2016-06-24 20:48:46
【问题描述】:
我截取了一段代码,用于从 google 域中检索用户列表。我正在尝试编写一个单元测试来返回用户列表。但我不想查询 googleapi 服务器以返回单元测试的用户列表。我如何模拟http?请记住,google apiclient 包装了 api post 请求。
还可以深入了解模拟构建服务对象的答案也会有所帮助。
【问题讨论】:
标签: python-2.7 unit-testing mocking
我截取了一段代码,用于从 google 域中检索用户列表。我正在尝试编写一个单元测试来返回用户列表。但我不想查询 googleapi 服务器以返回单元测试的用户列表。我如何模拟http?请记住,google apiclient 包装了 api post 请求。
还可以深入了解模拟构建服务对象的答案也会有所帮助。
【问题讨论】:
标签: python-2.7 unit-testing mocking
我通过在云控制台中为我正在处理的项目创建 API 密钥解决了这个问题。
我创建了一个文件 http_response.json 并复制了我期望的响应样本。 我使用了以下sn-p:
import unittest
from apiclient.discovery import build
from apiclient.http import HttpMock
import original_file
from apiclient.discovery import build
class TestAdmin(unittest.TestCase):
def setUp(self):
server_response = 'Blah Blah Blah' # sample server response
with open('http_response.json','w') as response_file:
json.dump(server_response, response_file)
def test_admin(self):
http = HttpMock('http_response.json', {'status': '200'})
api_key = 'api key created on google cloud'
service_object = build('admin', 'directory_v1', http=http, developerKey=api_key)
# The call to build should be made to a method
# in the original class that implements the build service
request = service_object.users().list(customer='my_customer', maxResults=1, orderBy='email',query='/')
http = HttpMock('allusers.json', {'status': '200'})
response = request.execute(http=http)
self.assertEquals(response, server_response)
def tearDown(self):
# delete the temporary file created
try:
os.remove(self.user_response)
except OSError:
pass
if __name__ == '__main__':
unittest.main()
我输入了这个。可能有错别字:)
【讨论】: