From 7d0b09d9f2d858e18e5a4280a50bffc2befc387e Mon Sep 17 00:00:00 2001 From: Fabien Piuzzi Date: Sat, 17 Feb 2018 03:48:06 +0100 Subject: [PATCH] Added more error handling for invalid data --- foobot_async/__init__.py | 31 ++++++++++++++++++++++++------- tests/test_foobot_async.py | 15 +++++++++++++++ 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/foobot_async/__init__.py b/foobot_async/__init__.py index e588a7c..ca439ab 100644 --- a/foobot_async/__init__.py +++ b/foobot_async/__init__.py @@ -138,13 +138,16 @@ def parse_data(self, response): * allpollu: `foobot index `_, unit: % """ parsed = [] - items = response['sensors'] - for datapoint in response['datapoints']: - line = {} - for index, data in enumerate(datapoint): - line[items[index]] = data - parsed.append(line) - return parsed + try: + items = response['sensors'] + for datapoint in response['datapoints']: + line = {} + for index, data in enumerate(datapoint): + line[items[index]] = data + parsed.append(line) + return parsed + except (KeyError, IndexError, TypeError): + raise FoobotClient.InvalidData() @asyncio.coroutine def _get(self, path, **kwargs): @@ -165,20 +168,34 @@ def _get(self, path, **kwargs): raise FoobotClient.ClientError(resp.text()) return (yield from resp.json()) + @property + def last_data_request(self): + return self._last_data_request + class ClientError(Exception): + """Generic Error.""" pass class AuthFailure(ClientError): + """Failed Authentication.""" pass class BadFormat(ClientError): + """Request is malformed.""" pass class ForbiddenAccess(ClientError): + """Access is prohibited.""" pass class TooManyRequests(ClientError): + """Too many requests for this time period.""" pass class InternalError(ClientError): + """Server Internal Error.""" + pass + + class InvalidData(ClientError): + """Can't parse response data.""" pass diff --git a/tests/test_foobot_async.py b/tests/test_foobot_async.py index d15274e..8991d5b 100644 --- a/tests/test_foobot_async.py +++ b/tests/test_foobot_async.py @@ -142,3 +142,18 @@ def test_get_historical_data_request(): co2 = 1178.0, voc = 325.5, allpollu= 131.19643) == resp[0] + +def test_get_bad_data_request(): + body = '''{"uuid": "1234127987696AB", + "start": 1518131274, + "end": 1518131874}''' + + with aioresponses() as mocked: + mocked.get('https://api.foobot.io/v2/device/1234127987696AB/datapoint/1518121274/1518131274/3600/', + status=200, body=body) + + with pytest.raises(FoobotClient.InvalidData): + loop.run_until_complete(client.get_historical_data("1234127987696AB", + datetime.utcfromtimestamp(1518121274), + datetime.utcfromtimestamp(1518131274), + 3600))