Пример #1
0
    def test_delete(self):
        # in case an empty payload is returned
        def monkey_patched_delete(uri,
                                  params=None,
                                  headers=None,
                                  proxies=None,
                                  json=None,
                                  timeout=None,
                                  verify=False):
            return MockResponse(204, None)

        requests.delete = monkey_patched_delete
        status, data = HttpClient('apikey', DEFAULT_CONFIG,
                                  'anyurl.com').delete('/resource')
        self.assertIsNone(data)

        # in case a non-empty payload is returned
        expected_data = '{"message": "deleted"}'

        def monkey_patched_delete_returning_payload(uri,
                                                    params=None,
                                                    headers=None,
                                                    proxies=None,
                                                    json=None,
                                                    timeout=None,
                                                    verify=False):
            return MockResponse(204, expected_data)

        requests.delete = monkey_patched_delete_returning_payload
        status, data = HttpClient('apikey', DEFAULT_CONFIG,
                                  'anyurl.com').delete('/resource')
        self.assertEqual(json.loads(expected_data), data)

        requests.delete = self.requests_original_delete
Пример #2
0
    def cacheable_get_json(self):

        cached_data = '{"name": "james bond", "designation": "007"}'
        other_data = '{"name": "doctor no"}'

        def monkey_patched_get(uri,
                               params=None,
                               headers=None,
                               timeout=None,
                               verify=False):
            return MockResponse(200, other_data)

        requests.get = monkey_patched_get

        # cache hit
        cache = MockCache(cached_data)
        instance = HttpClient(cache=cache)
        status, data = instance.cacheable_get_json('http://anyurl.com')
        self.assertEqual(200, status)
        self.assertEqual(cached_data, data)

        # cache miss
        cache = MockCache(None)
        instance = HttpClient(cache=cache)
        status, data = instance.cacheable_get_json('http://anyurl.com')
        self.assertEqual(200, status)
        self.assertEqual(other_data, data)

        requests.get = self.requests_original_get
 def __init__(self, API_key, config):
     assert API_key is not None, 'You must provide a valid API Key'
     self.API_key = API_key
     assert isinstance(config, dict)
     self.ap_client = airpollution_client.AirPollutionHttpClient(
         API_key, HttpClient(API_key, config, ROOT_POLLUTION_API_URL))
     self.new_ap_client = airpollution_client.AirPollutionHttpClient(
         API_key, HttpClient(API_key, config, NEW_ROOT_POLLUTION_API_URL))
Пример #4
0
 def __init__(self, API_key, config):
     assert isinstance(API_key, str), 'You must provide a valid API Key'
     self.API_key = API_key
     assert isinstance(config, dict)
     self.http_client = HttpClient(API_key, config, ROOT_AGRO_API)
     self.geotiff_downloader_http_client = HttpClient(
         self.API_key, config, ROOT_DOWNLOAD_GEOTIFF_API)
     self.png_downloader_http_client = HttpClient(self.API_key, config,
                                                  ROOT_DOWNLOAD_PNG_API)
 def __init__(self, API_key, map_layer):
     assert API_key is not None, 'You must provide a valid API Key'
     self.API_key = API_key
     assert map_layer is not None, 'You must provide a valid map layer name'
     assert isinstance(map_layer, str), 'Map layer name must be a string'
     self.map_layer = map_layer
     self.http_client = HttpClient()
    def test_get_json_parse_error(self):

        def monkey_patched_get(uri, params=None, headers=None, proxies=None, timeout=None, verify=False):
            return MockResponse(200, 123846237647236)

        requests.get = monkey_patched_get
        self.assertRaises(pyowm.commons.exceptions.ParseAPIResponseError,
                          HttpClient('apikey', DEFAULT_CONFIG, 'anyurl.com').get_json, '/resource', params=dict(a=1, b=2))
        requests.get = self.requests_original_get
    def test_put(self):
        expected_data = '{"key": "value"}'

        def monkey_patched_put(uri, params=None, headers=None, proxies=None, json=None, timeout=None, verify=False):
            return MockResponse(200, expected_data)

        requests.put = monkey_patched_put
        status, data = HttpClient('apikey', DEFAULT_CONFIG, 'anyurl.com').put('/resource', data=dict(key=7))
        self.assertEqual(json.loads(expected_data), data)
        requests.put = self.requests_original_put
Пример #8
0
    def test_get_json_parse_error(self):
        def monkey_patched_get(uri, params=None, headers=None):
            return MockResponse(200, 123846237647236)

        requests.get = monkey_patched_get
        self.assertRaises(parse_response_error.ParseResponseError,
                          HttpClient().get_json,
                          'http://anyurl.com',
                          params=dict(a=1, b=2))
        requests.get = self.requests_original_get
    def test_get_json(self):

        expected_data = '{"name": "james bond", "designation": "007"}'

        def monkey_patched_get(uri, params=None, headers=None, proxies=None, timeout=None, verify=False):
            return MockResponse(200, expected_data)

        requests.get = monkey_patched_get
        status, data = HttpClient('apikey', DEFAULT_CONFIG, 'anyurl.com').get_json('/resource')
        self.assertEqual(json.loads(expected_data), data)
        requests.get = self.requests_original_get
    def test_get_geotiff(self):
        expected_data = b'II*\x00\x08\x00\x04\x00k{\x84s\x84\x84\x8c\x84\x84\x84k\x84k\x84\x84k{s\x9c\x94k\x84'

        def monkey_patched_get(uri, stream=True, params=None, headers=None, proxies=None, timeout=None, verify=False):
            return MockResponse(200, expected_data)

        requests.get = monkey_patched_get
        status, data = HttpClient('apikey', DEFAULT_CONFIG, 'anyurl.com').get_geotiff('/resource')
        self.assertIsInstance(data, bytes)
        self.assertEqual(expected_data, data)
        requests.get = self.requests_original_get
    def test_get_png(self):
        expected_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x01\x03\x00\x00\x00%\xdbV\xca\x00\x00\x00\x03PLTE\x00p\xff\xa5G\xab\xa1\x00\x00\x00\x01tRNS\xcc\xd24V\xfd\x00\x00\x00\nIDATx\x9ccb\x00\x00\x00\x06\x00\x0367|\xa8\x00\x00\x00\x00IEND\xaeB`\x82'

        def monkey_patched_get(uri, stream=True, params=None, headers=None, proxies=None, timeout=None, verify=False):
            return MockResponse(200, expected_data)

        requests.get = monkey_patched_get
        status, data = HttpClient('apikey', DEFAULT_CONFIG, 'anyurl.com').get_png('/resource')
        self.assertIsInstance(data, bytes)
        self.assertEqual(expected_data, data)
        requests.get = self.requests_original_get
Пример #12
0
    def test_put(self):
        expected_data = '{"key": "value"}'

        def monkey_patched_put(uri, params=None, headers=None, json=None):
            return MockResponse(200, expected_data)

        requests.put = monkey_patched_put
        status, data = HttpClient().put('http://anyurl.com', data=dict(key=7))
        self.assertEquals(json.loads(expected_data), data)

        requests.put = self.requests_original_put
 def test_ssl_certs_verification_failure(self):
     # https://wrong.host.badssl.com does not have a valid SSL cert
     config = DEFAULT_CONFIG.copy()
     config['connection']['use_ssl'] = True
     config['connection']['verify_ssl_certs'] = True
     instance = HttpClient('fakeapikey',
                           config,
                           'wrong.host.badssl.com',
                           admits_subdomains=False)
     self.assertRaises(pyowm.commons.exceptions.InvalidSSLCertificateError,
                       HttpClient.get_json, instance, '')
 def __init__(self, API_key, map_layer, config):
     assert API_key is not None, 'You must provide a valid API Key'
     self.API_key = API_key
     assert map_layer is not None, 'You must provide a valid map layer name'
     assert isinstance(map_layer, str), 'Map layer name must be a string'
     self.map_layer = map_layer
     assert isinstance(config, dict)
     self.http_client = HttpClient(API_key,
                                   config,
                                   ROOT_TILE_URL,
                                   admits_subdomains=False)
Пример #15
0
    def test_get_json(self):

        expected_data = '{"name": "james bond", "designation": "007"}'

        def monkey_patched_get(uri, params=None, headers=None):
            return MockResponse(200, expected_data)

        requests.get = monkey_patched_get
        status, data = HttpClient().get_json('http://anyurl.com')
        self.assertEquals(json.loads(expected_data), data)
        requests.get = self.requests_original_get
 def test_get_geotiff(self):
     # https://download.osgeo.org/geotiff/samples/made_up/bogota.tif
     config = DEFAULT_CONFIG.copy()
     config['connection']['use_ssl'] = True
     instance = HttpClient('fakeapikey',
                           config,
                           'download.osgeo.org',
                           admits_subdomains=False)
     status, data = instance.get_geotiff(
         'geotiff/samples/made_up/bogota.tif')
     self.assertIsNotNone(data)
     self.assertIsInstance(data, bytes)
Пример #17
0
    def test_delete(self):
        # in case an empty payload is returned
        def monkey_patched_delete(uri, params=None, headers=None, json=None):
            return MockResponse(204, None)

        requests.delete = monkey_patched_delete
        status, data = HttpClient().delete('http://anyurl.com')
        self.assertIsNone(data)

        # in case a non-empty payload is returned
        expected_data = '{"message": "deleted"}'

        def monkey_patched_delete_returning_payload(uri,
                                                    params=None,
                                                    headers=None,
                                                    json=None):
            return MockResponse(204, expected_data)

        requests.delete = monkey_patched_delete_returning_payload
        status, data = HttpClient().delete('http://anyurl.com')
        self.assertEquals(json.loads(expected_data), data)

        requests.delete = self.requests_original_delete
    def test_timeouts(self):
        timeout = 0.5

        def monkey_patched_get_timeouting(uri, params=None, headers=None, proxies=None, timeout=timeout, verify=False):
            raise requests.exceptions.Timeout()

        requests.get = monkey_patched_get_timeouting
        config = DEFAULT_CONFIG.copy()
        config['connection']['timeout_secs'] = timeout
        try:
            status, data = HttpClient('apikey', config, 'anyurl.com').get_json('/resource')
            self.fail()
        except pyowm.commons.exceptions.TimeoutError:
            requests.get = self.requests_original_get
Пример #19
0
class TestHTTPClient(unittest.TestCase):

    instance = HttpClient()

    def test_get_json_against_httpbin_ok(self):
        # http://httpbin.org/ip
        status, data = self.instance.get_json('http://httpbin.org/ip')
        self.assertEqual(200, status)
        self.assertIsInstance(data, dict)

    def test_get_json_against_httpbin_status_code_ko(self):
        # http://httpbin.org/status/400
        expected_status = 400

        self.assertRaises(api_call_error.APICallError, HttpClient.get_json,
                          self.instance,
                          'http://httpbin.org/status/' + str(expected_status))

    def test_get_json_against_httpbin_parse_error(self):
        # http://httpbin.org/xml
        try:
            status, data = self.instance.get_json('http://httpbin.org/xml')
            self.fail()
        except parse_response_error.ParseResponseError:
            pass

    def test_put_against_httpbin(self):
        # http://httpbin.org/put
        formdata = dict(a=1, b=2, c=3)
        status, data = self.instance.put('http://httpbin.org/put',
                                         data=formdata)
        self.assertEqual(200, status)
        self.assertIsInstance(data, dict)
        self.assertEqual(formdata, data['json'])

    def test_delete_against_httpbin(self):
        # http://httpbin.org/delete
        formdata = dict(a=1, b=2, c=3)
        status, data = self.instance.delete('http://httpbin.org/delete',
                                            data=formdata)
        self.assertEqual(200, status)
        self.assertIsInstance(data, dict)
        self.assertEqual(formdata, data['json'])

    def test_ssl_certs_verification_failure(self):
        # https://wrong.host.badssl.com does not have a valid SSL cert
        client = HttpClient(timeout=4, use_ssl=True, verify_ssl_certs=True)
        self.assertRaises(api_call_error.APIInvalidSSLCertificateError,
                          HttpClient.get_json, client,
                          'https://wrong.host.badssl.com')
Пример #20
0
    def test_timeouts(self):
        timeout = 0.5

        def monkey_patched_get_timeouting(uri,
                                          params=None,
                                          headers=None,
                                          timeout=timeout,
                                          verify=False):
            raise requests.exceptions.Timeout()

        requests.get = monkey_patched_get_timeouting
        try:
            status, data = HttpClient(
                timeout=timeout).get_json('http://anyurl.com')
            self.fail()
        except api_call_error.APICallTimeoutError:
            requests.get = self.requests_original_get
Пример #21
0
class TestHTTPClient(unittest.TestCase):

    instance = HttpClient()

    def test_get_json_against_httpbin_ok(self):
        # https://httpbin.org/ip
        status, data = self.instance.get_json('http://httpbin.org/ip')
        self.assertEqual(200, status)
        self.assertIsInstance(data, dict)

    def test_get_json_against_httpbin_status_code_ko(self):
        # https://httpbin.org/status/400
        expected_status = 400

        self.assertRaises(api_call_error.APICallError, HttpClient.get_json,
                          self.instance, 'https://httpbin.org/status/' +
                                              str(expected_status))

    def test_get_json_against_httpbin_parse_error(self):
        # https://httpbin.org/xml
        try:
            status, data = self.instance.get_json('http://httpbin.org/xml')
            self.fail()
        except parse_response_error.ParseResponseError:
            pass

    def test_put_against_httpbin(self):
        # https://httpbin.org/put
        formdata = dict(a=1, b=2, c=3)
        status, data = self.instance.put('http://httpbin.org/put', data=formdata)
        self.assertEqual(200, status)
        self.assertIsInstance(data, dict)
        self.assertEquals(formdata, data['json'])

    def test_delete_against_httpbin(self):
        # https://httpbin.org/delete
        formdata = dict(a=1, b=2, c=3)
        status, data = self.instance.delete('http://httpbin.org/delete', data=formdata)
        self.assertEqual(200, status)
        self.assertIsInstance(data, dict)
        self.assertEquals(formdata, data['json'])
Пример #22
0
 def __init__(self, API_key, config):
     assert isinstance(API_key, str), 'You must provide a valid API Key'
     self.API_key = API_key
     assert isinstance(config, dict)
     self.http_client = HttpClient(API_key, config, ROOT_WEATHER_API)
Пример #23
0
class TestOWMHttpUVClient(unittest.TestCase):

    __test_cache = NullCache()
    __instance = UltraVioletHttpClient('xyz', HttpClient(cache=__test_cache))

    def test_trim_to(self):
        ts = timeformatutils.to_date(1463041620)  # 2016-05-12T08:27:00Z
        self.assertEqual(self.__instance._trim_to(ts, 'minute'),
                          '2016-05-12T08:27Z')
        self.assertEqual(self.__instance._trim_to(ts, 'hour'),
                          '2016-05-12T08Z')
        self.assertEqual(self.__instance._trim_to(ts, 'day'),
                          '2016-05-12Z')
        self.assertEqual(self.__instance._trim_to(ts, 'month'),
                          '2016-05Z')
        self.assertEqual(self.__instance._trim_to(ts, 'year'),
                          '2016Z')
        self.assertRaises(ValueError, self.__instance._trim_to,
                          ts, 'abcdef')

    def test_get_uvi(self):
        # case: current UV index
        params = {'lon': 8.25, 'lat': 43.75}
        expected = {k: str(v) for k, v in params.items()}

        def mock_func(uri, params=None, headers=None):
            return 200, (uri, params)

        self.__instance._client.cacheable_get_json = mock_func

        result = self.__instance.get_uvi(params)
        self.assertEqual('http://api.openweathermap.org/data/2.5/uvi?APPID=xyz',
                         result[0])
        self.assertEqual(expected, result[1])

    def test_get_uvi_forecast(self):
        params = {'lon': 8.25, 'lat': 43.75}
        expected = {k: str(v) for k, v in params.items()}

        def mock_func(uri, params=None, headers=None):
            return 200, (uri, params)

        self.__instance._client.cacheable_get_json = mock_func

        result = self.__instance.get_uvi_forecast(params)
        self.assertEqual('http://api.openweathermap.org/data/2.5/uvi/forecast?APPID=xyz',
                         result[0])
        self.assertEqual(expected, result[1])

    def test_get_uvi_history(self):
        params = {'lon': 8.25, 'lat': 43.75, 'start': 1498049953,
                  'end': 1498481991}
        expected = {k: str(v) for k, v in params.items()}

        def mock_func(uri, params=None, headers=None):
            return 200, (uri, params)

        self.__instance._client.cacheable_get_json = mock_func

        result = self.__instance.get_uvi_history(params)
        self.assertEqual('http://api.openweathermap.org/data/2.5/uvi/history?APPID=xyz',
                         result[0])
        self.assertEqual(expected, result[1])
class TestUVClient(unittest.TestCase):

    __instance = UltraVioletHttpClient(
        'xyz', HttpClient('apikey', DEFAULT_CONFIG, 'anyurl.com'))

    def test_trim_to(self):
        ts = formatting.to_date(1463041620)  # 2016-05-12T08:27:00Z
        self.assertEqual(self.__instance._trim_to(ts, 'minute'),
                         '2016-05-12T08:27Z')
        self.assertEqual(self.__instance._trim_to(ts, 'hour'),
                         '2016-05-12T08Z')
        self.assertEqual(self.__instance._trim_to(ts, 'day'), '2016-05-12Z')
        self.assertEqual(self.__instance._trim_to(ts, 'month'), '2016-05Z')
        self.assertEqual(self.__instance._trim_to(ts, 'year'), '2016Z')
        self.assertRaises(ValueError, self.__instance._trim_to, ts, 'abcdef')

    def test_get_uvi(self):
        # case: current UV index
        params = {'lon': 8.25, 'lat': 43.75}
        expected = {k: str(v) for k, v in params.items()}

        def mock_func(uri, params=None, headers=None):
            return 200, (uri, params)

        self.__instance._client.get_json = mock_func

        result = self.__instance.get_uvi(params)
        self.assertEqual('uvi', result[0])
        self.assertEqual(expected, result[1])

    def test_get_uvi_forecast(self):
        params = {'lon': 8.25, 'lat': 43.75}
        expected = {k: str(v) for k, v in params.items()}

        def mock_func(uri, params=None, headers=None):
            return 200, (uri, params)

        self.__instance._client.get_json = mock_func

        result = self.__instance.get_uvi_forecast(params)
        self.assertEqual('uvi/forecast', result[0])
        self.assertEqual(expected, result[1])

    def test_get_uvi_history(self):
        params = {
            'lon': 8.25,
            'lat': 43.75,
            'start': 1498049953,
            'end': 1498481991
        }
        expected = {k: str(v) for k, v in params.items()}

        def mock_func(uri, params=None, headers=None):
            return 200, (uri, params)

        self.__instance._client.get_json = mock_func

        result = self.__instance.get_uvi_history(params)
        self.assertEqual('uvi/history', result[0])
        self.assertEqual(expected, result[1])

    def test_repr(self):
        print(self.__instance)
Пример #25
0
 def test_ssl_certs_verification_failure(self):
     # https://wrong.host.badssl.com does not have a valid SSL cert
     client = HttpClient(timeout=4, use_ssl=True, verify_ssl_certs=True)
     self.assertRaises(api_call_error.APIInvalidSSLCertificateError,
                       HttpClient.get_json, client,
                       'https://wrong.host.badssl.com')
Пример #26
0
 def __init__(self, API_key, config):
     assert API_key is not None, 'You must provide a valid API Key'
     self.API_key = API_key
     assert isinstance(config, dict)
     self.http_client = HttpClient(API_key, config, ROOT_GEOCODING_API_URL)
Пример #27
0
 def test_repr(self):
     print(HttpClient('apikey', DEFAULT_CONFIG, 'anyurl.com'))
Пример #28
0
 def __init__(self, API_key):
     assert API_key is not None, 'You must provide a valid API Key'
     self.API_key = API_key
     self.stations_parser = StationParser()
     self.aggregated_measurements_parser = AggregatedMeasurementParser()
     self.http_client = HttpClient()
Пример #29
0
 def __init__(self, API_key):
     assert API_key is not None, 'You must provide a valid API Key'
     self.API_key = API_key
     self.trigger_parser = TriggerParser()
     self.alert_parser = AlertParser()
     self.http_client = HttpClient()
class TestHTTPClient(unittest.TestCase):

    instance = HttpClient('fakeapikey',
                          DEFAULT_CONFIG,
                          'httpbin.org',
                          admits_subdomains=False)

    def test_get_json_against_httpbin_ok(self):
        # http://httpbin.org/ip
        status, data = self.instance.get_json('/ip')
        self.assertEqual(200, status)
        self.assertIsInstance(data, dict)

    def test_get_json_against_httpbin_status_code_ko(self):
        # http://httpbin.org/status/400
        expected_status = 400

        self.assertRaises(pyowm.commons.exceptions.APIRequestError,
                          HttpClient.get_json, self.instance,
                          'status/{}'.format(str(expected_status)))

    def test_get_json_against_httpbin_parse_error(self):
        # http://httpbin.org/xml
        try:
            status, data = self.instance.get_json('xml')
            self.fail()
        except pyowm.commons.exceptions.ParseAPIResponseError:
            pass

    def test_put_against_httpbin(self):
        # http://httpbin.org/put
        formdata = dict(a=1, b=2, c=3)
        status, data = self.instance.put('put', data=formdata)
        self.assertEqual(200, status)
        self.assertIsInstance(data, dict)
        self.assertEqual(formdata, data['json'])

    def test_delete_against_httpbin(self):
        # http://httpbin.org/delete
        formdata = dict(a=1, b=2, c=3)
        status, data = self.instance.delete('delete', data=formdata)
        self.assertEqual(200, status)
        self.assertIsInstance(data, dict)
        self.assertEqual(formdata, data['json'])

    def test_ssl_certs_verification_failure(self):
        # https://wrong.host.badssl.com does not have a valid SSL cert
        config = DEFAULT_CONFIG.copy()
        config['connection']['use_ssl'] = True
        config['connection']['verify_ssl_certs'] = True
        instance = HttpClient('fakeapikey',
                              config,
                              'wrong.host.badssl.com',
                              admits_subdomains=False)
        self.assertRaises(pyowm.commons.exceptions.InvalidSSLCertificateError,
                          HttpClient.get_json, instance, '')

    def test_get_png(self):
        # http://httpbin.org/image/png
        status, data = self.instance.get_png('image/png')
        self.assertIsNotNone(data)
        self.assertIsInstance(data, bytes)

    def test_get_geotiff(self):
        # https://download.osgeo.org/geotiff/samples/made_up/bogota.tif
        config = DEFAULT_CONFIG.copy()
        config['connection']['use_ssl'] = True
        instance = HttpClient('fakeapikey',
                              config,
                              'download.osgeo.org',
                              admits_subdomains=False)
        status, data = instance.get_geotiff(
            'geotiff/samples/made_up/bogota.tif')
        self.assertIsNotNone(data)
        self.assertIsInstance(data, bytes)

    def test_get_png(self):
        # http://httpbin.org/image/png
        status, data = self.instance.get_png('http://httpbin.org/image/png')
        self.assertIsNotNone(data)
        self.assertIsInstance(data, bytes)

    def test_get_geotiff(self):
        # https://download.osgeo.org/geotiff/samples/made_up/bogota.tif
        status, data = self.instance.get_geotiff(
            'https://download.osgeo.org/geotiff/samples/made_up/bogota.tif')
        self.assertIsNotNone(data)
        self.assertIsInstance(data, bytes)