Coverage for src/dirschema/json/handler.py: 100%

2 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-12-07 09:34 +0000

1"""Interface for custom validation handlers.""" 

2 

3from abc import ABC 

4from typing import IO, Any, Dict, List 

5 

6 

7class ValidationHandler(ABC): # we don't use @abstractmethod on purpose # noqa: B024 

8 """Interface for custom validators that can be registered via entrypoints. 

9 

10 Only one of validate or validate_json may be implemented. 

11 

12 These can be used instead of JSON Schemas inside a dirschema like this: 

13 

14 `validMeta: "v#ENTRYPOINT://any args for validator, e.g. schema name"` 

15 """ 

16 

17 def __init__(self, args: str): 

18 """Store passed arguments in instance.""" 

19 self.args = args 

20 

21 @property 

22 def _for_json(self) -> bool: 

23 """Return whether this handler is for JSON (i.e. overrides validate_json).""" 

24 return type(self).validate_json != ValidationHandler.validate_json 

25 

26 def validate(self, data) -> Dict[str, List[str]]: 

27 """Run validation on passed metadata object.""" 

28 if self._for_json: 

29 return self.validate_json(data, self.args) 

30 else: 

31 return self.validate_raw(data, self.args) 

32 

33 # ---- 

34 

35 @classmethod 

36 def validate_raw(cls, data: IO[bytes], args: str) -> Dict[str, List[str]]: 

37 """Perform custom validation on passed raw binary stream. 

38 

39 This can be used to implement validators for files that are not JSON 

40 or not parsable as JSON by the adapter used in combination with the handler. 

41 

42 Args: 

43 data: Binary data stream 

44 args: String following the entry-point prefix, i.e. 

45 when used as `v#ENTRYPOINT://a` the `args` value will be "a". 

46 

47 Returns: 

48 The output is a dict mapping from paths (JSON Pointers) inside the 

49 object to respective collected error messages. 

50 

51 If there are no errors, an empty dict is returned. 

52 """ 

53 raise NotImplementedError 

54 

55 @classmethod 

56 def validate_json(cls, data: Any, args: str) -> Dict[str, List[str]]: 

57 """Perform custom validation on passed JSON dict. 

58 

59 Args: 

60 data: Valid JSON dict loaded by a dirschema adapter. 

61 args: String following the entry-point prefix, i.e. 

62 when used as `v#ENTRYPOINT://a` the `args` value will be "a". 

63 

64 Returns: 

65 The output is a dict mapping from paths (JSON Pointers) inside the 

66 object to respective collected error messages. 

67 

68 If there are no errors, an empty dict is returned. 

69 """ 

70 raise NotImplementedError