def testGetAccessToken_failure(self):
   self._MockSubprocessOutput('Not logged in.', return_code=1)
   with self.assertRaises(luci_auth.AuthorizationError):
     luci_auth.GetAccessToken()
Exemple #2
0
def Request(url,
            method='GET',
            params=None,
            data=None,
            accept=None,
            content_type='urlencoded',
            use_auth=False,
            retries=None):
    """Perform an HTTP request of a given resource.

  Args:
    url: A string with the URL to request.
    method: A string with the HTTP method to perform, e.g. 'GET' or 'POST'.
    params: An optional dict or sequence of key, value pairs to be added as
      a query to the url.
    data: An optional dict or sequence of key, value pairs to send as payload
      data in the body of the request.
    accept: An optional string to specify the expected response format.
      Currently only 'json' is supported, which attempts to parse the response
      content as json. If omitted, the default is to return the raw response
      content as a string.
    content_type: A string specifying how to encode the payload data,
      can be either 'urlencoded' (default) or 'json'.
    use_auth: A boolean indecating whether to send authorized requests, if True
      luci-auth is used to get an access token for the logged in user.
    retries: Number of times to retry the request in case of ServerError. Note,
      the request is _not_ retried if the response is a ClientError.

  Returns:
    A string with the content of the response when it has a successful status.

  Raises:
    A ClientError if the response has a 4xx status, or ServerError if the
    response has a 5xx status.
  """
    del retries  # Handled by the decorator.

    if params:
        url = '%s?%s' % (url, six.moves.urllib.parse.urlencode(params))

    body = None
    headers = {}

    if accept == 'json':
        headers['Accept'] = 'application/json'
    elif accept is not None:
        raise NotImplementedError('Invalid accept format: %s' % accept)

    if data is not None:
        if content_type == 'json':
            body = json.dumps(data, sort_keys=True, separators=(',', ':'))
            headers['Content-Type'] = 'application/json'
        elif content_type == 'urlencoded':
            body = six.moves.urllib.parse.urlencode(data)
            headers['Content-Type'] = 'application/x-www-form-urlencoded'
        else:
            raise NotImplementedError('Invalid content type: %s' %
                                      content_type)
    else:
        headers['Content-Length'] = '0'

    if use_auth:
        headers['Authorization'] = 'Bearer %s' % luci_auth.GetAccessToken()

    logging.info('Making API request: %s', url)
    http = httplib2.Http()
    response, content = http.request(url,
                                     method=method,
                                     body=body,
                                     headers=headers)
    if response.status != 200:
        raise BuildRequestError(url, response, content)

    if accept == 'json':
        if content[:4] == JSON_SECURITY_PREFIX:
            content = content[4:]  # Strip off security prefix if found.
        content = json.loads(content)
    return content
 def testGetAccessToken_success(self):
   self._MockSubprocessOutput('access-token')
   self.assertEqual(luci_auth.GetAccessToken(), 'access-token')