Debian Codegraph @

tests/test_plugin_wpush.py

raw
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 pytest
36 import requests
37
38 from apprise import Apprise
39 from apprise.exception import AppriseImproperlyConfigured
40 from apprise.plugins.wpush import (
41 WPUSH_CHANNEL_DEFAULT,
42 NotifyWPush,
43 WPushChannel,
44 )
45
46 logging.disable(logging.CRITICAL)
47
48 # WPUSH + exactly 27 more alphanumeric characters (32 total)
49 GOOD_KEY = "WPUSH" + ("a" * 27)
50
51 GOOD_RESPONSE = dumps(
52 {"code": 0, "message": "success", "data": "1126950958891274240"}
53 )
54 BAD_RESPONSE = dumps({"code": 401, "message": "API Key error"})
55
56 apprise_url_tests = (
57 (
58 "wpush://",
59 {"instance": AppriseImproperlyConfigured},
60 ),
61 (
62 "wpush://short",
63 {"instance": AppriseImproperlyConfigured},
64 ),
65 (
66 "wpush://{}".format(GOOD_KEY),
67 {
68 "instance": NotifyWPush,
69 "privacy_url": "wpush://****/",
70 "requests_response_text": GOOD_RESPONSE,
71 },
72 ),
73 (
74 "wpush://?apikey={}".format(GOOD_KEY),
75 {
76 "instance": NotifyWPush,
77 "privacy_url": "wpush://****/",
78 "requests_response_text": GOOD_RESPONSE,
79 },
80 ),
81 (
82 "wpush://{}?channel=feishu".format(GOOD_KEY),
83 {
84 "instance": NotifyWPush,
85 "requests_response_text": GOOD_RESPONSE,
86 },
87 ),
88 (
89 "wpush://{}?channel=feishu,dingtalk,qqbot".format(GOOD_KEY),
90 {
91 "instance": NotifyWPush,
92 "requests_response_text": GOOD_RESPONSE,
93 },
94 ),
95 (
96 "wpush://{}/topic1/topic2".format(GOOD_KEY),
97 {
98 "instance": NotifyWPush,
99 "requests_response_text": GOOD_RESPONSE,
100 },
101 ),
102 (
103 "wpush://{}?to=topic1,topic2".format(GOOD_KEY),
104 {
105 "instance": NotifyWPush,
106 "requests_response_text": GOOD_RESPONSE,
107 },
108 ),
109 (
110 "wpush://{}?topic_code=mytopic".format(GOOD_KEY),
111 {
112 "instance": NotifyWPush,
113 "requests_response_text": GOOD_RESPONSE,
114 },
115 ),
116 (
117 "wpush://{}?topic=mytopic".format(GOOD_KEY),
118 {
119 "instance": NotifyWPush,
120 "requests_response_text": GOOD_RESPONSE,
121 },
122 ),
123 (
124 "wpush://{}?channel=qqbot&group=123456".format(GOOD_KEY),
125 {
126 "instance": NotifyWPush,
127 "requests_response_text": GOOD_RESPONSE,
128 },
129 ),
130 (
131 "wpush://{}?channel=qqbot&option=123456".format(GOOD_KEY),
132 {
133 "instance": NotifyWPush,
134 "requests_response_text": GOOD_RESPONSE,
135 },
136 ),
137 (
138 "wpush://{}?url=https://example.com/".format(GOOD_KEY),
139 {
140 "instance": NotifyWPush,
141 "requests_response_text": GOOD_RESPONSE,
142 },
143 ),
144 (
145 "wpush://{}?channel=nope".format(GOOD_KEY),
146 {"instance": AppriseImproperlyConfigured},
147 ),
148 (
149 "wpush://{}?group=123456&topic_code=mytopic".format(GOOD_KEY),
150 {"instance": AppriseImproperlyConfigured},
151 ),
152 (
153 "https://api.wpush.cn/api/v1/send?apikey={}".format(GOOD_KEY),
154 {
155 "instance": NotifyWPush,
156 "requests_response_text": GOOD_RESPONSE,
157 },
158 ),
159 (
160 "wpush://{}".format(GOOD_KEY),
161 {
162 "instance": NotifyWPush,
163 "response": False,
164 "requests_response_text": BAD_RESPONSE,
165 },
166 ),
167 (
168 "wpush://{}".format(GOOD_KEY),
169 {
170 "instance": NotifyWPush,
171 "response": False,
172 "requests_response_code": requests.codes.internal_server_error,
173 },
174 ),
175 (
176 "wpush://{}".format(GOOD_KEY),
177 {
178 "instance": NotifyWPush,
179 "test_requests_exceptions": True,
180 },
181 ),
182 )
183
184
185 def test_plugin_wpush_urls():
186 """NotifyWPush() Apprise URL test suite."""
187 AppriseURLTester(tests=apprise_url_tests).run_all()
188
189
190 def test_plugin_wpush_init():
191 """NotifyWPush() object initialization."""
192 obj = NotifyWPush(apikey=GOOD_KEY)
193 assert obj.apikey == GOOD_KEY
194 assert obj.channels == [WPUSH_CHANNEL_DEFAULT]
195 assert obj.topics == []
196 assert obj.group is None
197 assert obj.click_url is None
198 assert len(obj) == 1
199
200 obj = NotifyWPush(apikey=GOOD_KEY, channel="mail")
201 assert obj.channels == [WPushChannel.MAIL]
202
203 # Channels are stored once in alphabetical order
204 obj = NotifyWPush(apikey=GOOD_KEY, channel="feishu,dingtalk,qqbot")
205 assert obj.channels == [
206 WPushChannel.DINGTALK,
207 WPushChannel.FEISHU,
208 WPushChannel.QQBOT,
209 ]
210
211 obj = NotifyWPush(apikey=GOOD_KEY, targets=["topic1", "topic2"])
212 assert obj.topics == ["topic1", "topic2"]
213 assert len(obj) == 2
214
215 obj = NotifyWPush(apikey=GOOD_KEY, channel="qqbot", group="123456")
216 assert obj.group == "123456"
217
218 # Channel matching ignores case and duplicates
219 obj = NotifyWPush(apikey=GOOD_KEY, channel="Feishu,dingtalk,feishu")
220 assert obj.channels == [WPushChannel.DINGTALK, WPushChannel.FEISHU]
221
222 obj = NotifyWPush(apikey=GOOD_KEY, click_url="https://example.com/")
223 assert obj.click_url == "https://example.com/"
224
225 with pytest.raises(AppriseImproperlyConfigured):
226 NotifyWPush(apikey=GOOD_KEY, channel="nope")
227
228 with pytest.raises(AppriseImproperlyConfigured):
229 NotifyWPush(apikey=GOOD_KEY, channel="feishu,nope")
230
231 with pytest.raises(AppriseImproperlyConfigured):
232 NotifyWPush(apikey="bad")
233
234 with pytest.raises(AppriseImproperlyConfigured):
235 # Group and topic targets cannot be combined
236 NotifyWPush(apikey=GOOD_KEY, group="123456", targets=["topic1"])
237
238
239 def test_plugin_wpush_url_round_trip():
240 """NotifyWPush() url() round trip through parse_url()."""
241 obj = NotifyWPush(
242 apikey=GOOD_KEY,
243 channel="feishu,dingtalk",
244 targets=["topic1", "topic2"],
245 click_url="https://example.com/",
246 )
247 results = NotifyWPush.parse_url(obj.url())
248 obj2 = NotifyWPush(**results)
249
250 assert obj.url_identifier == obj2.url_identifier
251 assert obj.topics == obj2.topics
252 # Channels are stored once in alphabetical order
253 assert obj2.channels == [WPushChannel.DINGTALK, WPushChannel.FEISHU]
254 assert obj2.click_url == "https://example.com/"
255
256 # Round trip a QQ Robot group without a topic
257 obj3 = NotifyWPush(apikey=GOOD_KEY, channel="qqbot", group="123456")
258 results3 = NotifyWPush.parse_url(obj3.url())
259 obj4 = NotifyWPush(**results3)
260 assert obj4.group == "123456"
261 assert obj4.channels == [WPushChannel.QQBOT]
262
263
264 @mock.patch("requests.post")
265 def test_plugin_wpush_send_ok(mock_post):
266 """Send once when no topic is set."""
267 response = mock.Mock()
268 response.status_code = requests.codes.ok
269 response.content = GOOD_RESPONSE.encode("utf-8")
270 mock_post.return_value = response
271
272 obj = NotifyWPush(apikey=GOOD_KEY)
273 assert obj.send(body="hello", title="title") is True
274 assert mock_post.call_count == 1
275 assert mock_post.call_args[0][0] == "https://api.wpush.cn/api/v1/send"
276 assert mock_post.call_args[1]["headers"]["X-API-Key"] == GOOD_KEY
277 assert "X-Idempotency-Key" in mock_post.call_args[1]["headers"]
278 payload = loads(mock_post.call_args[1]["data"])
279 assert payload["apikey"] == GOOD_KEY
280 assert payload["title"] == "title"
281 assert payload["content"] == "hello"
282 assert payload["channel"] == WPUSH_CHANNEL_DEFAULT
283 assert "topic_code" not in payload
284 assert "option" not in payload
285 assert "url" not in payload
286
287 mock_post.reset_mock()
288 assert obj.send(body="only body") is True
289 payload = loads(mock_post.call_args[1]["data"])
290 assert payload["title"] == "only body"
291
292
293 @mock.patch("requests.post")
294 def test_plugin_wpush_send_multi_channel(mock_post):
295 """Send to several channels in one request."""
296 response = mock.Mock()
297 response.status_code = requests.codes.ok
298 response.content = GOOD_RESPONSE.encode("utf-8")
299 mock_post.return_value = response
300
301 # The payload keeps the stored alphabetical order
302 obj = NotifyWPush(apikey=GOOD_KEY, channel="feishu,dingtalk,qqbot")
303 assert obj.send(body="msg", title="t") is True
304 assert mock_post.call_count == 1
305 payload = loads(mock_post.call_args[1]["data"])
306 assert payload["channel"] == "dingtalk,feishu,qqbot"
307
308
309 @mock.patch("requests.post")
310 def test_plugin_wpush_send_topic_and_channel(mock_post):
311 """Send to one topic through a selected channel."""
312 response = mock.Mock()
313 response.status_code = requests.codes.ok
314 response.content = GOOD_RESPONSE.encode("utf-8")
315 mock_post.return_value = response
316
317 obj = NotifyWPush(apikey=GOOD_KEY, channel="feishu", targets="abc123")
318 assert obj.send(body="msg", title="t") is True
319 payload = loads(mock_post.call_args[1]["data"])
320 assert payload["channel"] == "feishu"
321 assert payload["topic_code"] == "abc123"
322
323
324 @mock.patch("requests.post")
325 def test_plugin_wpush_send_qqbot_group(mock_post):
326 """NotifyWPush() includes API option whenever group/option is set."""
327 response = mock.Mock()
328 response.status_code = requests.codes.ok
329 response.content = GOOD_RESPONSE.encode("utf-8")
330 mock_post.return_value = response
331
332 # Send the group code for QQ Robot
333 obj = NotifyWPush(apikey=GOOD_KEY, channel="qqbot", group="123456")
334 assert obj.send(body="msg") is True
335 payload = loads(mock_post.call_args[1]["data"])
336 assert payload["option"] == "123456"
337
338 # Other supported channels use option to select a bound instance
339 mock_post.reset_mock()
340 obj = NotifyWPush(apikey=GOOD_KEY, channel="mail", group="123456")
341 assert obj.send(body="msg") is True
342 payload = loads(mock_post.call_args[1]["data"])
343 assert payload["option"] == "123456"
344
345
346 @mock.patch("requests.post")
347 def test_plugin_wpush_send_click_url(mock_post):
348 """Include an optional click-through URL."""
349 response = mock.Mock()
350 response.status_code = requests.codes.ok
351 response.content = GOOD_RESPONSE.encode("utf-8")
352 mock_post.return_value = response
353
354 obj = NotifyWPush(apikey=GOOD_KEY, click_url="https://example.com/")
355 assert obj.send(body="msg") is True
356 payload = loads(mock_post.call_args[1]["data"])
357 assert payload["url"] == "https://example.com/"
358
359
360 @mock.patch("requests.post")
361 def test_plugin_wpush_send_multiple_topics(mock_post):
362 """NotifyWPush() sends once per topic and reports partial failure."""
363 ok_response = mock.Mock()
364 ok_response.status_code = requests.codes.ok
365 ok_response.content = GOOD_RESPONSE.encode("utf-8")
366
367 bad_response = mock.Mock()
368 bad_response.status_code = requests.codes.ok
369 bad_response.content = BAD_RESPONSE.encode("utf-8")
370
371 # Capture each key while the shared headers dictionary changes
372 seen_keys = []
373 responses = [ok_response, bad_response]
374
375 def _side_effect(*args, **kwargs):
376 seen_keys.append(kwargs["headers"]["X-Idempotency-Key"])
377 return responses[len(seen_keys) - 1]
378
379 mock_post.side_effect = _side_effect
380
381 obj = NotifyWPush(apikey=GOOD_KEY, targets=["topic1", "topic2"])
382 assert obj.send(body="msg") is False
383 assert mock_post.call_count == 2
384
385 # Each request must use a different key
386 assert seen_keys[0] != seen_keys[1]
387
388
389 @mock.patch("requests.post")
390 def test_plugin_wpush_send_api_error(mock_post):
391 """Handle a WPUSH error returned with HTTP 200."""
392 response = mock.Mock()
393 response.status_code = requests.codes.ok
394 response.content = BAD_RESPONSE.encode("utf-8")
395 mock_post.return_value = response
396 obj = NotifyWPush(apikey=GOOD_KEY)
397 assert obj.send(body="msg") is False
398
399
400 @mock.patch("requests.post")
401 def test_plugin_wpush_bad_json(mock_post):
402 """Handle a response that is not JSON."""
403 response = mock.Mock()
404 response.status_code = requests.codes.ok
405 response.content = b"not-json"
406 mock_post.return_value = response
407
408 obj = NotifyWPush(apikey=GOOD_KEY)
409 assert obj.send(body="msg") is False
410
411
412 @mock.patch("requests.post")
413 def test_plugin_wpush_apprise_integration(mock_post):
414 """Send through Apprise."""
415 response = mock.Mock()
416 response.status_code = requests.codes.ok
417 response.content = GOOD_RESPONSE.encode("utf-8")
418 mock_post.return_value = response
419
420 aobj = Apprise()
421 assert aobj.add("wpush://{}".format(GOOD_KEY))
422 assert bool(aobj.notify(title="T", body="B")) is True
423 assert mock_post.call_count == 1
424
425
426 def test_plugin_wpush_instance_options():
427 """Send instance codes through the option field."""
428 from json import loads
429
430 for channel in ("feishu", "dingtalk", "webhook", "wechat_work"):
431 obj = Apprise.instantiate(
432 "wpush://{}?channel={}&option=ops".format(GOOD_KEY, channel)
433 )
434 assert isinstance(obj, NotifyWPush)
435 assert obj.group == "ops"
436
437 with mock.patch("requests.post") as mock_post:
438 mock_post.return_value = mock.Mock(
439 status_code=200,
440 content=GOOD_RESPONSE.encode("utf-8"),
441 )
442 assert obj.notify(title="t", body="b") is True
443 assert mock_post.called
444 payload = loads(mock_post.call_args[1]["data"].decode("utf-8"))
445 assert payload.get("option") == "ops"
446 assert payload.get("channel") == channel
447
448
449 def test_plugin_wpush_parse_native_url():
450 """Parse supported and invalid native URLs."""
451
452 # Parse the API Key
453 result = NotifyWPush.parse_native_url(
454 "https://api.wpush.cn/api/v1/send?apikey={}".format(GOOD_KEY)
455 )
456 assert result is not None
457 obj = NotifyWPush(**result)
458 assert obj.apikey == GOOD_KEY
459
460 # Preserve the channel parameter
461 result = NotifyWPush.parse_native_url(
462 "https://api.wpush.cn/api/v1/send?apikey={}&channel=mail".format(
463 GOOD_KEY
464 )
465 )
466 assert result is not None
467 obj = NotifyWPush(**result)
468 assert obj.channels == [WPushChannel.MAIL]
469
470 # Reject a URL without an API Key
471 assert (
472 NotifyWPush.parse_native_url(
473 "https://api.wpush.cn/api/v1/send?channel=mail"
474 )
475 is None
476 )
477
478 # Reject other domains
479 assert (
480 NotifyWPush.parse_native_url(
481 "https://other.example.com/api/v1/send?apikey={}".format(GOOD_KEY)
482 )
483 is None
484 )
485
486 # Reject a URL without query parameters
487 assert (
488 NotifyWPush.parse_native_url("https://api.wpush.cn/api/v1/send")
489 is None
490 )
491
492
493 def test_plugin_wpush_rejects_boolean_code():
494 """Reject Boolean codes even though False equals zero in Python."""
495 obj = Apprise.instantiate("wpush://{}".format(GOOD_KEY))
496 with mock.patch("requests.post") as mock_post:
497 mock_post.return_value = mock.Mock(
498 status_code=200,
499 content=dumps({"code": False, "message": "nope"}).encode("utf-8"),
500 )
501 assert obj.notify(title="t", body="b") is False