Debian Codegraph @

tests/test_plugin_google_chat.py

raw
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 from json import loads
29
30 # Disable logging for a cleaner testing output
31 import logging
32 from unittest import mock
33
34 from helpers import AppriseURLTester
35 import pytest
36 import requests
37
38 from apprise import Apprise, NotifyFormat, NotifyType
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.google_chat import NotifyGoogleChat
41
42 logging.disable(logging.CRITICAL)
43
44 # Our Testing URLs
45 apprise_url_tests = (
46 (
47 "gchat://",
48 {
49 "instance": AppriseImproperlyConfigured,
50 },
51 ),
52 (
53 "gchat://:@/",
54 {
55 "instance": AppriseImproperlyConfigured,
56 },
57 ),
58 # Workspace, but not Key or Token
59 (
60 "gchat://workspace",
61 {
62 "instance": AppriseImproperlyConfigured,
63 },
64 ),
65 # Workspace and key, but no Token
66 (
67 "gchat://workspace/key/",
68 {
69 "instance": AppriseImproperlyConfigured,
70 },
71 ),
72 # Credentials are good
73 (
74 "gchat://workspace/key/token",
75 {
76 "instance": NotifyGoogleChat,
77 "privacy_url": "gchat://w...e/k...y/t...n",
78 },
79 ),
80 # Test arguments
81 (
82 "gchat://?workspace=ws&key=mykey&token=mytoken",
83 {
84 "instance": NotifyGoogleChat,
85 "privacy_url": "gchat://w...s/m...y/m...n",
86 },
87 ),
88 (
89 "gchat://?workspace=ws&key=mykey&token=mytoken&thread=abc123",
90 {
91 # Test our thread key
92 "instance": NotifyGoogleChat,
93 "privacy_url": "gchat://w...s/m...y/m...n/a...3",
94 },
95 ),
96 (
97 "gchat://?workspace=ws&key=mykey&token=mytoken&threadKey=abc345",
98 {
99 # Test our thread key
100 "instance": NotifyGoogleChat,
101 "privacy_url": "gchat://w...s/m...y/m...n/a...5",
102 },
103 ),
104 # Google Native Webhook URL
105 (
106 (
107 "https://chat.googleapis.com/v1/spaces/myworkspace/messages"
108 "?key=mykey&token=mytoken"
109 ),
110 {
111 "instance": NotifyGoogleChat,
112 "privacy_url": "gchat://m...e/m...y/m...n",
113 },
114 ),
115 (
116 (
117 "https://chat.googleapis.com/v1/spaces/myworkspace/messages"
118 "?key=mykey&token=mytoken&threadKey=mythreadkey"
119 ),
120 {
121 "instance": NotifyGoogleChat,
122 "privacy_url": "gchat://m...e/m...y/m...n/m...y",
123 },
124 ),
125 (
126 "gchat://workspace/key/token",
127 {
128 "instance": NotifyGoogleChat,
129 # force a failure
130 "response": False,
131 "requests_response_code": requests.codes.internal_server_error,
132 },
133 ),
134 (
135 "gchat://workspace/key/token",
136 {
137 "instance": NotifyGoogleChat,
138 # throw a bizarre code forcing us to fail to look it up
139 "response": False,
140 "requests_response_code": 999,
141 },
142 ),
143 (
144 "gchat://workspace/key/token",
145 {
146 "instance": NotifyGoogleChat,
147 # Throws a series of i/o exceptions with this flag
148 # is set and tests that we gracefully handle them
149 "test_requests_exceptions": True,
150 },
151 ),
152 )
153
154
155 def test_plugin_google_chat_urls():
156 """NotifyGoogleChat() Apprise URLs."""
157
158 # Run our general tests
159 AppriseURLTester(tests=apprise_url_tests).run_all()
160
161
162 @mock.patch("requests.post")
163 def test_plugin_google_chat_general(mock_post):
164 """NotifyGoogleChat() General Checks."""
165
166 # Initialize some generic (but valid) tokens
167 workspace = "ws"
168 key = "key"
169 threadkey = "threadkey"
170 token = "token"
171
172 # Prepare Mock
173 mock_post.return_value = requests.Request()
174 mock_post.return_value.status_code = requests.codes.ok
175
176 # Test our messaging
177 obj = Apprise.instantiate(f"gchat://{workspace}/{key}/{token}")
178 assert isinstance(obj, NotifyGoogleChat)
179 assert (
180 bool(
181 obj.notify(
182 body="test body", title="title", notify_type=NotifyType.INFO
183 )
184 )
185 is True
186 )
187
188 # Test our call count
189 assert mock_post.call_count == 1
190 assert (
191 mock_post.call_args_list[0][0][0]
192 == "https://chat.googleapis.com/v1/spaces/ws/messages"
193 )
194 params = mock_post.call_args_list[0][1]["params"]
195 assert params.get("token") == token
196 assert params.get("key") == key
197 assert "messageReplyOption" not in params
198 payload = loads(mock_post.call_args_list[0][1]["data"])
199 assert "thread" not in payload
200 assert payload["text"] == "title\r\ntest body"
201
202 mock_post.reset_mock()
203
204 # Test our messaging with the thread_key
205 obj = Apprise.instantiate(f"gchat://{workspace}/{key}/{token}/{threadkey}")
206 assert isinstance(obj, NotifyGoogleChat)
207 assert (
208 bool(
209 obj.notify(
210 body="test body", title="title", notify_type=NotifyType.INFO
211 )
212 )
213 is True
214 )
215
216 # Test our call count
217 assert mock_post.call_count == 1
218 assert (
219 mock_post.call_args_list[0][0][0]
220 == "https://chat.googleapis.com/v1/spaces/ws/messages"
221 )
222 params = mock_post.call_args_list[0][1]["params"]
223 assert params.get("token") == token
224 assert params.get("key") == key
225 assert (
226 params.get("messageReplyOption")
227 == "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
228 )
229 payload = loads(mock_post.call_args_list[0][1]["data"])
230 assert "thread" in payload
231 assert payload["text"] == "title\r\ntest body"
232 assert payload["thread"].get("thread_key") == threadkey
233
234
235 def test_plugin_google_chat_edge_case():
236 """NotifyGoogleChat() Edge Cases."""
237 with pytest.raises(AppriseImproperlyConfigured):
238 NotifyGoogleChat("workspace", "webhook", "token", thread_key=object())
239
240
241 @mock.patch("requests.post")
242 def test_plugin_google_chat_html_to_markdown_hardening(mock_post):
243 """Test edge cases in the CommonMark-to-Google-Chat dialect
244 adaptation."""
245
246 mock_post.return_value = requests.Request()
247 mock_post.return_value.status_code = requests.codes.ok
248 mock_post.return_value.content = b"{}"
249 mock_post.return_value.text = "{}"
250
251 def notify(body):
252 """Send one HTML body through the configured Google Chat plugin."""
253 aobj = Apprise()
254 assert aobj.add("gchat://workspace/key/token")
255 assert (
256 bool(aobj.notify(body=body, body_format=NotifyFormat.HTML)) is True
257 )
258 payload = loads(mock_post.call_args_list[-1][1]["data"])
259 mock_post.reset_mock()
260 return payload["text"]
261
262 # Convert CommonMark emphasis to Google Chat delimiters.
263 assert notify("<b>hello</b> <i>world</i>") == "*hello* _world_"
264
265 # A CommonMark link ("[text](<url>)", html_to_markdown's output) must
266 # arrive as Chat's own "<url|text>" syntax.
267 assert (
268 notify('<a href="https://example.com/x">click here</a>')
269 == "<https://example.com/x|click here>"
270 )
271
272 # '&'/'<'/'>' need entity escaping, since Chat's own <...> link/mention
273 # syntax reserves them.
274 assert notify("<p>2 &lt; 3 &amp; 4</p>") == "2 &lt; 3 &amp; 4"
275
276 # Escape Chat control characters in link destinations.
277 assert (
278 notify('<a href="https://e/x>TAIL">click</a>')
279 == "<https://e/x&gt;TAIL|click>"
280 )
281
282 # Percent-encode Chat's URL-label separator inside destinations.
283 assert (
284 notify('<a href="https://e/x|evil">click</a>')
285 == "<https://e/x%7Cevil|click>"
286 )
287
288 # Entity-escape Chat controls inside code spans.
289 assert notify("<code>a &lt; b &amp; c</code>") == "`a &lt; b &amp; c`"
290
291 # Adjacent nested tags flatten to CommonMark italic around bold.
292 assert notify("<b><i>x</i></b>") == "_*x*_"
293
294 # Non-adjacent nesting and sibling spans are unaffected.
295 assert notify("<b>bold <i>italic</i> still bold</b>") == (
296 "*bold _italic_ still bold*"
297 )
298 # Adjacent bold tags retain their ambiguous middle markers as literals.
299 assert notify("<b>A</b><b>B</b>") == "*A****B*"
300
301 # Direct Google Chat Markdown remains unchanged.
302 aobj = Apprise()
303 assert aobj.add("gchat://workspace/key/token")
304 assert bool(aobj.notify(body="*already* chat-bound markdown")) is True
305 payload = loads(mock_post.call_args_list[-1][1]["data"])
306 assert payload["text"] == "*already* chat-bound markdown"
307 mock_post.reset_mock()
308
309 # Preserve unmatched backticks as literal text.
310 assert (
311 NotifyGoogleChat._commonmark_to_google_chat("text ``unterminated")
312 == "text ``unterminated"
313 )
314
315 # Preserve an opener with no closer.
316 assert NotifyGoogleChat._commonmark_to_google_chat("****x") == "****x"
317
318 # A backslash-escaped '>' outside of link syntax still needs entity
319 # escaping, the same as a bare one.
320 f = NotifyGoogleChat._commonmark_to_google_chat
321 assert f("\\>literal") == "&gt;literal"
322
323 # Drop CommonMark escapes that Google Chat does not use.
324 assert f("\\!text") == "!text"
325
326 # A three-backtick content line cannot close a four-backtick fence.
327 # Preserve indentation until the matching four-backtick closing fence.
328 assert f("````\n``` nested\n indented\nlast\n````") == (
329 "````\n``` nested\n indented\nlast\n````"
330 )
331
332 # Preserve escapes so Chat formatting characters remain literal.
333 assert f("\\*text\\*") == "\\*text\\*"
334 assert f("\\_text\\_") == "\\_text\\_"
335 assert f("\\~text\\~") == "\\~text\\~"
336 assert f("\\`text\\`") == "\\`text\\`"
337
338 # Preserve an incomplete link as literal text.
339 assert f("[text](<https://example.com/unterminated") == (
340 "[text](<https://example.com/unterminated"
341 )
342
343 # Preserve unmatched markers in a complete body.
344 assert f("**unterminated") == "**unterminated"
345 assert f("**") == "**"
346
347 # User-provided Private Use text must not collide with placeholders.
348 marker = chr(0xE000)
349 attack = f"before {marker}0{marker} after"
350 assert f(attack) == attack
351 assert f(f"*bold* {attack}") == f"_bold_ {attack}"
352
353 # Google Chat renders the merged title heading as bold.
354 aobj = Apprise()
355 assert aobj.add("gchat://workspace/key/token")
356 assert (
357 bool(
358 aobj.notify(
359 body="<b>hello</b>",
360 title="My Title",
361 body_format=NotifyFormat.HTML,
362 )
363 )
364 is True
365 )
366 payload = loads(mock_post.call_args_list[-1][1]["data"])
367 assert payload["text"] == "*My Title*\n*hello*"
368 mock_post.reset_mock()
369
370 # Title that reduces to an empty string after stripping leading heading
371 # and list characters (html_to_markdown converts " - " to "-").
372 # The heading is skipped and the title field is cleared regardless.
373 assert (
374 bool(
375 aobj.notify(
376 body="<b>hello</b>",
377 title=" - ",
378 body_format=NotifyFormat.HTML,
379 )
380 )
381 is True
382 )
383 payload = loads(mock_post.call_args_list[-1][1]["data"])
384 assert payload["text"] == "*hello*"
385
386
387 @mock.patch("requests.post")
388 def test_plugin_google_chat_markdown_dialect_conversion(
389 mock_post,
390 ):
391 """Declared Markdown gets Google Chat dialect completion."""
392
393 mock_post.return_value = requests.Request()
394 mock_post.return_value.status_code = requests.codes.ok
395 mock_post.return_value.content = b"{}"
396
397 aobj = Apprise()
398 assert aobj.add("gchat://workspace/key/token")
399
400 assert (
401 bool(
402 aobj.notify(
403 body="*bold* [click here](<https://example.com/x>)",
404 body_format=NotifyFormat.MARKDOWN,
405 )
406 )
407 is True
408 )
409 payload = loads(mock_post.call_args_list[-1][1]["data"])
410 assert payload["text"] == "_bold_ <https://example.com/x|click here>"
411 mock_post.reset_mock()
412
413 # Directly verify the hook leaves unsupported formats unchanged.
414 inst = aobj[0]
415 body = "*bold*"
416 assert inst.dialect_convert(body, NotifyFormat.HTML) == body
417
418
419 def test_plugin_google_chat_bare_link_and_autolink_dialect():
420 """Bare-paren links and standalone autolinks convert safely."""
421
422 # Bare destinations convert without treating URL punctuation as emphasis.
423 assert (
424 NotifyGoogleChat._commonmark_to_google_chat(
425 "[click here](https://a*b)"
426 )
427 == "<https://a*b|click here>"
428 )
429
430 # Complete autolinks become Chat's unlabeled anchors.
431 assert (
432 NotifyGoogleChat._commonmark_to_google_chat("see <https://a*b> now")
433 == "see <https://a*b> now"
434 )
435
436 # A "<" that never forms a valid scheme is passed through literally.
437 assert NotifyGoogleChat._commonmark_to_google_chat("a < b") == "a < b"
438
439 # A destination containing whitespace remains literal.
440 assert (
441 NotifyGoogleChat._commonmark_to_google_chat("[label](has space)")
442 == "[label](has space)"
443 )
444
445 # An unfinished destination also remains literal.
446 assert (
447 NotifyGoogleChat._commonmark_to_google_chat("[label](unterminated")
448 == "[label](unterminated"
449 )
450
451
452 def test_plugin_google_chat_nested_angle_link():
453 """Keep the outer link when a nested angle link is invalid."""
454
455 # Retire only the invalid inner label so the outer link still converts.
456 body = "[OUTER [INNER](<badstuff)](https://example.com)"
457 assert NotifyGoogleChat._commonmark_to_google_chat(body) == (
458 "<https://example.com|OUTER [INNER](<badstuff)>"
459 )
460
461
462 def test_plugin_google_chat_stray_bracket_retires_opener():
463 """A "]" with no "(" must retire its "[" instead of leaving it
464 pending for a later, unrelated link to reuse."""
465
466 # No "(" ever follows the first "]", so "[label]" is not a link and
467 # must not be spliced into the later, unrelated "](https://...)".
468 body = "[label] and ](https://example.com) end"
469 assert (
470 NotifyGoogleChat._commonmark_to_google_chat(body)
471 == "[label] and ](https://example.com) end"
472 )
473
474
475 @mock.patch("requests.post")
476 def test_plugin_google_chat_dialect_overflow(mock_post):
477 """Apply the selected overflow mode after Chat escaping expands text."""
478
479 mock_post.return_value = requests.Request()
480 mock_post.return_value.status_code = requests.codes.ok
481 mock_post.return_value.content = b"{}"
482 mock_post.return_value.text = "{}"
483
484 def notify(overflow):
485 aobj = Apprise()
486 assert aobj.add(f"gchat://workspace/key/token?overflow={overflow}")
487 # Entity escaping makes this body exceed the post-conversion limit.
488 assert aobj.notify(
489 body="& " * 10000, body_format=NotifyFormat.MARKDOWN
490 )
491 texts = [loads(c[1]["data"])["text"] for c in mock_post.call_args_list]
492 mock_post.reset_mock()
493 return texts
494
495 # UPSTREAM: exactly one message, sent oversized rather than split.
496 texts = notify("upstream")
497 assert len(texts) == 1
498 assert len(texts[0]) > NotifyGoogleChat.body_maxlen
499
500 # TRUNCATE: exactly one message, clipped to fit.
501 texts = notify("truncate")
502 assert len(texts) == 1
503 assert len(texts[0]) <= NotifyGoogleChat.body_maxlen
504
505 # SPLIT: as many messages as needed, each one within the limit.
506 texts = notify("split")
507 assert len(texts) > 1
508 for text in texts:
509 assert len(text) <= NotifyGoogleChat.body_maxlen