From 59a04dc65db6a10a165cfb4e270c0af591ed9c66 Mon Sep 17 00:00:00 2001 From: Yuval Adam <_@yuv.al> Date: Thu, 21 Apr 2022 08:40:59 +0300 Subject: Add parse() method and add some basic unit tests --- alarmpy/alarmpy.py | 12 ++++++++---- alarmpy/tests/test_alarmpy.py | 12 +++++++++--- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/alarmpy/alarmpy.py b/alarmpy/alarmpy.py index 5182cb6..3d2b45b 100644 --- a/alarmpy/alarmpy.py +++ b/alarmpy/alarmpy.py @@ -103,7 +103,8 @@ class Alarm: def start(self): while True: try: - cities, alarm_id = self.fetch() + res = self.fetch() + cities, alarm_id = self.parse(res) self.update(cities, alarm_id) except Exception as e: # pylint: disable=broad-except self.output_error(f"Exception: {e}") @@ -120,18 +121,21 @@ class Alarm: exit(1) except requests.Timeout as e: raise Exception("HTTP request timed out") from e + + return res.content - if not res.content: + def parse(self, res): + if not res: # empty content means no alarms return [], None - if res.content == b"\xef\xbb\xbf\r\n": + if res == b"\xef\xbb\xbf\r\n": # some weird binary content that also means no alarms return [], None data = {} # To avoid warning in KeyError try: - data = json.loads(res.content[3:-2]) # strip leading and trailing bytes + data = json.loads(res[3:-2]) # strip leading and trailing bytes alarm_id = data["id"] cities = data["data"] return cities, alarm_id diff --git a/alarmpy/tests/test_alarmpy.py b/alarmpy/tests/test_alarmpy.py index 3ca635c..0b14448 100644 --- a/alarmpy/tests/test_alarmpy.py +++ b/alarmpy/tests/test_alarmpy.py @@ -1,6 +1,12 @@ from ..alarmpy import Alarm -def test_foo(): - _alarm = Alarm() - assert 1 == 1 +def test_parse(): + alarm = Alarm() + res = b'\xef\xbb\xbf{\r\n "id": "132949694460000000",\r\n "cat": "1",\r\n "title": "\xd7\x99\xd7\xa8\xd7\x99 \xd7\x98\xd7\x99\xd7\x9c\xd7\x99\xd7\x9d \xd7\x95\xd7\xa8\xd7\xa7\xd7\x98\xd7\x95\xd7\xaa",\r\n "data": [\r\n "\xd7\xa9\xd7\x93\xd7\xa8\xd7\x95\xd7\xaa, \xd7\x90\xd7\x99\xd7\x91\xd7\x99\xd7\x9d, \xd7\xa0\xd7\x99\xd7\xa8 \xd7\xa2\xd7\x9d",\r\n "\xd7\x90\xd7\xa8\xd7\x96",\r\n "\xd7\x9e\xd7\xa4\xd7\x9c\xd7\xa1\xd7\x99\xd7\x9d",\r\n "\xd7\x9e\xd7\x98\xd7\x95\xd7\x95\xd7\x97 \xd7\xa0\xd7\x99\xd7\xa8 \xd7\xa2\xd7\x9d"\r\n ],\r\n "desc": "\xd7\x94\xd7\x99\xd7\x9b\xd7\xa0\xd7\xa1\xd7\x95 \xd7\x9c\xd7\x9e\xd7\xa8\xd7\x97\xd7\x91 \xd7\x94\xd7\x9e\xd7\x95\xd7\x92\xd7\x9f"\r\n}\r\n' + assert alarm.parse(res) == (['שדרות, איבים, ניר עם', 'ארז', 'מפלסים', 'מטווח ניר עם'], '132949694460000000') + +def test_empty_parse(): + alarm = Alarm() + assert alarm.parse(None) == ([], None) + assert alarm.parse(b"") == ([], None) \ No newline at end of file -- cgit v1.3.1