首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟API密钥

模拟API密钥
EN

Stack Overflow用户
提问于 2015-05-07 20:10:56
回答 1查看 2.2K关注 0票数 1

我正在为Client类client.py编写单元测试,该类查询API。每个测试都使用c = client.Client("apikey")实例化客户机。一次运行一个测试很好,但是运行所有测试(例如,使用py.test),我会得到一个401:“异常:响应401:未经授权的访问。请求必须包含一个有效的api-key。”

我有一个有效的API键,但这不应该包含在单元测试中。我希望能解释一下为什么"apikey"只适用于一个查询。更具体地说,我如何模拟对API的调用?下面是一个单元测试示例:

代码语言:javascript
复制
def testGetContextReturnFields(self):
  c = client.Client("apikey")
  contexts = c.getContext("foo")

  assert(isinstance(contexts[0]["context_label"], str))
  assert(contexts[0]["context_id"] == 0)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-10 02:40:17

分离API调用和Client.getContext()方法的测试。为了显式测试API调用,修补请求对象.

代码语言:javascript
复制
import client
import httpretty
import requests
from mock import Mock, patch
...
def testGetQueryToAPI(self):
  """
  Tests the client can send a 'GET' query to the API, asserting we receive
  an HTTP status code reflecting successful operation.
  """
  # Arrange: patch the request in client.Client._queryAPI().
  with patch.object(requests, 'get') as mock_get:
    mock_get.return_value = mock_response = Mock()
    mock_response.status_code = 200

    # Act:
    c = client.Client()
    response = c._queryAPI("path", 'GET', {}, None, {})

    # Assert:
    self.assertEqual(response.status_code, 200)

# Repeat the same test for 'POST' queries.

为了测试getContext(),请用httpretty模拟HTTP .

代码语言:javascript
复制
@httpretty.activate
def testGetContextReturnFields(self):
  """
  Tests client.getContext() for a sample term.
  Asserts the returned object contains the corrcet fields and have contents as
  expected.
  """
  # Arrange: mock JSON response from API, mock out the API endpoint we expect
  # to be called.
  mockResponseString = getMockApiData("context_foo.json")
  httpretty.register_uri(httpretty.GET,
                         "http://this.is.the.url/query",
                         body=mockResponseString,
                         content_type="application/json")

  # Act: create the client object we'll be testing.
  c = client.Client()
  contexts = c.getContext("foo")

  # Assert: check the result object.
  self.assertTrue(isinstance(contexts, list),
    "Returned object is not of type list as expected.")
  self.assertTrue(("context_label" and "context_id") in contexts[0], 
    "Data structure returned by getContext() does not contain"
    " the required fields.")
  self.assertTrue(isinstance(contexts[0]["context_label"], str),
    "The \'context_label\' field is not of type string.")
  self.assertEqual(contexts[0]["context_id"], 0,
    "The top context does not have ID of zero.")
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30110776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档