模拟Google Directory Admin API

时间:2016-06-24 20:48:46

标签: python-2.7 unit-testing mocking

我有一个代码剪切,可以从google域中检索用户列表。我正在尝试编写单元测试来返回用户列表。但我不想查询googleapi服务器返回unittest的用户列表。我如何模拟http?请记住,google apiclient包含了api post请求。

也可以帮助您深入了解构建服务对象。

1 个答案:

答案 0 :(得分:0)

我通过在云控制台中为我正在处理的项目创建API密钥来解决这个问题。

我创建了一个文件http_response.json并复制了我期待的响应示例。 我使用了以下代码段:

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()

我打了出来。可能有错别字:)