Coverage for src/ipyvizzu/json.py: 100%

24 statements  

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

1"""A module for working JavaScript code in json convertible objects.""" 

2 

3import json 

4from typing import Any, Optional 

5import uuid 

6 

7 

8class RawJavaScript: 

9 """A class for representing raw JavaScript code.""" 

10 

11 # pylint: disable=too-few-public-methods 

12 

13 def __init__(self, raw: Optional[str]): 

14 """ 

15 RawJavaScript constructor. 

16 

17 It stores raw JavaScript code as a string. 

18 

19 Args: 

20 raw: JavaScript code as `str`. 

21 """ 

22 

23 self._raw = raw 

24 

25 @property 

26 def raw(self) -> Optional[str]: 

27 """ 

28 A property for storing raw JavaScript code as a string. 

29 

30 Returns: 

31 Raw JavaScript code as `str`. 

32 """ 

33 

34 return self._raw 

35 

36 

37class RawJavaScriptEncoder(json.JSONEncoder): 

38 """ 

39 A class for representing a custom json encoder, 

40 it can encode objects that contain 

41 [RawJavaScript][ipyvizzu.json.RawJavaScript] values. 

42 """ 

43 

44 def __init__(self, *args, **kwargs): 

45 """ 

46 RawJavaScriptEncoder constructor. 

47 

48 It extends [JSONEncoder][json.JSONEncoder] with 

49 an instance variable (`_raw_replacements`). 

50 The `_raw_replacements` dictionary stores the `uuids` and 

51 JavaScript codes of the [RawJavaScript][ipyvizzu.json.RawJavaScript] objects. 

52 """ 

53 

54 json.JSONEncoder.__init__(self, *args, **kwargs) 

55 self._raw_replacements = {} 

56 

57 def default(self, o: Any): 

58 """ 

59 Overrides [JSONEncoder.default][json.JSONEncoder.default] method. 

60 It replaces [RawJavaScript][ipyvizzu.json.RawJavaScript] object with `uuid` and 

61 it stores raw JavaScript code with `uuid` key in the `_raw_replacements` dictionary. 

62 """ 

63 

64 if isinstance(o, RawJavaScript): 

65 key = uuid.uuid4().hex 

66 self._raw_replacements[key] = o.raw 

67 return key 

68 return json.JSONEncoder.default(self, o) 

69 

70 def encode(self, o: Any): 

71 """ 

72 Overrides [JSONEncoder.encode][json.JSONEncoder.encode] method. 

73 It replaces `uuids` with raw JavaScript code without apostrophes. 

74 """ 

75 

76 result = json.JSONEncoder.encode(self, o) 

77 for key, val in self._raw_replacements.items(): 

78 result = result.replace(f'"{key}"', val) 

79 return result