Coverage for pass_import/formats/json.py: 98%

42 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-02-26 12:11 +0000

1# -*- encoding: utf-8 -*- 

2# pass import - Passwords importer swiss army knife 

3# Copyright (C) 2017-2024 Alexandre PUJOL <alexandre@pujol.io>. 

4# 

5 

6import json 

7 

8from pass_import.core import Cap, register_detecters 

9from pass_import.detecter import Formatter 

10from pass_import.manager import PasswordImporter 

11 

12 

13class JSON(Formatter, PasswordImporter): 

14 """Base class for JSON based importers.""" 

15 cap = Cap.FORMAT | Cap.IMPORT 

16 format = 'json' 

17 json_header = {} 

18 jsons = None 

19 

20 # Import methods 

21 

22 def parse(self): 

23 """Parse JSON based file.""" 

24 raise NotImplementedError() 

25 

26 # Format recognition methods 

27 

28 def is_format(self) -> bool: 

29 """Return True if the file is a JSON file.""" 

30 try: 

31 self.jsons = json.loads(self.file.read()) 

32 except (json.decoder.JSONDecodeError, UnicodeDecodeError): 

33 return False 

34 return True 

35 

36 def _ensureheader(self, data, header) -> bool: 

37 """Ensure the data is in the header format. 

38 

39 :return bool: 

40 True or False either the header match the json data. 

41 

42 """ 

43 # pylint: disable=too-many-return-statements 

44 if isinstance(header, type): 

45 if data is not None and not isinstance(data, header): 

46 return False 

47 return True 

48 

49 if isinstance(data, list): 

50 if not isinstance(header, list): 

51 return False 

52 for item in data: 

53 if not self._ensureheader(item, header[0]): 

54 return False 

55 return True 

56 

57 if isinstance(data, dict): 

58 if not isinstance(header, dict): 

59 return False 

60 for key, value in header.items(): 

61 if key not in data or not self._ensureheader(data[key], value): 

62 return False 

63 return True 

64 

65 return data == header 

66 

67 def checkheader(self, header, only=False) -> bool: 

68 """Ensure the file header is the same than the pm header.""" 

69 return self._ensureheader(self.jsons, header) 

70 

71 @classmethod 

72 def header(cls): 

73 """Header for JSON file.""" 

74 return cls.json_header 

75 

76 

77register_detecters(JSON)