From eccd08a8bcb9cbb619448ae3897ee69e0dd401bb Mon Sep 17 00:00:00 2001 From: s3lph <1375407-s3lph@users.noreply.gitlab.com> Date: Sun, 7 Aug 2022 16:02:53 +0200 Subject: [PATCH] Handle 404 error on key get api call --- multischleuder/api.py | 10 ++++++++-- multischleuder/test/test_api.py | 20 +++++++++++++++++--- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/multischleuder/api.py b/multischleuder/api.py index aef04f4..de2feab 100644 --- a/multischleuder/api.py +++ b/multischleuder/api.py @@ -3,8 +3,10 @@ from typing import List, Optional import base64 import json +import logging import os import ssl +import urllib.error import urllib.request from multischleuder.types import SchleuderKey, SchleuderList, SchleuderSubscriber @@ -129,8 +131,12 @@ class SchleuderApi: # Key Management - def get_key(self, fpr: str, schleuder: SchleuderList) -> SchleuderKey: - key = self.__request('keys/{}.json', list_id=schleuder.id, fmt=[fpr]) + def get_key(self, fpr: str, schleuder: SchleuderList) -> Optional[SchleuderKey]: + try: + key = self.__request('keys/{}.json', list_id=schleuder.id, fmt=[fpr]) + except urllib.error.HTTPError as e: + logging.exception(e) + return None return SchleuderKey.from_api(schleuder.id, **key) def post_key(self, key: SchleuderKey, schleuder: SchleuderList): diff --git a/multischleuder/test/test_api.py b/multischleuder/test/test_api.py index 8463b12..c2251be 100644 --- a/multischleuder/test/test_api.py +++ b/multischleuder/test/test_api.py @@ -1,5 +1,6 @@ import unittest +import urllib.error from datetime import datetime from unittest.mock import patch, MagicMock @@ -111,7 +112,7 @@ _KEY_RESPONSE = ''' class TestSchleuderApi(unittest.TestCase): - def _mock_api(self, mock, nokey=False): + def _mock_api(self, mock, nokey=False, error=None): m = MagicMock() m.getcode.return_value = 200 @@ -133,8 +134,14 @@ class TestSchleuderApi(unittest.TestCase): m.read = read m.__enter__.return_value = m mock.return_value = m - return SchleuderApi('https://localhost:4443', - '86cf2676d065dc902548e563ab22b57868ed2eb6') + api = SchleuderApi('https://localhost:4443', + '86cf2676d065dc902548e563ab22b57868ed2eb6') + if error is not None: + def __request(*args, **kwargs): + raise error + api._SchleuderApi__request = __request + + return api @patch('urllib.request.urlopen') def test_get_lists(self, mock): @@ -282,6 +289,13 @@ class TestSchleuderApi(unittest.TestCase): self.assertEqual(42, key.schleuder) self.assertIn('-----BEGIN PGP PUBLIC KEY BLOCK-----', key.blob) + @patch('urllib.request.urlopen') + def test_get_key_404(self, mock): + url = 'https://localhost:4443/keys/ADB9BC679FF53CC8EF66FAC39348FDAB7A7663FA.json?list_id=42' + api = self._mock_api(mock, error=urllib.error.HTTPError(url=url, code=404, msg='Not Found', hdrs={}, fp=None)) + key = api.get_key('ADB9BC679FF53CC8EF66FAC39348FDAB7A7663FA', SchleuderList(42, '', '')) + self.assertIsNone(key) + @patch('urllib.request.urlopen') def test_post_key(self, mock): api = self._mock_api(mock)