|
13 | 13 | import re |
14 | 14 | import warnings |
15 | 15 | from collections import defaultdict |
16 | | -from typing import Any, Dict, Iterable, Optional, Sequence, Union |
| 16 | +from typing import Any, Dict, Iterable, Optional, Sequence, Union, Tuple |
17 | 17 | from pkg_resources import resource_filename |
18 | 18 |
|
19 | 19 | import intelmq.lib.exceptions as exceptions |
@@ -186,8 +186,9 @@ def is_valid(self, key: str, value: str, sanitize: bool = True) -> bool: |
186 | 186 | intelmq.lib.exceptions.InvalidKey: if given key is invalid. |
187 | 187 |
|
188 | 188 | """ |
189 | | - if not self.__is_valid_key(key): |
190 | | - raise exceptions.InvalidKey(key) |
| 189 | + key_validation = self.__is_valid_key(key) |
| 190 | + if not key_validation[0]: |
| 191 | + raise exceptions.InvalidKey(key, additional_text=key_validation[1]) |
191 | 192 |
|
192 | 193 | if value is None or value in ["", "-", "N/A"]: |
193 | 194 | return False |
@@ -243,8 +244,9 @@ def add(self, key: str, value: str, sanitize: bool = True, |
243 | 244 | del self[key] |
244 | 245 | return |
245 | 246 |
|
246 | | - if not self.__is_valid_key(key): |
247 | | - raise exceptions.InvalidKey(key) |
| 247 | + key_validation = self.__is_valid_key(key) |
| 248 | + if not key_validation[0]: |
| 249 | + raise exceptions.InvalidKey(key, additional_text=key_validation[1]) |
248 | 250 |
|
249 | 251 | try: |
250 | 252 | if value in ignore: |
@@ -330,16 +332,16 @@ def unserialize(message_string: str): |
330 | 332 | message = json.loads(message_string) |
331 | 333 | return message |
332 | 334 |
|
333 | | - def __is_valid_key(self, key: str): |
| 335 | + def __is_valid_key(self, key: str) -> Tuple[bool, str]: |
334 | 336 | try: |
335 | 337 | class_name, subitem = self.__get_type_config(key) |
336 | 338 | except KeyError: |
337 | | - return False |
| 339 | + return False, 'This key is not allowed by the harmonization configuration' |
338 | 340 | if key in self.harmonization_config or key == '__type': |
339 | | - return True |
| 341 | + return True, None |
340 | 342 | if subitem: |
341 | | - return HARMONIZATION_KEY_FORMAT.match(key) |
342 | | - return False |
| 343 | + return HARMONIZATION_KEY_FORMAT.match(key), f'Does not match regular expression {HARMONIZATION_KEY_FORMAT.pattern}' |
| 344 | + return False, 'This key is not allowed by the harmonization configuration' |
343 | 345 |
|
344 | 346 | def __is_valid_value(self, key: str, value: str): |
345 | 347 | if key == '__type': |
@@ -569,7 +571,7 @@ def __init__(self, message: Union[dict, tuple] = (), auto: bool = False, |
569 | 571 | if isinstance(message, Event): |
570 | 572 | super().__init__({}, auto, harmonization) |
571 | 573 | for key, value in message.items(): |
572 | | - if self._Message__is_valid_key(key): |
| 574 | + if self._Message__is_valid_key(key)[0]: |
573 | 575 | self.add(key, value, sanitize=False) |
574 | 576 | else: |
575 | 577 | super().__init__(message, auto, harmonization) |
|
0 commit comments