Created
February 27, 2017 09:24
-
-
Save onjin/c907d83b6e06381e3232da924e65c752 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
from collections import namedtuple | |
import requests | |
import logging | |
import json | |
import enum | |
class ApiInteraction(enum.Enum): | |
SUCCESS = 1 | |
ERROR = 2 | |
FAILURE = 3 | |
ApiResponse = namedtuple('ApiResponse', 'status,payload') | |
def hit_endpoint(url: str) -> ApiResponse: | |
try: | |
response = requests.get(url) | |
payload = response.json() | |
except json.decoder.JSONDecodeError as e: | |
logging.error('could not decode json from {}'.format(url)) | |
logging.info(e, exc_info=True) | |
return ApiResponse(ApiInteraction.ERROR, None) | |
except Exception as e: | |
logging.error('Something bad happend trying to reach {}'.format(url)) | |
logging.info(e, exc_info=True) | |
return ApiResponse(ApiInteraction.FAILURE, None) | |
else: | |
return ApiResponse(ApiInteraction.SUCCESS, payload) | |
ApiResponse.from_url = hit_endpoint | |
def test_endpoint_response(): | |
url = 'http://httpbin.org/headers' | |
response = ApiResponse.from_url(url) | |
assert response.status == ApiInteraction.SUCCESS | |
assert response.status == hit_endpoint(url).status | |
assert response.payload is not None | |
url = 'http://twitter.com' | |
response = ApiResponse.from_url(url) | |
assert response.status == ApiInteraction.ERROR | |
assert response.status == hit_endpoint(url).status | |
assert response.payload is None | |
url = 'foo' | |
response = ApiResponse.from_url(url) | |
assert response.status == ApiInteraction.FAILURE | |
assert response.status == hit_endpoint(url).status | |
assert response.payload is None | |
if __name__ == "__main__": | |
test_endpoint_response() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment