Debian Codegraph @

tests/test_plugin_pushplus.py

raw symbols SCIP
1 #
2 # BSD 2-Clause License
3 #
4 # Apprise - Push Notification Library.
5 # Copyright (c) 2026, Chris Caron <[email protected]>
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright notice,
11 # this list of conditions and the following disclaimer.
12 #
13 # 2. Redistributions in binary form must reproduce the above copyright notice,
14 # this list of conditions and the following disclaimer in the documentation
15 # and/or other materials provided with the distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
28
29 # Disable logging for a cleaner testing output
30 from json import dumps, loads
31 import logging
32 from unittest import mock
33
34 from helpers import AppriseURLTester
35 import requests
36
37 from apprise import Apprise
38 from apprise.common import NotifyFormat
39 from apprise.plugins.pushplus import (
40 PUSHPLUS_CHANNEL_DEFAULT,
41 PUSHPLUS_CHANNELS,
42 PUSHPLUS_FORMAT_MAP,
43 NotifyPushplus,
44 PushPlusChannel,
45 )
46
47 logging.disable(logging.CRITICAL)
48
49 # A 32-character token used throughout the tests (minimum valid length)
50 GOOD_TOKEN = "abc123def456ghi789jkl012mno345pq"
51
52 # A 64-character token (upper boundary of the allowed length range)
53 LONG_TOKEN = "a" * 64
54
55 # PushPlus always returns HTTP 200; success/failure lives in the JSON body
56 GOOD_RESPONSE = dumps({"code": 200, "msg": "ok", "data": "msgid"})
57 BAD_RESPONSE = dumps({"code": 907, "msg": "Token does not exist."})
58
59 # Our Testing URLs
60 apprise_url_tests = (
61 # ----------------------------------------------------------------
62 # Invalid / missing token cases
63 # ----------------------------------------------------------------
64 (
65 "pushplus://",
66 {
67 # Empty token must raise
68 "instance": TypeError,
69 },
70 ),
71 (
72 "pushplus://short",
73 {
74 # Token too short (fewer than 32 characters)
75 "instance": TypeError,
76 },
77 ),
78 (
79 "pushplus://invalid!chars00000000000000000000000000000",
80 {
81 # Token contains characters not allowed by the regex
82 "instance": TypeError,
83 },
84 ),
85 # ----------------------------------------------------------------
86 # Valid token -- basic personal notification (no targets)
87 # ----------------------------------------------------------------
88 (
89 "pushplus://{}".format(GOOD_TOKEN),
90 {
91 "instance": NotifyPushplus,
92 # Privacy URL must mask the token
93 "privacy_url": "pushplus://****/",
94 "requests_response_text": GOOD_RESPONSE,
95 },
96 ),
97 # Token supplied as a query parameter instead of the URL host
98 (
99 "pushplus://?token={}".format(GOOD_TOKEN),
100 {
101 "instance": NotifyPushplus,
102 "privacy_url": "pushplus://****/",
103 "requests_response_text": GOOD_RESPONSE,
104 },
105 ),
106 # 64-character (maximum-length) token
107 (
108 "pushplus://{}".format(LONG_TOKEN),
109 {
110 "instance": NotifyPushplus,
111 "requests_response_text": GOOD_RESPONSE,
112 },
113 ),
114 # ----------------------------------------------------------------
115 # Group topic variations
116 # ----------------------------------------------------------------
117 # Single topic in the URL path (no prefix required)
118 (
119 "pushplus://{}/mygroup".format(GOOD_TOKEN),
120 {
121 "instance": NotifyPushplus,
122 "privacy_url": "pushplus://****/mygroup/",
123 "requests_response_text": GOOD_RESPONSE,
124 },
125 ),
126 # Two topics in the path -- two API calls are made
127 (
128 "pushplus://{}/group1/group2".format(GOOD_TOKEN),
129 {
130 "instance": NotifyPushplus,
131 "requests_response_text": GOOD_RESPONSE,
132 },
133 ),
134 # Topic supplied via the backward-compatible ?topic= parameter
135 (
136 "pushplus://{}/?topic=mygroup".format(GOOD_TOKEN),
137 {
138 "instance": NotifyPushplus,
139 "requests_response_text": GOOD_RESPONSE,
140 },
141 ),
142 # Topic supplied via the ?to= convenience alias
143 (
144 "pushplus://{}/?to=mygroup".format(GOOD_TOKEN),
145 {
146 "instance": NotifyPushplus,
147 "requests_response_text": GOOD_RESPONSE,
148 },
149 ),
150 # Invalid topic characters are silently moved to invalid_targets;
151 # the object still instantiates and sends a personal notification
152 (
153 "pushplus://{}/bad!topic".format(GOOD_TOKEN),
154 {
155 "instance": NotifyPushplus,
156 "requests_response_text": GOOD_RESPONSE,
157 },
158 ),
159 # ----------------------------------------------------------------
160 # Delivery channel via ?channel= query parameter
161 # ----------------------------------------------------------------
162 (
163 "pushplus://{}?channel=mail".format(GOOD_TOKEN),
164 {
165 "instance": NotifyPushplus,
166 "requests_response_text": GOOD_RESPONSE,
167 },
168 ),
169 (
170 "pushplus://{}?channel=sms".format(GOOD_TOKEN),
171 {
172 "instance": NotifyPushplus,
173 "requests_response_text": GOOD_RESPONSE,
174 },
175 ),
176 (
177 "pushplus://{}?channel=cp".format(GOOD_TOKEN),
178 {
179 "instance": NotifyPushplus,
180 "requests_response_text": GOOD_RESPONSE,
181 },
182 ),
183 # wecom is a friendly alias that maps to the "cp" API channel
184 (
185 "pushplus://{}?channel=wecom".format(GOOD_TOKEN),
186 {
187 "instance": NotifyPushplus,
188 "requests_response_text": GOOD_RESPONSE,
189 },
190 ),
191 # mode= is a synonym for channel=
192 (
193 "pushplus://{}?mode=mail".format(GOOD_TOKEN),
194 {
195 "instance": NotifyPushplus,
196 "requests_response_text": GOOD_RESPONSE,
197 },
198 ),
199 # ----------------------------------------------------------------
200 # Schema alias that auto-sets the delivery channel
201 # ----------------------------------------------------------------
202 # wecom:// auto-sets channel=cp (WeCom / Enterprise WeChat)
203 (
204 "wecom://{}".format(GOOD_TOKEN),
205 {
206 "instance": NotifyPushplus,
207 "requests_response_text": GOOD_RESPONSE,
208 },
209 ),
210 # ----------------------------------------------------------------
211 # Webhook channel with a named endpoint -- both input forms accepted
212 # ----------------------------------------------------------------
213 (
214 "pushplus://{}?channel=webhook&name=myhook".format(GOOD_TOKEN),
215 {
216 "instance": NotifyPushplus,
217 # url() emits the compact schema://name@token form
218 "privacy_url": "pushplus://myhook@",
219 "requests_response_text": GOOD_RESPONSE,
220 },
221 ),
222 # schema://name@token form -- channel=webhook is implied
223 (
224 "pushplus://myhook@{}".format(GOOD_TOKEN),
225 {
226 "instance": NotifyPushplus,
227 "privacy_url": "pushplus://myhook@",
228 "requests_response_text": GOOD_RESPONSE,
229 },
230 ),
231 # ----------------------------------------------------------------
232 # Native PushPlus API URL (parse_native_url support)
233 # ----------------------------------------------------------------
234 (
235 "https://www.pushplus.plus/send?token={}".format(GOOD_TOKEN),
236 {
237 "instance": NotifyPushplus,
238 "requests_response_text": GOOD_RESPONSE,
239 },
240 ),
241 # ----------------------------------------------------------------
242 # API application-level failure (HTTP 200 but JSON code != 200)
243 # ----------------------------------------------------------------
244 (
245 "pushplus://{}".format(GOOD_TOKEN),
246 {
247 "instance": NotifyPushplus,
248 "response": False,
249 "requests_response_text": BAD_RESPONSE,
250 },
251 ),
252 # Unparsable JSON body is treated as a failure
253 (
254 "pushplus://{}".format(GOOD_TOKEN),
255 {
256 "instance": NotifyPushplus,
257 "response": False,
258 "requests_response_text": "{bad json",
259 },
260 ),
261 # None body is treated as a failure
262 (
263 "pushplus://{}".format(GOOD_TOKEN),
264 {
265 "instance": NotifyPushplus,
266 "response": False,
267 "requests_response_text": None,
268 },
269 ),
270 # ----------------------------------------------------------------
271 # HTTP-level failures
272 # ----------------------------------------------------------------
273 (
274 "pushplus://{}".format(GOOD_TOKEN),
275 {
276 "instance": NotifyPushplus,
277 "response": False,
278 "requests_response_code": requests.codes.internal_server_error,
279 },
280 ),
281 (
282 "pushplus://{}".format(GOOD_TOKEN),
283 {
284 "instance": NotifyPushplus,
285 "response": False,
286 "requests_response_code": 999,
287 },
288 ),
289 # ----------------------------------------------------------------
290 # Connection / socket exceptions
291 # ----------------------------------------------------------------
292 (
293 "pushplus://{}".format(GOOD_TOKEN),
294 {
295 "instance": NotifyPushplus,
296 "test_requests_exceptions": True,
297 },
298 ),
299 )
300
301
302 def test_plugin_pushplus_urls():
303 """NotifyPushplus() Apprise URL test suite."""
304 AppriseURLTester(tests=apprise_url_tests).run_all()
305
306
307 def test_plugin_pushplus_init():
308 """NotifyPushplus() initialisation and parameter handling."""
309
310 # Minimal valid instantiation -- no targets
311 obj = NotifyPushplus(token=GOOD_TOKEN)
312 assert obj.token == GOOD_TOKEN
313 assert obj.topics == []
314 assert obj.channel == PUSHPLUS_CHANNEL_DEFAULT
315 assert obj.webhook is None
316 assert obj.invalid_targets == []
317
318 # Single group topic via targets list (no prefix required)
319 obj = NotifyPushplus(token=GOOD_TOKEN, targets=["mygroup"])
320 assert obj.topics == ["mygroup"]
321 assert obj.channel == PUSHPLUS_CHANNEL_DEFAULT
322
323 # Multiple group topics
324 obj = NotifyPushplus(
325 token=GOOD_TOKEN, targets=["group1", "group2", "group3"]
326 )
327 assert obj.topics == ["group1", "group2", "group3"]
328
329 # Explicit channel via channel= argument
330 obj = NotifyPushplus(token=GOOD_TOKEN, channel="mail")
331 assert obj.channel == PushPlusChannel.MAIL
332
333 # wecom friendly alias normalises to the "cp" API value
334 obj = NotifyPushplus(token=GOOD_TOKEN, channel="wecom")
335 assert obj.channel == PushPlusChannel.WECOM
336 assert obj.channel == "cp"
337
338 # cp is the canonical API value (same result as wecom)
339 obj = NotifyPushplus(token=GOOD_TOKEN, channel="cp")
340 assert obj.channel == "cp"
341
342 # Channel is case-insensitive
343 obj = NotifyPushplus(token=GOOD_TOKEN, channel="MAIL")
344 assert obj.channel == PushPlusChannel.MAIL
345
346 # Invalid channel raises TypeError
347 import pytest
348
349 with pytest.raises(TypeError):
350 NotifyPushplus(token=GOOD_TOKEN, channel="invalid_channel")
351
352 # Invalid target (bad characters) goes to invalid_targets
353 obj = NotifyPushplus(token=GOOD_TOKEN, targets=["bad!target"])
354 assert obj.topics == []
355 assert obj.invalid_targets == ["bad!target"]
356
357 # Invalid token raises TypeError
358 with pytest.raises(TypeError):
359 NotifyPushplus(token="short")
360
361 with pytest.raises(TypeError):
362 NotifyPushplus(token="bad!token" + "0" * 30)
363
364 # Webhook value stored as None when falsy
365 obj = NotifyPushplus(token=GOOD_TOKEN, webhook="")
366 assert obj.webhook is None
367
368 # Webhook value stored when truthy
369 obj = NotifyPushplus(
370 token=GOOD_TOKEN,
371 channel="webhook",
372 webhook="myhook",
373 )
374 assert obj.webhook == "myhook"
375 assert obj.channel == PushPlusChannel.WEBHOOK
376
377
378 def test_plugin_pushplus_schema_aliases():
379 """NotifyPushplus() wecom:// schema alias."""
380
381 # wecom:// schema sets channel=cp (WeCom API value)
382 result = NotifyPushplus.parse_url("wecom://{}".format(GOOD_TOKEN))
383 assert result is not None
384 obj = NotifyPushplus(**result)
385 assert obj.channel == PushPlusChannel.WECOM
386 assert obj.channel == "cp"
387
388 # An explicit channel= overrides the schema-implied channel
389 result = NotifyPushplus.parse_url(
390 "wecom://{}?channel=mail".format(GOOD_TOKEN)
391 )
392 assert result is not None
393 obj = NotifyPushplus(**result)
394 assert obj.channel == PushPlusChannel.MAIL
395
396
397 def test_plugin_pushplus_all_channels():
398 """NotifyPushplus() accepts every documented API channel value."""
399
400 for ch in PUSHPLUS_CHANNELS:
401 # Each channel must initialise without raising
402 obj = NotifyPushplus(token=GOOD_TOKEN, channel=ch)
403 assert obj.channel == ch
404
405 # Channel matching must be case-insensitive
406 obj2 = NotifyPushplus(token=GOOD_TOKEN, channel=ch.upper())
407 assert obj2.channel == ch
408
409
410 def test_plugin_pushplus_url():
411 """NotifyPushplus() url() output and round-trip fidelity."""
412
413 # Personal notification URL -- no topics in path, default channel omitted
414 obj = NotifyPushplus(token=GOOD_TOKEN)
415 url = obj.url()
416 assert url.startswith("pushplus://")
417 # Token appears in plain text
418 assert GOOD_TOKEN in url
419 # No topic path segment
420 assert "/mygroup" not in url
421 # Default channel is omitted from params
422 assert "channel=" not in url
423
424 # Privacy URL must mask the token
425 priv = obj.url(privacy=True)
426 assert GOOD_TOKEN not in priv
427 assert "****" in priv
428
429 # Group topic URL -- topic appears in the path
430 obj = NotifyPushplus(token=GOOD_TOKEN, targets=["mygroup"])
431 url = obj.url()
432 assert "/mygroup/" in url
433 priv = obj.url(privacy=True)
434 assert "/mygroup/" in priv
435 assert GOOD_TOKEN not in priv
436
437 # Multiple topics all appear in the path
438 obj = NotifyPushplus(token=GOOD_TOKEN, targets=["grp1", "grp2"])
439 url = obj.url()
440 assert "grp1" in url
441 assert "grp2" in url
442
443 # Non-default channel appears as ?channel= query parameter
444 obj = NotifyPushplus(token=GOOD_TOKEN, channel="mail")
445 url = obj.url()
446 assert "channel=mail" in url
447
448 # Default channel (wechat) is suppressed from the URL
449 obj = NotifyPushplus(token=GOOD_TOKEN, channel="wechat")
450 url = obj.url()
451 assert "channel=" not in url
452
453 # When channel=webhook with a name, url() uses schema://name@token form
454 obj = NotifyPushplus(
455 token=GOOD_TOKEN,
456 channel="webhook",
457 webhook="myhook",
458 )
459 url = obj.url()
460 assert "pushplus://myhook@" in url
461 # channel= and name= are both implied by user@ -- omitted from params
462 assert "channel=" not in url
463 assert "name=" not in url
464
465 # Privacy URL preserves the webhook name but masks the token
466 priv = obj.url(privacy=True)
467 assert "pushplus://myhook@" in priv
468 assert GOOD_TOKEN not in priv
469 assert "****" in priv
470
471 # Webhook prefix form with group topics -- schema://name@token/topic/ form
472 obj = NotifyPushplus(
473 token=GOOD_TOKEN,
474 channel="webhook",
475 webhook="myhook",
476 targets=["mygroup"],
477 )
478 url = obj.url()
479 assert "pushplus://myhook@" in url
480 assert "mygroup" in url
481 assert "channel=" not in url
482 assert "name=" not in url
483
484 # Webhook name suppressed when channel is not webhook
485 obj = NotifyPushplus(
486 token=GOOD_TOKEN,
487 channel="mail",
488 webhook="myhook",
489 )
490 url = obj.url()
491 assert "name=" not in url
492 assert "@" not in url
493
494 # Webhook channel without a name uses the plain ?channel=webhook form
495 obj = NotifyPushplus(token=GOOD_TOKEN, channel="webhook")
496 url = obj.url()
497 assert "name=" not in url
498 assert "channel=webhook" in url
499 assert "@" not in url
500
501 # Invalid targets are preserved in the URL path for round-trip fidelity
502 obj = NotifyPushplus(token=GOOD_TOKEN, targets=["bad!target"])
503 url = obj.url()
504 assert "bad" in url
505
506 # url_identifier contains only the schema and token (no targets or channel)
507 obj = NotifyPushplus(token=GOOD_TOKEN, targets=["grp"])
508 assert obj.url_identifier == ("pushplus", GOOD_TOKEN)
509
510 # Schema alias (wecom://) always normalises back to pushplus://
511 result = NotifyPushplus.parse_url("wecom://{}".format(GOOD_TOKEN))
512 obj = NotifyPushplus(**result)
513 url = obj.url()
514 assert url.startswith("pushplus://")
515 assert "channel=cp" in url
516
517
518 @mock.patch("requests.post")
519 def test_plugin_pushplus_send_ok(mock_post):
520 """NotifyPushplus() successful personal-notification send."""
521
522 # Prepare a successful mock response
523 response = mock.Mock()
524 response.status_code = requests.codes.ok
525 response.content = GOOD_RESPONSE.encode("utf-8")
526 mock_post.return_value = response
527
528 # Personal notification (no topic) -- single API call
529 obj = NotifyPushplus(token=GOOD_TOKEN)
530 assert obj.send(body="hello", title="title") is True
531 assert mock_post.call_count == 1
532
533 # Verify the endpoint URL
534 call = mock_post.call_args
535 assert call[0][0] == "https://www.pushplus.plus/send"
536
537 # Verify the core payload fields
538 payload = loads(call[1]["data"])
539 assert payload["token"] == GOOD_TOKEN
540 assert payload["content"] == "hello"
541 assert payload["title"] == "title"
542 # Default format is HTML -- PushPlus template should be "html"
543 assert payload["template"] == PUSHPLUS_FORMAT_MAP[NotifyFormat.HTML]
544 assert payload["channel"] == PUSHPLUS_CHANNEL_DEFAULT
545 # topic and webhook keys must be absent when not configured
546 assert "topic" not in payload
547 assert "webhook" not in payload
548
549 mock_post.reset_mock()
550 response.content = GOOD_RESPONSE.encode("utf-8")
551
552 # When no title is supplied the body is used as the title fallback
553 assert obj.send(body="only body") is True
554 payload = loads(mock_post.call_args[1]["data"])
555 assert payload["title"] == "only body"
556 assert payload["content"] == "only body"
557
558
559 @mock.patch("requests.post")
560 def test_plugin_pushplus_send_formats(mock_post):
561 """NotifyPushplus() maps notify_format to the PushPlus template field."""
562
563 response = mock.Mock()
564 response.status_code = requests.codes.ok
565 response.content = GOOD_RESPONSE.encode("utf-8")
566 mock_post.return_value = response
567
568 obj = NotifyPushplus(token=GOOD_TOKEN)
569
570 # Markdown format -> "markdown" template
571 obj.notify_format = NotifyFormat.MARKDOWN
572 assert obj.send(body="# heading") is True
573 payload = loads(mock_post.call_args[1]["data"])
574 assert payload["template"] == "markdown"
575
576 mock_post.reset_mock()
577 response.content = GOOD_RESPONSE.encode("utf-8")
578
579 # Text format -> "txt" template
580 obj.notify_format = NotifyFormat.TEXT
581 assert obj.send(body="plain text") is True
582 payload = loads(mock_post.call_args[1]["data"])
583 assert payload["template"] == "txt"
584
585 mock_post.reset_mock()
586 response.content = GOOD_RESPONSE.encode("utf-8")
587
588 # HTML format -> "html" template
589 obj.notify_format = NotifyFormat.HTML
590 assert obj.send(body="<b>bold</b>") is True
591 payload = loads(mock_post.call_args[1]["data"])
592 assert payload["template"] == "html"
593
594
595 @mock.patch("requests.post")
596 def test_plugin_pushplus_send_topic(mock_post):
597 """NotifyPushplus() includes the topic in the payload when configured."""
598
599 response = mock.Mock()
600 response.status_code = requests.codes.ok
601 response.content = GOOD_RESPONSE.encode("utf-8")
602 mock_post.return_value = response
603
604 # Single topic -- one API call, topic present in payload
605 obj = NotifyPushplus(token=GOOD_TOKEN, targets=["mygroup"])
606 assert obj.send(body="group msg") is True
607 assert mock_post.call_count == 1
608 payload = loads(mock_post.call_args[1]["data"])
609 assert payload["topic"] == "mygroup"
610
611
612 @mock.patch("requests.post")
613 def test_plugin_pushplus_send_multiple_topics(mock_post):
614 """NotifyPushplus() makes one API call per group topic."""
615
616 response = mock.Mock()
617 response.status_code = requests.codes.ok
618 response.content = GOOD_RESPONSE.encode("utf-8")
619 mock_post.return_value = response
620
621 # Three topics -> three separate API calls
622 obj = NotifyPushplus(
623 token=GOOD_TOKEN, targets=["topic1", "topic2", "topic3"]
624 )
625 assert len(obj.topics) == 3
626 assert obj.send(body="multi msg") is True
627 assert mock_post.call_count == 3
628
629 # Verify each call carries the correct topic value
630 calls = mock_post.call_args_list
631 topics_sent = [loads(c[1]["data"])["topic"] for c in calls]
632 assert topics_sent == ["topic1", "topic2", "topic3"]
633
634 mock_post.reset_mock()
635 response.content = GOOD_RESPONSE.encode("utf-8")
636
637 # Topics with a channel override -- all API calls use the specified channel
638 obj2 = NotifyPushplus(
639 token=GOOD_TOKEN, targets=["grp1", "grp2"], channel="mail"
640 )
641 assert len(obj2.topics) == 2
642 assert obj2.channel == PushPlusChannel.MAIL
643 assert obj2.send(body="mixed") is True
644 assert mock_post.call_count == 2
645 for call in mock_post.call_args_list:
646 assert loads(call[1]["data"])["channel"] == "mail"
647
648 mock_post.reset_mock()
649
650 # Partial failure: first topic succeeds, second fails -> overall False
651 good_resp = mock.Mock()
652 good_resp.status_code = requests.codes.ok
653 good_resp.content = GOOD_RESPONSE.encode("utf-8")
654 bad_resp = mock.Mock()
655 bad_resp.status_code = requests.codes.ok
656 bad_resp.content = BAD_RESPONSE.encode("utf-8")
657 mock_post.side_effect = [good_resp, bad_resp]
658
659 obj3 = NotifyPushplus(token=GOOD_TOKEN, targets=["grp1", "grp2"])
660 assert obj3.send(body="partial") is False
661 assert mock_post.call_count == 2
662
663
664 @mock.patch("requests.post")
665 def test_plugin_pushplus_send_webhook(mock_post):
666 """NotifyPushplus() webhook channel behaviour."""
667
668 response = mock.Mock()
669 response.status_code = requests.codes.ok
670 response.content = GOOD_RESPONSE.encode("utf-8")
671 mock_post.return_value = response
672
673 # Webhook channel with a named endpoint -- webhook key in payload
674 obj = NotifyPushplus(
675 token=GOOD_TOKEN,
676 channel="webhook",
677 webhook="myhook",
678 )
679 assert obj.send(body="hook msg") is True
680 payload = loads(mock_post.call_args[1]["data"])
681 assert payload["channel"] == PushPlusChannel.WEBHOOK
682 assert payload["webhook"] == "myhook"
683
684 mock_post.reset_mock()
685 response.content = GOOD_RESPONSE.encode("utf-8")
686
687 # Webhook channel without a name -- webhook key must be absent
688 obj2 = NotifyPushplus(token=GOOD_TOKEN, channel="webhook")
689 assert obj2.send(body="hook no name") is True
690 payload2 = loads(mock_post.call_args[1]["data"])
691 assert "webhook" not in payload2
692
693 mock_post.reset_mock()
694 response.content = GOOD_RESPONSE.encode("utf-8")
695
696 # Non-webhook channel with a webhook value set -- key must be absent
697 obj3 = NotifyPushplus(
698 token=GOOD_TOKEN,
699 channel="mail",
700 webhook="myhook",
701 )
702 assert obj3.send(body="mail msg") is True
703 payload3 = loads(mock_post.call_args[1]["data"])
704 assert "webhook" not in payload3
705
706
707 @mock.patch("requests.post")
708 def test_plugin_pushplus_send_http_error(mock_post):
709 """NotifyPushplus() handles HTTP-level errors correctly."""
710
711 response = mock.Mock()
712 response.content = b""
713 mock_post.return_value = response
714
715 obj = NotifyPushplus(token=GOOD_TOKEN)
716
717 # HTTP 500
718 response.status_code = requests.codes.internal_server_error
719 assert obj.send(body="msg") is False
720
721 # Unknown HTTP status code
722 response.status_code = 999
723 assert obj.send(body="msg") is False
724
725
726 @mock.patch("requests.post")
727 def test_plugin_pushplus_send_api_error(mock_post):
728 """NotifyPushplus() handles API-level failures (HTTP 200, bad code)."""
729
730 response = mock.Mock()
731 response.status_code = requests.codes.ok
732 mock_post.return_value = response
733
734 obj = NotifyPushplus(token=GOOD_TOKEN)
735
736 # Known API error code (907 = Token does not exist)
737 response.content = BAD_RESPONSE.encode("utf-8")
738 assert obj.send(body="msg") is False
739
740 # Unknown API error code with a msg field -- falls back to msg
741 response.content = dumps({"code": 999, "msg": "some error"}).encode(
742 "utf-8"
743 )
744 assert obj.send(body="msg") is False
745
746 # Unknown API error code with no msg field -- generic fallback
747 response.content = dumps({"code": 999}).encode("utf-8")
748 assert obj.send(body="msg") is False
749
750 # Unparsable JSON body
751 response.content = b"{bad json"
752 assert obj.send(body="msg") is False
753
754 # None content -- treated as unparsable
755 response.content = None
756 assert obj.send(body="msg") is False
757
758
759 @mock.patch("requests.post")
760 def test_plugin_pushplus_send_exception(mock_post):
761 """NotifyPushplus() handles connection exceptions gracefully."""
762 mock_post.side_effect = requests.RequestException("connection error")
763 obj = NotifyPushplus(token=GOOD_TOKEN)
764 assert obj.send(body="msg") is False
765
766
767 @mock.patch("requests.post")
768 def test_plugin_pushplus_send_exception_multi_topic(mock_post):
769 """NotifyPushplus() continues after a connection error on one topic."""
770
771 # First call raises, second succeeds -- overall result is False
772 good_resp = mock.Mock()
773 good_resp.status_code = requests.codes.ok
774 good_resp.content = GOOD_RESPONSE.encode("utf-8")
775 mock_post.side_effect = [
776 requests.RequestException("network error"),
777 good_resp,
778 ]
779
780 obj = NotifyPushplus(token=GOOD_TOKEN, targets=["grp1", "grp2"])
781 assert obj.send(body="msg") is False
782 # Both topics must still be attempted
783 assert mock_post.call_count == 2
784
785
786 def test_plugin_pushplus_parse_url():
787 """NotifyPushplus() parse_url() extracts all supported fields."""
788
789 # Token in the host position
790 result = NotifyPushplus.parse_url("pushplus://{}".format(GOOD_TOKEN))
791 assert result["token"] == GOOD_TOKEN
792 assert result["targets"] == []
793
794 # Token supplied as a ?token= query parameter
795 result = NotifyPushplus.parse_url(
796 "pushplus://?token={}".format(GOOD_TOKEN)
797 )
798 assert result["token"] == GOOD_TOKEN
799
800 # Topic in the URL path becomes a plain targets entry
801 result = NotifyPushplus.parse_url(
802 "pushplus://{}/mygroup".format(GOOD_TOKEN)
803 )
804 assert "mygroup" in result["targets"]
805
806 # Two topics in the path
807 result = NotifyPushplus.parse_url(
808 "pushplus://{}/grp1/grp2".format(GOOD_TOKEN)
809 )
810 assert "grp1" in result["targets"]
811 assert "grp2" in result["targets"]
812
813 # Backward compat: ?topic= adds a plain topic entry
814 result = NotifyPushplus.parse_url(
815 "pushplus://{}/?topic=mygroup".format(GOOD_TOKEN)
816 )
817 assert "mygroup" in result["targets"]
818
819 # ?to= alias appends additional targets
820 result = NotifyPushplus.parse_url(
821 "pushplus://{}/?to=mygroup".format(GOOD_TOKEN)
822 )
823 assert "mygroup" in result["targets"]
824
825 # Delivery channel via ?channel=
826 result = NotifyPushplus.parse_url(
827 "pushplus://{}?channel=mail".format(GOOD_TOKEN)
828 )
829 assert result.get("channel") == "mail"
830
831 # Delivery channel via ?mode= alias
832 result = NotifyPushplus.parse_url(
833 "pushplus://{}?mode=sms".format(GOOD_TOKEN)
834 )
835 assert result.get("channel") == "sms"
836
837 # channel= takes precedence over mode= when both are supplied
838 result = NotifyPushplus.parse_url(
839 "pushplus://{}?mode=sms&channel=mail".format(GOOD_TOKEN)
840 )
841 assert result.get("channel") == "mail"
842
843 # Webhook name extracted into the "webhook" key from ?name=
844 result = NotifyPushplus.parse_url(
845 "pushplus://{}?channel=webhook&name=myhook".format(GOOD_TOKEN)
846 )
847 assert result.get("webhook") == "myhook"
848 assert result.get("channel") == "webhook"
849
850 # schema://name@token form: user@ -> webhook, implies channel=webhook
851 result = NotifyPushplus.parse_url(
852 "pushplus://myhook@{}".format(GOOD_TOKEN)
853 )
854 assert result.get("webhook") == "myhook"
855 assert result.get("channel") == PushPlusChannel.WEBHOOK
856
857 # Explicit ?channel= overrides the webhook implication from user@
858 result = NotifyPushplus.parse_url(
859 "pushplus://myhook@{}?channel=mail".format(GOOD_TOKEN)
860 )
861 assert result.get("webhook") == "myhook"
862 assert result.get("channel") == "mail"
863
864 # ?name= takes precedence over user@ when both are supplied
865 result = NotifyPushplus.parse_url(
866 "pushplus://other@{}?channel=webhook&name=myhook".format(GOOD_TOKEN)
867 )
868 assert result.get("webhook") == "myhook"
869 assert result.get("channel") == "webhook"
870
871
872 def test_plugin_pushplus_parse_native_url():
873 """NotifyPushplus() parse_native_url() handles all edge cases."""
874
875 # Basic native URL -- token extracted correctly
876 result = NotifyPushplus.parse_native_url(
877 "https://www.pushplus.plus/send?token={}".format(GOOD_TOKEN)
878 )
879 assert result is not None
880 obj = NotifyPushplus(**result)
881 assert obj.token == GOOD_TOKEN
882
883 # Native URL with topic parameter preserved via round-trip
884 result = NotifyPushplus.parse_native_url(
885 "https://www.pushplus.plus/send?token={}&topic=mygroup".format(
886 GOOD_TOKEN
887 )
888 )
889 assert result is not None
890 obj = NotifyPushplus(**result)
891 assert "mygroup" in obj.topics
892
893 # Native URL with channel parameter preserved
894 result = NotifyPushplus.parse_native_url(
895 "https://www.pushplus.plus/send?token={}&channel=mail".format(
896 GOOD_TOKEN
897 )
898 )
899 assert result is not None
900 obj = NotifyPushplus(**result)
901 assert obj.channel == PushPlusChannel.MAIL
902
903 # Native URL with webhook name parameter preserved
904 result = NotifyPushplus.parse_native_url(
905 "https://www.pushplus.plus/send"
906 "?token={}&channel=webhook&name=myhook".format(GOOD_TOKEN)
907 )
908 assert result is not None
909 obj = NotifyPushplus(**result)
910 assert obj.webhook == "myhook"
911 assert obj.channel == PushPlusChannel.WEBHOOK
912
913 # Native URL without a token -- not matched, returns None
914 assert (
915 NotifyPushplus.parse_native_url(
916 "https://www.pushplus.plus/send?channel=mail"
917 )
918 is None
919 )
920
921 # Completely different domain -- not matched, returns None
922 assert (
923 NotifyPushplus.parse_native_url(
924 "https://other.example.com/send?token={}".format(GOOD_TOKEN)
925 )
926 is None
927 )
928
929 # Native URL with no query string -- not matched, returns None
930 assert (
931 NotifyPushplus.parse_native_url("https://www.pushplus.plus/send")
932 is None
933 )
934
935
936 @mock.patch("requests.post")
937 def test_plugin_pushplus_apprise_integration(mock_post):
938 """NotifyPushplus() integrates correctly with the Apprise object."""
939
940 response = mock.Mock()
941 response.status_code = requests.codes.ok
942 response.content = GOOD_RESPONSE.encode("utf-8")
943 mock_post.return_value = response
944
945 # Personal URL -- single notification
946 aobj = Apprise()
947 assert aobj.add("pushplus://{}".format(GOOD_TOKEN))
948 assert len(aobj) == 1
949 assert aobj.notify(title="Test Title", body="Test Body") is True
950 assert mock_post.call_count == 1
951
952 mock_post.reset_mock()
953 response.content = GOOD_RESPONSE.encode("utf-8")
954
955 # Group URL with markdown format override
956 aobj2 = Apprise()
957 assert aobj2.add(
958 "pushplus://{}/mygroup?format=markdown".format(GOOD_TOKEN)
959 )
960 assert aobj2.notify(body="Group message") is True
961 assert mock_post.call_count == 1
962 payload = loads(mock_post.call_args[1]["data"])
963 # format=markdown must map to the PushPlus "markdown" template
964 assert payload["template"] == "markdown"
965 assert payload["topic"] == "mygroup"
966
967 mock_post.reset_mock()
968 response.content = GOOD_RESPONSE.encode("utf-8")
969
970 # wecom:// schema alias -- channel=cp in payload
971 aobj3 = Apprise()
972 assert aobj3.add("wecom://{}".format(GOOD_TOKEN))
973 assert aobj3.notify(body="WeCom message") is True
974 payload = loads(mock_post.call_args[1]["data"])
975 assert payload["channel"] == PushPlusChannel.WECOM