Debian Codegraph @

tests/test_plugin_google_chat.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 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.plugins.google_chat import NotifyGoogleChat
40
41 logging.disable(logging.CRITICAL)
42
43 # Our Testing URLs
44 apprise_url_tests = (
45 (
46 "gchat://",
47 {
48 "instance": TypeError,
49 },
50 ),
51 (
52 "gchat://:@/",
53 {
54 "instance": TypeError,
55 },
56 ),
57 # Workspace, but not Key or Token
58 (
59 "gchat://workspace",
60 {
61 "instance": TypeError,
62 },
63 ),
64 # Workspace and key, but no Token
65 (
66 "gchat://workspace/key/",
67 {
68 "instance": TypeError,
69 },
70 ),
71 # Credentials are good
72 (
73 "gchat://workspace/key/token",
74 {
75 "instance": NotifyGoogleChat,
76 "privacy_url": "gchat://w...e/k...y/t...n",
77 },
78 ),
79 # Test arguments
80 (
81 "gchat://?workspace=ws&key=mykey&token=mytoken",
82 {
83 "instance": NotifyGoogleChat,
84 "privacy_url": "gchat://w...s/m...y/m...n",
85 },
86 ),
87 (
88 "gchat://?workspace=ws&key=mykey&token=mytoken&thread=abc123",
89 {
90 # Test our thread key
91 "instance": NotifyGoogleChat,
92 "privacy_url": "gchat://w...s/m...y/m...n/a...3",
93 },
94 ),
95 (
96 "gchat://?workspace=ws&key=mykey&token=mytoken&threadKey=abc345",
97 {
98 # Test our thread key
99 "instance": NotifyGoogleChat,
100 "privacy_url": "gchat://w...s/m...y/m...n/a...5",
101 },
102 ),
103 # Google Native Webhook URL
104 (
105 (
106 "https://chat.googleapis.com/v1/spaces/myworkspace/messages"
107 "?key=mykey&token=mytoken"
108 ),
109 {
110 "instance": NotifyGoogleChat,
111 "privacy_url": "gchat://m...e/m...y/m...n",
112 },
113 ),
114 (
115 (
116 "https://chat.googleapis.com/v1/spaces/myworkspace/messages"
117 "?key=mykey&token=mytoken&threadKey=mythreadkey"
118 ),
119 {
120 "instance": NotifyGoogleChat,
121 "privacy_url": "gchat://m...e/m...y/m...n/m...y",
122 },
123 ),
124 (
125 "gchat://workspace/key/token",
126 {
127 "instance": NotifyGoogleChat,
128 # force a failure
129 "response": False,
130 "requests_response_code": requests.codes.internal_server_error,
131 },
132 ),
133 (
134 "gchat://workspace/key/token",
135 {
136 "instance": NotifyGoogleChat,
137 # throw a bizarre code forcing us to fail to look it up
138 "response": False,
139 "requests_response_code": 999,
140 },
141 ),
142 (
143 "gchat://workspace/key/token",
144 {
145 "instance": NotifyGoogleChat,
146 # Throws a series of i/o exceptions with this flag
147 # is set and tests that we gracefully handle them
148 "test_requests_exceptions": True,
149 },
150 ),
151 )
152
153
154 def test_plugin_google_chat_urls():
155 """NotifyGoogleChat() Apprise URLs."""
156
157 # Run our general tests
158 AppriseURLTester(tests=apprise_url_tests).run_all()
159
160
161 @mock.patch("requests.post")
162 def test_plugin_google_chat_general(mock_post):
163 """NotifyGoogleChat() General Checks."""
164
165 # Initialize some generic (but valid) tokens
166 workspace = "ws"
167 key = "key"
168 threadkey = "threadkey"
169 token = "token"
170
171 # Prepare Mock
172 mock_post.return_value = requests.Request()
173 mock_post.return_value.status_code = requests.codes.ok
174
175 # Test our messaging
176 obj = Apprise.instantiate(f"gchat://{workspace}/{key}/{token}")
177 assert isinstance(obj, NotifyGoogleChat)
178 assert (
179 obj.notify(
180 body="test body", title="title", notify_type=NotifyType.INFO
181 )
182 is True
183 )
184
185 # Test our call count
186 assert mock_post.call_count == 1
187 assert (
188 mock_post.call_args_list[0][0][0]
189 == "https://chat.googleapis.com/v1/spaces/ws/messages"
190 )
191 params = mock_post.call_args_list[0][1]["params"]
192 assert params.get("token") == token
193 assert params.get("key") == key
194 assert "messageReplyOption" not in params
195 payload = loads(mock_post.call_args_list[0][1]["data"])
196 assert "thread" not in payload
197 assert payload["text"] == "title\r\ntest body"
198
199 mock_post.reset_mock()
200
201 # Test our messaging with the thread_key
202 obj = Apprise.instantiate(f"gchat://{workspace}/{key}/{token}/{threadkey}")
203 assert isinstance(obj, NotifyGoogleChat)
204 assert (
205 obj.notify(
206 body="test body", title="title", notify_type=NotifyType.INFO
207 )
208 is True
209 )
210
211 # Test our call count
212 assert mock_post.call_count == 1
213 assert (
214 mock_post.call_args_list[0][0][0]
215 == "https://chat.googleapis.com/v1/spaces/ws/messages"
216 )
217 params = mock_post.call_args_list[0][1]["params"]
218 assert params.get("token") == token
219 assert params.get("key") == key
220 assert (
221 params.get("messageReplyOption")
222 == "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
223 )
224 payload = loads(mock_post.call_args_list[0][1]["data"])
225 assert "thread" in payload
226 assert payload["text"] == "title\r\ntest body"
227 assert payload["thread"].get("thread_key") == threadkey
228
229
230 def test_plugin_google_chat_edge_case():
231 """NotifyGoogleChat() Edge Cases."""
232 with pytest.raises(TypeError):
233 NotifyGoogleChat("workspace", "webhook", "token", thread_key=object())
234
235
236 @mock.patch("requests.post")
237 def test_plugin_google_chat_html_to_markdown_hardening(mock_post):
238 """Test edge cases in the CommonMark-to-Google-Chat dialect
239 adaptation."""
240
241 mock_post.return_value = requests.Request()
242 mock_post.return_value.status_code = requests.codes.ok
243 mock_post.return_value.content = b"{}"
244 mock_post.return_value.text = "{}"
245
246 def notify(body):
247 aobj = Apprise()
248 assert aobj.add("gchat://workspace/key/token")
249 assert aobj.notify(body=body, body_format=NotifyFormat.HTML) is True
250 payload = loads(mock_post.call_args_list[-1][1]["data"])
251 mock_post.reset_mock()
252 return payload["text"]
253
254 # Convert CommonMark emphasis to Google Chat delimiters.
255 assert notify("<b>hello</b> <i>world</i>") == "*hello* _world_"
256
257 # A CommonMark link ("[text](<url>)", html_to_markdown's output) must
258 # arrive as Chat's own "<url|text>" syntax.
259 assert (
260 notify('<a href="https://example.com/x">click here</a>')
261 == "<https://example.com/x|click here>"
262 )
263
264 # '&'/'<'/'>' need entity escaping, since Chat's own <...> link/mention
265 # syntax reserves them.
266 assert notify("<p>2 &lt; 3 &amp; 4</p>") == "2 &lt; 3 &amp; 4"
267
268 # Escape Chat control characters in link destinations.
269 assert (
270 notify('<a href="https://e/x>TAIL">click</a>')
271 == "<https://e/x&gt;TAIL|click>"
272 )
273
274 # Percent-encode Chat's URL-label separator inside destinations.
275 assert (
276 notify('<a href="https://e/x|evil">click</a>')
277 == "<https://e/x%7Cevil|click>"
278 )
279
280 # Entity-escape Chat controls inside code spans.
281 assert notify("<code>a &lt; b &amp; c</code>") == "`a &lt; b &amp; c`"
282
283 # Preserve adjacent nested emphasis.
284 assert notify("<b><i>x</i></b>") == "*_x_*"
285
286 # Non-adjacent nesting and sibling spans are unaffected.
287 assert notify("<b>bold <i>italic</i> still bold</b>") == (
288 "*bold _italic_ still bold*"
289 )
290 assert notify("<b>A</b><b>B</b>") == "*A**B*"
291
292 # Direct Google Chat Markdown remains unchanged.
293 aobj = Apprise()
294 assert aobj.add("gchat://workspace/key/token")
295 assert aobj.notify(body="*already* chat-bound markdown") is True
296 payload = loads(mock_post.call_args_list[-1][1]["data"])
297 assert payload["text"] == "*already* chat-bound markdown"
298 mock_post.reset_mock()
299
300 # Preserve unmatched backticks as literal text.
301 assert (
302 NotifyGoogleChat._commonmark_to_google_chat("text ``unterminated")
303 == "text ``unterminated"
304 )
305
306 # Collapse empty entities without affecting following content.
307 assert NotifyGoogleChat._commonmark_to_google_chat("****x") == "x"
308
309 # A backslash-escaped '>' outside of link syntax still needs entity
310 # escaping, the same as a bare one.
311 f = NotifyGoogleChat._commonmark_to_google_chat
312 assert f("\\>literal") == "&gt;literal"
313
314 # Drop CommonMark escapes that Google Chat does not use.
315 assert f("\\!text") == "!text"
316
317 # A three-backtick content line cannot close a four-backtick fence.
318 # Preserve indentation until the matching four-backtick closing fence.
319 assert f("````\n``` nested\n indented\nlast\n````") == (
320 "````\n``` nested\n indented\nlast\n````"
321 )
322
323 # Preserve escapes so Chat formatting characters remain literal.
324 assert f("\\*text\\*") == "\\*text\\*"
325 assert f("\\_text\\_") == "\\_text\\_"
326 assert f("\\~text\\~") == "\\~text\\~"
327 assert f("\\`text\\`") == "\\`text\\`"
328
329 # Preserve an incomplete link as literal text.
330 assert f("[text](<https://example.com/unterminated") == (
331 "[text](<https://example.com/unterminated"
332 )
333
334 # An emphasis span still open at the end of the string is force-closed
335 # rather than left dangling, so the result is valid on its own.
336 assert f("**unterminated") == "*unterminated*"
337
338 # Collapse an empty, unterminated emphasis span.
339 assert f("**") == ""
340
341 # HTML body with a title: title is merged into the body as a heading
342 # before the Chat dialect conversion runs (covers _build_send_calls
343 # title-merge branch).
344 aobj = Apprise()
345 assert aobj.add("gchat://workspace/key/token")
346 assert (
347 aobj.notify(
348 body="<b>hello</b>",
349 title="My Title",
350 body_format=NotifyFormat.HTML,
351 )
352 is True
353 )
354 payload = loads(mock_post.call_args_list[-1][1]["data"])
355 assert payload["text"] == "# My Title\n*hello*"
356 mock_post.reset_mock()
357
358 # Title that reduces to an empty string after stripping leading heading
359 # and list characters (html_to_markdown converts " - " to "-").
360 # The heading is skipped and the title field is cleared regardless.
361 assert (
362 aobj.notify(
363 body="<b>hello</b>",
364 title=" - ",
365 body_format=NotifyFormat.HTML,
366 )
367 is True
368 )
369 payload = loads(mock_post.call_args_list[-1][1]["data"])
370 assert payload["text"] == "*hello*"
371 mock_post.reset_mock()