Coverage for gws-app/gws/lib/jsonx/_test.py: 0%

44 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-17 01:37 +0200

1"""Tests for the jsonx module.""" 

2 

3import gws 

4import gws.test.util as u 

5import gws.lib.jsonx as jsonx 

6 

7_json_pretty = """{ 

8 "additionalInfo": null, 

9 "address": { 

10 "city": "New York", 

11 "postalCode": 10021, 

12 "state": "NY", 

13 "streetAddress": "21 2nd Street" 

14 }, 

15 "ficoScore": " > 640", 

16 "height": 62.4, 

17 "name": "John Smith", 

18 "phoneNumbers": [ 

19 "212 555-1111", 

20 "212 555-2222" 

21 ], 

22 "remote": false 

23}""" 

24 

25_json = """{ 

26 "name":"John Smith", 

27 "address": { 

28 "streetAddress": "21 2nd Street", 

29 "city": "New York", 

30 "state": "NY", 

31 "postalCode": 10021 

32 }, 

33 "phoneNumbers": [ 

34 "212 555-1111", 

35 "212 555-2222" 

36 ], 

37 "additionalInfo": null, 

38 "remote": false, 

39 "height": 62.4, 

40 "ficoScore": " > 640" 

41}""" 

42 

43_jsondict = { 

44 "name": "John Smith", 

45 "address": { 

46 "streetAddress": "21 2nd Street", 

47 "city": "New York", 

48 "state": "NY", 

49 "postalCode": 10021 

50 }, 

51 "phoneNumbers": [ 

52 "212 555-1111", 

53 "212 555-2222" 

54 ], 

55 "additionalInfo": None, 

56 "remote": False, 

57 "height": 62.4, 

58 "ficoScore": " > 640" 

59} 

60 

61 

62def test_form_path(tmp_path): 

63 path_json = tmp_path / "test.json" 

64 

65 with open(str(path_json), "w") as f: 

66 f.write(_json) 

67 

68 j = jsonx.from_path(str(path_json)) 

69 assert j == _jsondict 

70 

71 

72def test_from_string(): 

73 j = jsonx.from_string(_json) 

74 assert j == _jsondict 

75 

76 

77def test_to_path(tmp_path): 

78 path_json = tmp_path / "test.json" 

79 

80 jsonx.to_path(str(path_json), _jsondict) 

81 

82 with open(str(path_json), 'r') as f: 

83 assert f.read().replace(" ", "").replace("\n", "") == _json.replace(" ", "").replace("\n", "") 

84 

85 

86def test_to_string(): 

87 s = jsonx.to_string(_jsondict) 

88 assert s.replace(" ", "").replace("\n", "") == _json.replace(" ", "").replace("\n", "") 

89 

90 

91def test_to_string_ascii(): 

92 jsondict = {"FÖÖ": "BÄR"} 

93 s = jsonx.to_string(jsondict, ensure_ascii=False) 

94 assert s == '{"FÖÖ": "BÄR"}' 

95 

96 

97def test_to_string_ascii_escaped(): 

98 jsondict = {"FÖÖ": "BÄR"} 

99 s = jsonx.to_string(jsondict) 

100 assert s == '{"F\\u00d6\\u00d6": "B\\u00c4R"}' 

101 

102 

103def test_to_string_default(): 

104 def default(x): 

105 return {"foo": "bar"} 

106 

107 class CustomObject: 

108 def __init__(self, name): 

109 self.name = name 

110 

111 custom = CustomObject("Custom") 

112 jsondict = {"foo": custom} 

113 json_string = jsonx.to_string(jsondict, default=default) 

114 assert json_string == '{"foo": {"foo": "bar"}}' 

115 

116 

117def test_to_pretty_string(): 

118 s = jsonx.to_pretty_string(_jsondict) 

119 assert s == _json_pretty