Debian Codegraph @

tests/test_apprise_jsonencoder.py

raw symbols SCIP
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 import base64
29 from datetime import datetime, timezone
30 import json
31
32 # Disable logging for a cleaner testing output
33 import logging
34 import sys
35 from unittest import mock
36
37 import pytest
38
39 from apprise import Apprise
40 from apprise.common import AWARE_DATE_ISO_FORMAT, NAIVE_DATE_ISO_FORMAT
41 from apprise.locale import LazyTranslation
42 from apprise.utils.json import AppriseJSONEncoder
43
44 logging.disable(logging.CRITICAL)
45
46 # Ensure we don't create .pyc files for these tests
47 sys.dont_write_bytecode = True
48
49
50 def test_apprise_json_encoder_datetime_naive():
51 "AppriseJSONEncoder: naive datetime serialization"
52
53 dt = datetime(2026, 3, 11, 12, 30, 45, 123456)
54 result = json.dumps(dt, cls=AppriseJSONEncoder)
55 assert result == f'"{dt.strftime(NAIVE_DATE_ISO_FORMAT)}"'
56 assert "T" in result
57 # Naive datetimes have no timezone offset
58 assert result.endswith('"')
59 assert "+00:00" not in result
60
61
62 def test_apprise_json_encoder_datetime_aware():
63 "AppriseJSONEncoder: aware datetime serialization"
64
65 dt = datetime(2026, 3, 11, 12, 30, 45, 123456, tzinfo=timezone.utc)
66 result = json.dumps(dt, cls=AppriseJSONEncoder)
67 assert result == f'"{dt.strftime(AWARE_DATE_ISO_FORMAT)}"'
68 assert "T" in result
69 # Aware datetimes include the timezone offset
70 assert "+0000" in result
71
72
73 def test_apprise_json_encoder_bytes():
74 "AppriseJSONEncoder: bytes serialization"
75
76 data = b"hello world"
77 result = json.dumps(data, cls=AppriseJSONEncoder)
78 expected = base64.b64encode(data).decode("utf-8")
79 assert result == f'"{expected}"'
80
81 # Empty bytes
82 result = json.dumps(b"", cls=AppriseJSONEncoder)
83 assert result == '""'
84
85 # Binary data
86 data = bytes(range(256))
87 result = json.dumps(data, cls=AppriseJSONEncoder)
88 expected = base64.b64encode(data).decode("utf-8")
89 assert result == f'"{expected}"'
90
91
92 def test_apprise_json_encoder_set():
93 "AppriseJSONEncoder: set serialization"
94
95 data = {1, 2, 3}
96 result = json.loads(json.dumps(data, cls=AppriseJSONEncoder))
97 assert isinstance(result, list)
98 assert sorted(result) == [1, 2, 3]
99
100 # Empty set
101 result = json.loads(json.dumps(set(), cls=AppriseJSONEncoder))
102 assert result == []
103
104
105 def test_apprise_json_encoder_frozenset():
106 "AppriseJSONEncoder: frozenset serialization"
107
108 data = frozenset([4, 5, 6])
109 result = json.loads(json.dumps(data, cls=AppriseJSONEncoder))
110 assert isinstance(result, list)
111 assert sorted(result) == [4, 5, 6]
112
113 # Empty frozenset
114 result = json.loads(json.dumps(frozenset(), cls=AppriseJSONEncoder))
115 assert result == []
116
117
118 def test_apprise_json_encoder_tuple():
119 "AppriseJSONEncoder: tuple serialization"
120
121 data = (7, 8, 9)
122 result = json.loads(json.dumps(data, cls=AppriseJSONEncoder))
123 assert isinstance(result, list)
124 assert result == [7, 8, 9]
125
126 # Empty tuple
127 result = json.loads(json.dumps((), cls=AppriseJSONEncoder))
128 assert result == []
129
130
131 def test_apprise_json_encoder_lazy_translation():
132 "AppriseJSONEncoder: LazyTranslation serialization"
133
134 lt = LazyTranslation(text="hello world")
135 result = json.dumps(lt, cls=AppriseJSONEncoder)
136 assert result == '"hello world"'
137
138 # A translation with no gettext mapping returns the original text
139 lt = LazyTranslation(text="no-translation-key-xyz")
140 result = json.dumps(lt, cls=AppriseJSONEncoder)
141 assert result == '"no-translation-key-xyz"'
142
143
144 def test_apprise_json_encoder_unsupported_type():
145 "AppriseJSONEncoder: unsupported type raises TypeError"
146
147 class CustomObj:
148 pass
149
150 with pytest.raises(TypeError):
151 json.dumps(CustomObj(), cls=AppriseJSONEncoder)
152
153
154 def test_apprise_json_encoder_nested():
155 "AppriseJSONEncoder: nested structures with mixed types"
156
157 data = {
158 "when": datetime(2026, 3, 11, 0, 0, 0, tzinfo=timezone.utc),
159 "payload": b"binary data",
160 "tags": {"alpha", "beta"},
161 "label": LazyTranslation(text="nested"),
162 "coords": (1.0, 2.0),
163 }
164 result = json.loads(json.dumps(data, cls=AppriseJSONEncoder))
165
166 assert isinstance(result["when"], str)
167 assert "T" in result["when"]
168 assert isinstance(result["payload"], str)
169 assert result["payload"] == base64.b64encode(b"binary data").decode(
170 "utf-8"
171 )
172 assert isinstance(result["tags"], list)
173 assert sorted(result["tags"]) == ["alpha", "beta"]
174 assert result["label"] == "nested"
175 assert result["coords"] == [1.0, 2.0]
176
177
178 def test_apprise_json_method_no_path():
179 "Apprise.json(): returns compact JSON string when no path is given"
180
181 apobj = Apprise()
182
183 # Default call — compact output (indent=None), no newlines
184 result = apobj.json()
185 assert isinstance(result, str)
186 parsed = json.loads(result)
187 assert isinstance(parsed, dict)
188 # Compact: no newlines in the output
189 assert "\n" not in result
190
191 # show_requirements and show_disabled flags are forwarded to details()
192 result_req = apobj.json(show_requirements=True)
193 assert isinstance(result_req, str)
194 assert json.loads(result_req)
195
196 result_dis = apobj.json(show_disabled=True)
197 assert isinstance(result_dis, str)
198 assert json.loads(result_dis)
199
200
201 def test_apprise_json_method_indent():
202 "Apprise.json(): indent > 0 produces pretty-printed output with newlines"
203
204 apobj = Apprise()
205
206 result = apobj.json(indent=4)
207 assert isinstance(result, str)
208 # Pretty-printed output contains newlines
209 assert "\n" in result
210 assert json.loads(result)
211
212
213 def test_apprise_json_method_with_path(tmpdir):
214 "Apprise.json(): writes JSON to file and returns True"
215
216 apobj = Apprise()
217 output = tmpdir.join("details.json")
218
219 assert apobj.json(path=str(output)) is True
220 assert output.check(file=True)
221
222 content = output.read()
223 parsed = json.loads(content)
224 assert isinstance(parsed, dict)
225
226 # Compact by default — no newlines
227 assert "\n" not in content
228
229
230 def test_apprise_json_method_with_path_and_indent(tmpdir):
231 "Apprise.json(): writes pretty-printed JSON to file when indent is set"
232
233 apobj = Apprise()
234 output = tmpdir.join("details_pretty.json")
235
236 assert apobj.json(path=str(output), indent=2) is True
237 content = output.read()
238 assert "\n" in content
239 assert json.loads(content)
240
241
242 def test_apprise_json_method_write_failure(tmpdir):
243 "Apprise.json(): returns False when json.dump raises OSError"
244
245 apobj = Apprise()
246 output = tmpdir.join("fail.json")
247
248 with mock.patch(
249 "apprise.apprise.json.dump", side_effect=OSError("disk full")
250 ):
251 assert apobj.json(path=str(output)) is False
252
253
254 def test_apprise_json_method_write_eoferror(tmpdir):
255 "Apprise.json(): returns False when json.dump raises EOFError"
256
257 apobj = Apprise()
258 output = tmpdir.join("eof.json")
259
260 with mock.patch("apprise.apprise.json.dump", side_effect=EOFError):
261 assert apobj.json(path=str(output)) is False