# Path: performanceplatform/utils/http_with_backoff.py
# class HttpWithBackoff(Http):
# 
#     def __init__(self, cache=None, timeout=None,
#                  proxy_info=None,
#                  ca_certs=None, disable_ssl_certificate_validation=False,
#                  backoff_strategy_predicate=GABackoff):
#         dscv = disable_ssl_certificate_validation
#         super(HttpWithBackoff, self).__init__(
#             cache=cache, timeout=timeout,
#             proxy_info=proxy_info,
#             ca_certs=ca_certs,
#             disable_ssl_certificate_validation=dscv)
#         if backoff_strategy_predicate:
#             self._backoff_strategy_predicate = backoff_strategy_predicate
#         else:
#             self._backoff_strategy_predicate = GABackoff
# 
#     def request(self,
#                 uri,
#                 method="GET",
#                 body=None,
#                 headers=None,
#                 redirections=DEFAULT_MAX_REDIRECTS,
#                 connection_type=None):
# 
#         delay = 10
# 
#         for n in range(_MAX_RETRIES):
#             response, content = super(HttpWithBackoff, self).request(
#                 uri,
#                 method,
#                 body,
#                 headers,
#                 redirections,
#                 connection_type)
# 
#             response_action = self._backoff_strategy_predicate(
#                 response, content, method, uri)
# 
#             if response_action.should_retry:
#                 retry_info = response_action.retry_info
#                 retry_info += '(Attempt {} of {})'.format(n + 1, _MAX_RETRIES)
#                 if n + 1 < _MAX_RETRIES:
#                     retry_info += ' Retrying in {} seconds...'.format(delay)
#                 logging.info(retry_info)
#                 time.sleep(delay)
#                 delay *= 2
#             else:
#                 return response, content
# 
#         # we made _MAX_RETRIES requests but none worked
#         logging.error(
#             'Max retries exceeded for {}'.format(uri),
#             # HttpLibException doesn't exist but this fits with the format
#             # for logging other request failures
#             extra={
#                 'exception_class': 'HttpLibException',
#                 'exception_message': '{}: {}'.format(response.status,
#                                                      response.reason)
#             }
#         )
# 
#         return response, content
# 
# Path: performanceplatform/utils/http_with_backoff.py
# def parse_reason(response, content):
#     """
#     Google return a JSON document describing the error. We should parse this
#     and extract the error reason. See
#     https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors
#     """
#     def first_error(data):
#         errors = data['error']['errors']
#         if len(errors) > 1:
#             # we have more than one error. We should capture that?
#             logging.info('Received {} errors'.format(len(errors)))
#         return errors[0]
# 
#     try:
#         json_data = json.loads(content)
#         return first_error(json_data)['reason']
#     except:
#         return response.reason


from mock import patch, call
from nose.tools import assert_equal
from performanceplatform.utils.http_with_backoff import HttpWithBackoff
from performanceplatform.utils.http_with_backoff import parse_reason
from httplib2 import Response
import logging
        logging.info(content)

        mock_request.return_value = (service_unavailable_response,
                                     content)

        response = HttpWithBackoff().request('http://fake.com',
                                             method="PUT",
                                             body="bar",
                                             headers="foo",
                                             redirections=10,
                                             connection_type="wibble")

        assert_equal(response, (service_unavailable_response,
                                content))

        assert_equal(
            [call(10), call(20), call(40), call(80), call(160)],
            mock_sleep.call_args_list)

        mock_request.assert_called_with('http://fake.com',
                                        "PUT",
                                        "bar",
                                        "foo",
                                        10,
                                        "wibble")

    def test_parse_reason_with_empty_content(self):
        assert_equal(parse_reason(Response({}), ''), 'Ok')

    def test_parse_reason_with_html_content(self):

# Path: performanceplatform/utils/http_with_backoff.py
# class HttpWithBackoff(Http):
# 
#     def __init__(self, cache=None, timeout=None,
#                  proxy_info=None,
#                  ca_certs=None, disable_ssl_certificate_validation=False,
#                  backoff_strategy_predicate=GABackoff):
#         dscv = disable_ssl_certificate_validation
#         super(HttpWithBackoff, self).__init__(
#             cache=cache, timeout=timeout,
#             proxy_info=proxy_info,
#             ca_certs=ca_certs,
#             disable_ssl_certificate_validation=dscv)
#         if backoff_strategy_predicate:
#             self._backoff_strategy_predicate = backoff_strategy_predicate
#         else:
#             self._backoff_strategy_predicate = GABackoff
# 
#     def request(self,
#                 uri,
#                 method="GET",
#                 body=None,
#                 headers=None,
#                 redirections=DEFAULT_MAX_REDIRECTS,
#                 connection_type=None):
# 
#         delay = 10
# 
#         for n in range(_MAX_RETRIES):
#             response, content = super(HttpWithBackoff, self).request(
#                 uri,
#                 method,
#                 body,
#                 headers,
#                 redirections,
#                 connection_type)
# 
#             response_action = self._backoff_strategy_predicate(
#                 response, content, method, uri)
# 
#             if response_action.should_retry:
#                 retry_info = response_action.retry_info
#                 retry_info += '(Attempt {} of {})'.format(n + 1, _MAX_RETRIES)
#                 if n + 1 < _MAX_RETRIES:
#                     retry_info += ' Retrying in {} seconds...'.format(delay)
#                 logging.info(retry_info)
#                 time.sleep(delay)
#                 delay *= 2
#             else:
#                 return response, content
# 
#         # we made _MAX_RETRIES requests but none worked
#         logging.error(
#             'Max retries exceeded for {}'.format(uri),
#             # HttpLibException doesn't exist but this fits with the format
#             # for logging other request failures
#             extra={
#                 'exception_class': 'HttpLibException',
#                 'exception_message': '{}: {}'.format(response.status,
#                                                      response.reason)
#             }
#         )
# 
#         return response, content
# 
# Path: performanceplatform/utils/http_with_backoff.py
# def parse_reason(response, content):
#     """
#     Google return a JSON document describing the error. We should parse this
#     and extract the error reason. See
#     https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors
#     """
#     def first_error(data):
#         errors = data['error']['errors']
#         if len(errors) > 1:
#             # we have more than one error. We should capture that?
#             logging.info('Received {} errors'.format(len(errors)))
#         return errors[0]
# 
#     try:
#         json_data = json.loads(content)
#         return first_error(json_data)['reason']
#     except:
#         return response.reason


# Path: tests/performanceplatform/utils/test_http_with_backoff.py
from mock import patch, call
from nose.tools import assert_equal
from performanceplatform.utils.http_with_backoff import HttpWithBackoff
from performanceplatform.utils.http_with_backoff import parse_reason
from httplib2 import Response
import logging

        logging.info(content)

        mock_request.return_value = (service_unavailable_response,
                                     content)

        response = HttpWithBackoff().request('http://fake.com',
                                             method="PUT",
                                             body="bar",
                                             headers="foo",
                                             redirections=10,
                                             connection_type="wibble")

        assert_equal(response, (service_unavailable_response,
                                content))

        assert_equal(
            [call(10), call(20), call(40), call(80), call(160)],
            mock_sleep.call_args_list)

        mock_request.assert_called_with('http://fake.com',
                                        "PUT",
                                        "bar",
                                        "foo",
                                        10,
                                        "wibble")

    def test_parse_reason_with_empty_content(self):
        assert_equal(parse_reason(Response({}), ''), 'Ok')

    def test_parse_reason_with_html_content(self):

        assert_equal(parse_reason(Response({}), '<strong>lol</strong>'), 'Ok')