Debian Codegraph @

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