Debian Codegraph @

tests/test_plugin_kook.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 # Disable logging for a cleaner testing output
29 from json import dumps
30 import logging
31 import os
32 from unittest import mock
33 from urllib.parse import urlparse
34
35 from helpers import AppriseURLTester
36 import pytest
37 import requests
38
39 from apprise import Apprise, AppriseAttachment, NotifyFormat
40 from apprise.exception import AppriseImproperlyConfigured
41 from apprise.plugins.kook import (
42 KookMode,
43 NotifyKook,
44 )
45
46 logging.disable(logging.CRITICAL)
47
48 # Attachment directory
49 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
50
51 # A realistic-looking fake bot token (no slashes so URL interpolation works)
52 BOT_TOKEN = "MTQ3OTE5MTA3MzQ1ODE4OTQ0ABC123XYZ"
53
54 # Fake channel / user IDs (numeric snowflakes)
55 CHANNEL_ID = "1234567890"
56 CHANNEL_ID2 = "9876543210"
57 USER_ID = "5555555555"
58
59 # Fake webhook key
60 WEBHOOK_KEY = "abc123webhookkey"
61
62
63 TEST_URLS = (
64 ##
65 # Invalid cases
66 ##
67 # Missing token
68 (
69 "kook://",
70 {
71 "instance": AppriseImproperlyConfigured,
72 },
73 ),
74 # Invalid mode
75 (
76 f"kook://{BOT_TOKEN}/?mode=invalid",
77 {
78 "instance": AppriseImproperlyConfigured,
79 },
80 ),
81 ##
82 # Webhook mode
83 ##
84 # Basic webhook
85 (
86 f"kook://{WEBHOOK_KEY}/?mode=webhook",
87 {
88 "instance": NotifyKook,
89 "privacy_url": "kook://a...y/?mode=webhook",
90 },
91 ),
92 # Webhook via ?token= override
93 (
94 f"kook://ignored/?token={WEBHOOK_KEY}&mode=webhook",
95 {
96 "instance": NotifyKook,
97 },
98 ),
99 # Webhook HTTP 500
100 (
101 f"kook://{WEBHOOK_KEY}/?mode=webhook",
102 {
103 "instance": NotifyKook,
104 "response": False,
105 "requests_response_code": requests.codes.internal_server_error,
106 },
107 ),
108 # Webhook unknown response code
109 (
110 f"kook://{WEBHOOK_KEY}/?mode=webhook",
111 {
112 "instance": NotifyKook,
113 "response": False,
114 "requests_response_code": 999,
115 },
116 ),
117 # Webhook RequestException
118 (
119 f"kook://{WEBHOOK_KEY}/?mode=webhook",
120 {
121 "instance": NotifyKook,
122 "test_requests_exceptions": True,
123 },
124 ),
125 ##
126 # Bot mode - single channel
127 # attach_response=False because _upload() needs a CDN URL in the
128 # response body; the default mock returns empty content so the CDN
129 # upload step returns None and the send returns False.
130 ##
131 (
132 f"kook://{BOT_TOKEN}/{CHANNEL_ID}",
133 {
134 "instance": NotifyKook,
135 "attach_response": False,
136 },
137 ),
138 # Bot mode - multiple channels
139 (
140 f"kook://{BOT_TOKEN}/{CHANNEL_ID}/{CHANNEL_ID2}",
141 {
142 "instance": NotifyKook,
143 "attach_response": False,
144 },
145 ),
146 # Bot mode - DM target
147 (
148 f"kook://{BOT_TOKEN}/@{USER_ID}",
149 {
150 "instance": NotifyKook,
151 "attach_response": False,
152 },
153 ),
154 # Bot mode - channel + DM mixed
155 (
156 f"kook://{BOT_TOKEN}/{CHANNEL_ID}/@{USER_ID}",
157 {
158 "instance": NotifyKook,
159 "attach_response": False,
160 },
161 ),
162 # Bot mode - no targets (loads but notify() returns False)
163 (
164 f"kook://{BOT_TOKEN}",
165 {
166 "instance": NotifyKook,
167 "notify_response": False,
168 },
169 ),
170 # Bot mode via ?to=
171 (
172 f"kook://{BOT_TOKEN}/?to={CHANNEL_ID}",
173 {
174 "instance": NotifyKook,
175 "attach_response": False,
176 },
177 ),
178 # Bot mode with ?format=text (plain text delivery)
179 (
180 f"kook://{BOT_TOKEN}/{CHANNEL_ID}/?format=text",
181 {
182 "instance": NotifyKook,
183 "attach_response": False,
184 },
185 ),
186 # Bot mode HTTP 500
187 (
188 f"kook://{BOT_TOKEN}/{CHANNEL_ID}",
189 {
190 "instance": NotifyKook,
191 "response": False,
192 "requests_response_code": requests.codes.internal_server_error,
193 },
194 ),
195 # Bot mode unknown response code
196 (
197 f"kook://{BOT_TOKEN}/{CHANNEL_ID}",
198 {
199 "instance": NotifyKook,
200 "response": False,
201 "requests_response_code": 999,
202 },
203 ),
204 # Bot mode RequestException
205 (
206 f"kook://{BOT_TOKEN}/{CHANNEL_ID}",
207 {
208 "instance": NotifyKook,
209 "test_requests_exceptions": True,
210 },
211 ),
212 # Native webhook URL
213 (
214 "https://www.kookapp.cn/api/v3/incoming/nativekey123",
215 {
216 "instance": NotifyKook,
217 "privacy_url": "kook://n...3/?mode=webhook",
218 },
219 ),
220 )
221
222
223 @pytest.fixture
224 def apprise_url_tester():
225 return AppriseURLTester(tests=TEST_URLS)
226
227
228 def test_plugin_kook_urls(apprise_url_tester):
229 """Run all URL test table entries through AppriseURLTester."""
230 apprise_url_tester.run_all()
231
232
233 def test_plugin_kook_bot_mode():
234 """Verify bot-mode init, url(), url_identifier, and round-trip."""
235
236 # Single channel
237 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
238 assert obj.mode == KookMode.BOT
239 assert obj.notify_format == NotifyFormat.MARKDOWN
240 assert obj.channels == [CHANNEL_ID]
241 assert obj.dm_users == []
242 assert obj.attachment_support is True
243
244 # url_identifier must only reference connection identity, not targets
245 ident = obj.url_identifier
246 assert ident == ("kook", KookMode.BOT, BOT_TOKEN)
247
248 # Round-trip
249 url = obj.url()
250 parsed = NotifyKook.parse_url(url)
251 assert parsed is not None
252 obj2 = NotifyKook(**parsed)
253 assert obj2.url_identifier == obj.url_identifier
254 assert len(obj2.channels) == len(obj.channels)
255
256 # privacy_url should mask the token
257 purl = obj.url(privacy=True)
258 assert BOT_TOKEN not in purl
259
260 # Multiple channels
261 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID, CHANNEL_ID2])
262 assert len(obj.channels) == 2
263 url = obj.url()
264 parsed = NotifyKook.parse_url(url)
265 obj2 = NotifyKook(**parsed)
266 assert len(obj2.channels) == 2
267
268 # DM target
269 obj = NotifyKook(token=BOT_TOKEN, targets=[f"@{USER_ID}"])
270 assert obj.dm_users == [USER_ID]
271 assert obj.channels == []
272 url = obj.url()
273 parsed = NotifyKook.parse_url(url)
274 obj2 = NotifyKook(**parsed)
275 assert obj2.dm_users == [USER_ID]
276
277 # Mixed channel + DM
278 obj = NotifyKook(
279 token=BOT_TOKEN,
280 targets=[CHANNEL_ID, f"@{USER_ID}"],
281 )
282 assert len(obj.channels) == 1
283 assert len(obj.dm_users) == 1
284 url = obj.url()
285 parsed = NotifyKook.parse_url(url)
286 obj2 = NotifyKook(**parsed)
287 assert len(obj2.channels) == 1
288 assert len(obj2.dm_users) == 1
289
290 # # prefix stripped from channel
291 obj = NotifyKook(token=BOT_TOKEN, targets=[f"#{CHANNEL_ID}"])
292 assert obj.channels == [CHANNEL_ID]
293
294 # Invalid channel and DM IDs are stored in _invalid_targets and
295 # survive the round-trip
296 obj = NotifyKook(
297 token=BOT_TOKEN,
298 targets=["notanumber", "@notanumber"],
299 )
300 assert obj.channels == []
301 assert obj.dm_users == []
302 assert len(obj._invalid_targets) == 2
303 url = obj.url()
304 parsed = NotifyKook.parse_url(url)
305 obj2 = NotifyKook(**parsed)
306 assert len(obj2._invalid_targets) == 2
307
308 # No targets
309 obj = NotifyKook(token=BOT_TOKEN)
310 assert obj.channels == []
311 assert obj.dm_users == []
312
313 # ?format=text sets notify_format to TEXT; url() round-trips it
314 url = f"kook://{BOT_TOKEN}/{CHANNEL_ID}/?format=text"
315 parsed = NotifyKook.parse_url(url)
316 obj = NotifyKook(**parsed)
317 assert obj.notify_format == NotifyFormat.TEXT
318 url2 = obj.url()
319 parsed2 = NotifyKook.parse_url(url2)
320 obj2 = NotifyKook(**parsed2)
321 assert obj2.notify_format == NotifyFormat.TEXT
322
323 # Default notify_format stays MARKDOWN (kmarkdown mode)
324 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
325 assert obj.notify_format == NotifyFormat.MARKDOWN
326 url = obj.url()
327 assert "msg_type" not in url
328
329 # Default mode not emitted in URL
330 assert "mode" not in url
331
332
333 def test_plugin_kook_webhook_mode():
334 """Verify webhook-mode init, url(), and url_identifier."""
335
336 obj = NotifyKook(token=WEBHOOK_KEY, mode="webhook")
337 assert obj.mode == KookMode.WEBHOOK
338 assert obj.attachment_support is False
339 assert obj.channels == []
340 assert obj.dm_users == []
341
342 # url_identifier includes mode
343 assert obj.url_identifier == ("kook", KookMode.WEBHOOK, WEBHOOK_KEY)
344
345 # url() emits mode=webhook
346 url = obj.url()
347 assert "mode=webhook" in url
348
349 # Round-trip
350 parsed = NotifyKook.parse_url(url)
351 obj2 = NotifyKook(**parsed)
352 assert obj2.url_identifier == obj.url_identifier
353 assert obj2.mode == KookMode.WEBHOOK
354
355 # Missing token
356 with pytest.raises(AppriseImproperlyConfigured):
357 NotifyKook(token=None)
358
359 with pytest.raises(AppriseImproperlyConfigured):
360 NotifyKook(token="")
361
362
363 def test_plugin_kook_mode_invalid():
364 """An invalid mode is rejected."""
365 with pytest.raises(AppriseImproperlyConfigured):
366 NotifyKook(token=BOT_TOKEN, mode="invalid_mode")
367
368
369 def test_plugin_kook_url_parsing():
370 """Exercise parse_url edge cases."""
371
372 # ?token= query param overrides the host
373 url = f"kook://ignored/?token={BOT_TOKEN}&to={CHANNEL_ID}"
374 parsed = NotifyKook.parse_url(url)
375 assert parsed is not None
376 assert parsed["token"] == BOT_TOKEN
377 assert CHANNEL_ID in parsed["targets"]
378
379 # split_path collects multiple targets
380 url = f"kook://{BOT_TOKEN}/{CHANNEL_ID}/{CHANNEL_ID2}"
381 parsed = NotifyKook.parse_url(url)
382 assert CHANNEL_ID in parsed["targets"]
383 assert CHANNEL_ID2 in parsed["targets"]
384
385 # None input returns None
386 assert NotifyKook.parse_url(None) is None
387
388
389 def test_plugin_kook_native_url():
390 """parse_native_url accepts a full Kook webhook URL."""
391 url = "https://www.kookapp.cn/api/v3/incoming/mywebhookkey"
392 parsed = NotifyKook.parse_native_url(url)
393 assert parsed is not None
394 assert parsed["token"] == "mywebhookkey"
395 assert parsed["mode"] == KookMode.WEBHOOK
396
397 # Native URL with trailing slash
398 url = "https://www.kookapp.cn/api/v3/incoming/mywebhookkey/"
399 parsed = NotifyKook.parse_native_url(url)
400 assert parsed is not None
401 assert parsed["token"] == "mywebhookkey"
402
403 # Non-matching URL returns None
404 assert NotifyKook.parse_native_url("https://example.com/") is None
405
406
407 @mock.patch("requests.post")
408 def test_plugin_kook_webhook_send(mock_post):
409 """Webhook mode send: success, HTTP error, API error, RequestException."""
410
411 def _mk_resp(code=requests.codes.ok, api_code=0):
412 r = mock.Mock()
413 r.status_code = code
414 r.content = dumps({"code": api_code, "message": "ok"}).encode()
415 return r
416
417 # Success
418 mock_post.return_value = _mk_resp()
419 obj = NotifyKook(token=WEBHOOK_KEY, mode="webhook")
420 assert bool(obj.notify(body="hello")) is True
421 assert mock_post.call_count == 1
422
423 # Verify the endpoint URL
424 call_url = mock_post.call_args[0][0]
425 assert urlparse(call_url).hostname == "www.kookapp.cn"
426 assert "/incoming/" in call_url
427
428 # HTTP 500 -> False
429 mock_post.return_value = _mk_resp(
430 code=requests.codes.internal_server_error
431 )
432 assert bool(obj.notify(body="hello")) is False
433
434 # Unknown HTTP code -> False
435 mock_post.return_value = _mk_resp(code=999)
436 assert bool(obj.notify(body="hello")) is False
437
438 # API-level error (code != 0) -> False
439 mock_post.return_value = _mk_resp(api_code=40001)
440 assert bool(obj.notify(body="hello")) is False
441
442 # Unparseable JSON body is handled gracefully
443 r = mock.Mock()
444 r.status_code = requests.codes.ok
445 r.content = b"not-json"
446 mock_post.return_value = r
447 # code defaults to 0 -> success (unparseable treated as ok)
448 assert bool(obj.notify(body="hello")) is True
449
450 # RequestException -> False
451 mock_post.side_effect = requests.RequestException("conn error")
452 assert bool(obj.notify(body="hello")) is False
453 mock_post.side_effect = None
454
455
456 @mock.patch("requests.post")
457 def test_plugin_kook_bot_send(mock_post):
458 """Bot mode send: no targets, single channel, multiple, DM, error."""
459
460 def _ok():
461 r = mock.Mock()
462 r.status_code = requests.codes.ok
463 r.content = dumps({"code": 0}).encode()
464 return r
465
466 def _err(code=requests.codes.internal_server_error):
467 r = mock.Mock()
468 r.status_code = code
469 r.content = b""
470 return r
471
472 # No targets -> False without making a network call
473 obj = NotifyKook(token=BOT_TOKEN)
474 mock_post.reset_mock()
475 assert bool(obj.notify(body="hello")) is False
476 assert mock_post.call_count == 0
477
478 # Single channel success
479 mock_post.return_value = _ok()
480 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
481 assert bool(obj.notify(body="hello")) is True
482 assert mock_post.call_count == 1
483
484 # Verify Authorization header
485 call_kwargs = mock_post.call_args[1]
486 assert f"Bot {BOT_TOKEN}" in call_kwargs["headers"]["Authorization"]
487
488 # Multiple channels
489 mock_post.return_value = _ok()
490 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID, CHANNEL_ID2])
491 mock_post.reset_mock()
492 assert bool(obj.notify(body="hello")) is True
493 assert mock_post.call_count == 2
494
495 # DM target (uses dm_url endpoint)
496 mock_post.return_value = _ok()
497 obj = NotifyKook(token=BOT_TOKEN, targets=[f"@{USER_ID}"])
498 mock_post.reset_mock()
499 assert bool(obj.notify(body="hello")) is True
500 assert mock_post.call_count == 1
501 call_url = mock_post.call_args[0][0]
502 assert "direct-message" in call_url
503
504 # Mixed channel + DM
505 mock_post.return_value = _ok()
506 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID, f"@{USER_ID}"])
507 mock_post.reset_mock()
508 assert bool(obj.notify(body="hello")) is True
509 assert mock_post.call_count == 2
510
511 # HTTP 500 on one target -> has_error=True -> False
512 mock_post.return_value = _err()
513 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
514 assert bool(obj.notify(body="hello")) is False
515
516 # Unknown HTTP code
517 mock_post.return_value = _err(code=999)
518 assert bool(obj.notify(body="hello")) is False
519
520 # API-level error code
521 r = mock.Mock()
522 r.status_code = requests.codes.ok
523 r.content = dumps({"code": 40001, "message": "error"}).encode()
524 mock_post.return_value = r
525 assert bool(obj.notify(body="hello")) is False
526
527 # RequestException
528 mock_post.side_effect = requests.RequestException("boom")
529 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
530 assert bool(obj.notify(body="hello")) is False
531 mock_post.side_effect = None
532
533 # Partial failure: first channel fails, second would succeed,
534 # but has_error is still True so overall False
535 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID, CHANNEL_ID2])
536 mock_post.side_effect = [_err(), _ok()]
537 assert bool(obj.notify(body="hello")) is False
538 mock_post.side_effect = None
539
540 # ?format=text -> notify_format=TEXT -> Kook API type 1 in the payload
541 import json
542
543 mock_post.return_value = _ok()
544 parsed = NotifyKook.parse_url(
545 f"kook://{BOT_TOKEN}/{CHANNEL_ID}/?format=text"
546 )
547 obj = NotifyKook(**parsed)
548 mock_post.reset_mock()
549 assert bool(obj.notify(body="hello")) is True
550 payload = json.loads(mock_post.call_args[1]["data"])
551 assert payload["type"] == 1
552
553 # Default (markdown) -> notify_format=MARKDOWN -> Kook API type 9
554 mock_post.return_value = _ok()
555 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
556 mock_post.reset_mock()
557 assert bool(obj.notify(body="hello")) is True
558 payload = json.loads(mock_post.call_args[1]["data"])
559 assert payload["type"] == 9
560
561
562 @mock.patch("requests.post")
563 def test_plugin_kook_attachments_success(mock_post):
564 """Attachment upload succeeds and a follow-up message is posted."""
565
566 def _ok(cdn_url="https://img.kookapp.cn/assets/test.png"):
567 r = mock.Mock()
568 r.status_code = requests.codes.ok
569 r.content = dumps(
570 {
571 "code": 0,
572 "data": {"url": cdn_url},
573 }
574 ).encode()
575 return r
576
577 # call order: (1) text message, (2) CDN upload, (3) attach-msg POST
578 mock_post.side_effect = [_ok(), _ok(), _ok()]
579
580 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
581
582 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
583 assert bool(obj.notify(body="hello", attach=attach)) is True
584 assert mock_post.call_count == 3
585
586
587 @mock.patch("requests.post")
588 def test_plugin_kook_attachments_inaccessible(mock_post):
589 """Attachment that cannot be accessed returns False without HTTP call."""
590 mock_post.return_value = mock.Mock(
591 status_code=requests.codes.ok,
592 content=dumps({"code": 0}).encode(),
593 )
594
595 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
596
597 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
598
599 with mock.patch("os.path.isfile", return_value=False):
600 # Text message succeeds; attachment upload returns None -> False
601 assert bool(obj.notify(body="hello", attach=attach)) is False
602
603
604 @mock.patch("requests.post")
605 def test_plugin_kook_attachments_oserror(mock_post):
606 """OSError on attachment open is handled gracefully."""
607 # Text message POST returns ok
608 mock_post.return_value = mock.Mock(
609 status_code=requests.codes.ok,
610 content=dumps({"code": 0}).encode(),
611 )
612
613 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
614
615 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
616
617 with mock.patch("builtins.open", side_effect=OSError("read error")):
618 assert bool(obj.notify(body="hello", attach=attach)) is False
619
620
621 @mock.patch("requests.post")
622 def test_plugin_kook_attachments_upload_http_error(mock_post):
623 """HTTP error during CDN upload returns False."""
624 ok_resp = mock.Mock()
625 ok_resp.status_code = requests.codes.ok
626 ok_resp.content = dumps({"code": 0}).encode()
627
628 upload_err = mock.Mock()
629 upload_err.status_code = requests.codes.internal_server_error
630 upload_err.content = b""
631
632 # Text message OK, then upload fails
633 mock_post.side_effect = [ok_resp, upload_err]
634
635 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
636
637 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
638 assert bool(obj.notify(body="hello", attach=attach)) is False
639
640
641 @mock.patch("requests.post")
642 def test_plugin_kook_attachments_upload_no_url(mock_post):
643 """CDN upload returns HTTP 200 but no URL in response body -> False."""
644 ok_resp = mock.Mock()
645 ok_resp.status_code = requests.codes.ok
646 ok_resp.content = dumps({"code": 0}).encode()
647
648 no_url_resp = mock.Mock()
649 no_url_resp.status_code = requests.codes.ok
650 no_url_resp.content = dumps({"code": 0, "data": {}}).encode()
651
652 mock_post.side_effect = [ok_resp, no_url_resp]
653
654 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
655
656 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
657 assert bool(obj.notify(body="hello", attach=attach)) is False
658
659
660 @mock.patch("requests.post")
661 def test_plugin_kook_attachments_upload_request_exception(mock_post):
662 """RequestException during CDN upload returns False."""
663 ok_resp = mock.Mock()
664 ok_resp.status_code = requests.codes.ok
665 ok_resp.content = dumps({"code": 0}).encode()
666
667 mock_post.side_effect = [
668 ok_resp,
669 requests.RequestException("upload error"),
670 ]
671
672 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
673
674 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
675 assert bool(obj.notify(body="hello", attach=attach)) is False
676
677
678 @mock.patch("requests.post")
679 def test_plugin_kook_attachments_post_http_error(mock_post):
680 """HTTP error when posting attachment message returns False."""
681
682 def _ok(cdn_url="https://img.kookapp.cn/assets/test.png"):
683 r = mock.Mock()
684 r.status_code = requests.codes.ok
685 r.content = dumps(
686 {
687 "code": 0,
688 "data": {"url": cdn_url},
689 }
690 ).encode()
691 return r
692
693 err_resp = mock.Mock()
694 err_resp.status_code = requests.codes.internal_server_error
695 err_resp.content = b""
696
697 # Text message OK, CDN upload OK, attachment-message POST fails
698 mock_post.side_effect = [_ok(), _ok(), err_resp]
699
700 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
701
702 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
703 assert bool(obj.notify(body="hello", attach=attach)) is False
704
705
706 @mock.patch("requests.post")
707 def test_plugin_kook_attachments_post_request_exception(mock_post):
708 """RequestException when posting attachment message returns False."""
709
710 def _ok(cdn_url="https://img.kookapp.cn/assets/test.png"):
711 r = mock.Mock()
712 r.status_code = requests.codes.ok
713 r.content = dumps(
714 {
715 "code": 0,
716 "data": {"url": cdn_url},
717 }
718 ).encode()
719 return r
720
721 # Text message OK, CDN upload OK, attachment-message POST raises
722 mock_post.side_effect = [
723 _ok(),
724 _ok(),
725 requests.RequestException("post error"),
726 ]
727
728 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
729
730 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
731 assert bool(obj.notify(body="hello", attach=attach)) is False
732
733
734 @mock.patch("requests.post")
735 def test_plugin_kook_attachments_post_api_error(mock_post):
736 """API error in attach-message response sets has_error -> False."""
737
738 def _ok(cdn_url="https://img.kookapp.cn/assets/test.png"):
739 r = mock.Mock()
740 r.status_code = requests.codes.ok
741 r.content = dumps(
742 {
743 "code": 0,
744 "data": {"url": cdn_url},
745 }
746 ).encode()
747 return r
748
749 def _api_err():
750 r = mock.Mock()
751 r.status_code = requests.codes.ok
752 r.content = dumps({"code": 40001, "message": "forbidden"}).encode()
753 return r
754
755 # Text message OK, CDN upload OK, attach-msg POST returns API error
756 mock_post.side_effect = [_ok(), _ok(), _api_err()]
757
758 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
759
760 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
761 assert bool(obj.notify(body="hello", attach=attach)) is False
762
763
764 @mock.patch("requests.post")
765 def test_plugin_kook_attachments_image_and_file(mock_post):
766 """Image attachment uses type=2; non-image uses type=4."""
767 import json as _json
768
769 def _ok(cdn_url="https://img.kookapp.cn/assets/f"):
770 r = mock.Mock()
771 r.status_code = requests.codes.ok
772 r.content = dumps(
773 {
774 "code": 0,
775 "data": {"url": cdn_url},
776 }
777 ).encode()
778 return r
779
780 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
781
782 # Image attachment (PNG)
783 # call order: text-msg, upload, attach-msg
784 mock_post.side_effect = [_ok(), _ok(), _ok()]
785 attach_img = AppriseAttachment(
786 os.path.join(TEST_VAR_DIR, "apprise-test.png")
787 )
788 assert bool(obj.notify(body="hello", attach=attach_img)) is True
789 attach_msg_payload = _json.loads(mock_post.call_args_list[2][1]["data"])
790 assert attach_msg_payload["type"] == 2
791
792 # Non-image attachment (mp4 file)
793 mock_post.side_effect = [_ok(), _ok(), _ok()]
794 attach_file = AppriseAttachment(
795 os.path.join(TEST_VAR_DIR, "apprise-test.mp4")
796 )
797 mock_post.reset_mock()
798 mock_post.side_effect = [_ok(), _ok(), _ok()]
799 assert bool(obj.notify(body="hello", attach=attach_file)) is True
800 attach_msg_payload = _json.loads(mock_post.call_args_list[2][1]["data"])
801 assert attach_msg_payload["type"] == 4
802
803
804 @mock.patch("requests.post")
805 def test_plugin_kook_webhook_no_attachment_support(mock_post):
806 """Webhook mode ignores attachments since attachment_support=False."""
807 r = mock.Mock()
808 r.status_code = requests.codes.ok
809 r.content = dumps({"code": 0}).encode()
810 mock_post.return_value = r
811
812 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
813
814 obj = NotifyKook(token=WEBHOOK_KEY, mode="webhook")
815 assert obj.attachment_support is False
816 # Apprise framework skips attach when attachment_support=False
817 assert bool(obj.notify(body="hello", attach=attach)) is True
818 # Only one POST (the webhook message itself)
819 assert mock_post.call_count == 1
820
821
822 @mock.patch("requests.post")
823 def test_plugin_kook_invalid_json_responses(mock_post):
824 """Verify invalid JSON in API responses is handled gracefully."""
825
826 # _send_bot: API response with unparseable JSON
827 # The message POST returns 200 but with invalid JSON body; the except
828 # clause must handle it and fall back to code=0 (success).
829 r = mock.Mock()
830 r.status_code = requests.codes.ok
831 r.content = b"not-json"
832 mock_post.return_value = r
833
834 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
835 assert bool(obj.notify(body="hello")) is True
836
837 # _upload: CDN upload response with unparseable JSON
838 # Text message POST returns ok with bad JSON; CDN upload also returns ok
839 # with bad JSON. The except fires, cdn_url is None, send returns False.
840 mock_post.return_value = r # same bad JSON response for all calls
841 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
842 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
843 # Text succeeds (code defaults to 0); CDN upload has no URL -> False
844 assert bool(obj.notify(body="hello", attach=attach)) is False
845
846 # _send_bot: attach-message POST response with unparseable JSON
847 # text OK, CDN upload OK (valid cdn_url), attach-msg POST returns bad JSON;
848 # the except fires, content defaults to {}, code=0 -> treated as success.
849 def _ok_cdn():
850 resp = mock.Mock()
851 resp.status_code = requests.codes.ok
852 resp.content = dumps(
853 {"code": 0, "data": {"url": "https://cdn/f"}}
854 ).encode()
855 return resp
856
857 bad_json_resp = mock.Mock()
858 bad_json_resp.status_code = requests.codes.ok
859 bad_json_resp.content = b"not-json"
860
861 mock_post.side_effect = [_ok_cdn(), _ok_cdn(), bad_json_resp]
862 mock_post.return_value = None
863 obj = NotifyKook(token=BOT_TOKEN, targets=[CHANNEL_ID])
864 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
865 assert bool(obj.notify(body="hello", attach=attach)) is True
866 mock_post.side_effect = None
867
868
869 @mock.patch("requests.post")
870 def test_plugin_kook_apprise_integration(mock_post):
871 """Apprise().add() and notify() work for both modes."""
872 r = mock.Mock()
873 r.status_code = requests.codes.ok
874 r.content = dumps({"code": 0}).encode()
875 mock_post.return_value = r
876
877 # Bot mode
878 a = Apprise()
879 assert a.add(f"kook://{BOT_TOKEN}/{CHANNEL_ID}") is True
880 assert bool(a.notify(title="Test", body="Message")) is True
881
882 # Webhook mode
883 a = Apprise()
884 assert a.add(f"kook://{WEBHOOK_KEY}/?mode=webhook") is True
885 assert bool(a.notify(body="webhook message")) is True