Debian Codegraph @

tests/test_plugin_nextcloud.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 from unittest import mock
32
33 from helpers import AppriseURLTester
34 import requests
35
36 from apprise import Apprise, AppriseAsset, NotifyType, PersistentStoreMode
37 from apprise.plugins.nextcloud import NotifyNextcloud
38
39 NEXTCLOUD_GOOD_RESPONSE = dumps(
40 {
41 "ocs": {
42 "meta": {"status": "ok", "statuscode": 100},
43 "data": {"users": ["user1", "user2"]},
44 }
45 }
46 )
47
48 logging.disable(logging.CRITICAL)
49
50 apprise_url_tests = (
51 ##################################
52 # NotifyNextcloud
53 ##################################
54 (
55 "ncloud://:@/",
56 {
57 "instance": None,
58 # Our response expected server response
59 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
60 },
61 ),
62 (
63 "ncloud://",
64 {
65 "instance": None,
66 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
67 },
68 ),
69 (
70 "nclouds://",
71 {
72 # No hostname
73 "instance": None,
74 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
75 },
76 ),
77 (
78 "ncloud://localhost",
79 {
80 # No user specified
81 "instance": NotifyNextcloud,
82 # Since there are no targets specified we expect a False return on
83 # send()
84 "notify_response": False,
85 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
86 },
87 ),
88 (
89 "ncloud://user@localhost?to=user1,user2&version=invalid",
90 {
91 # An invalid version was specified
92 "instance": TypeError,
93 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
94 },
95 ),
96 (
97 "ncloud://user@localhost?to=user1,user2&version=0",
98 {
99 # An invalid version was specified
100 "instance": TypeError,
101 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
102 },
103 ),
104 (
105 "ncloud://user@localhost?to=user1,user2&version=-23",
106 {
107 # An invalid version was specified
108 "instance": TypeError,
109 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
110 },
111 ),
112 (
113 "ncloud://localhost/admin",
114 {
115 "instance": NotifyNextcloud,
116 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
117 },
118 ),
119 (
120 "ncloud://user@localhost/admin",
121 {
122 "instance": NotifyNextcloud,
123 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
124 },
125 ),
126 (
127 "ncloud://user@localhost?to=user1,user2",
128 {
129 "instance": NotifyNextcloud,
130 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
131 },
132 ),
133 (
134 "ncloud://user@localhost?to=user1,user2&version=20",
135 {
136 "instance": NotifyNextcloud,
137 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
138 },
139 ),
140 (
141 "ncloud://user@localhost?to=user1,user2&version=21",
142 {
143 "instance": NotifyNextcloud,
144 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
145 },
146 ),
147 (
148 "ncloud://user@localhost?to=user1&version=20&url_prefix=/abcd",
149 {
150 "instance": NotifyNextcloud,
151 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
152 },
153 ),
154 (
155 "ncloud://user@localhost?to=user1&version=21&url_prefix=/abcd",
156 {
157 "instance": NotifyNextcloud,
158 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
159 },
160 ),
161 (
162 "ncloud://user:pass@localhost/user1/user2",
163 {
164 "instance": NotifyNextcloud,
165 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
166 # Our expected url(privacy=True) startswith() response:
167 "privacy_url": "ncloud://user:****@localhost/@user1/@user2",
168 },
169 ),
170 (
171 "ncloud://user:pass@localhost/#group1/#group2/#group1",
172 {
173 # Test groups, but also note a duplicate group provided
174 "instance": NotifyNextcloud,
175 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
176 "privacy_url": "ncloud://user:****@localhost/#group",
177 },
178 ),
179 (
180 "ncloud://user:pass@localhost:8080/admin",
181 {
182 "instance": NotifyNextcloud,
183 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
184 },
185 ),
186 (
187 "nclouds://user:pass@localhost/admin",
188 {
189 "instance": NotifyNextcloud,
190 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
191 # Our expected url(privacy=True) startswith() response:
192 "privacy_url": "nclouds://user:****@localhost/@admin",
193 },
194 ),
195 (
196 "nclouds://user:pass@localhost:8080/admin/",
197 {
198 "instance": NotifyNextcloud,
199 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
200 },
201 ),
202 (
203 "nclouds://user:pass@localhost:8080/#group/",
204 {
205 "instance": NotifyNextcloud,
206 # Invalid JSON Response
207 "requests_response_text": "{",
208 # We will fail to make the notify() call due to our bad response
209 "notify_response": False,
210 },
211 ),
212 (
213 "ncloud://localhost:8080/admin?+HeaderKey=HeaderValue",
214 {
215 "instance": NotifyNextcloud,
216 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
217 },
218 ),
219 (
220 "ncloud://user:pass@localhost:8081/admin",
221 {
222 "instance": NotifyNextcloud,
223 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
224 # force a failure
225 "response": False,
226 "requests_response_code": requests.codes.internal_server_error,
227 },
228 ),
229 (
230 "ncloud://user:pass@localhost:8082/admin",
231 {
232 "instance": NotifyNextcloud,
233 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
234 # throw a bizarre code forcing us to fail to look it up
235 "response": False,
236 "requests_response_code": 999,
237 },
238 ),
239 (
240 "ncloud://user:pass@localhost:8083/user1/user2/user3",
241 {
242 "instance": NotifyNextcloud,
243 "requests_response_text": NEXTCLOUD_GOOD_RESPONSE,
244 # Throws a series of i/o exceptions with this flag
245 # is set and tests that we gracefully handle them
246 "test_requests_exceptions": True,
247 },
248 ),
249 )
250
251
252 def test_plugin_nextcloud_urls():
253 """NotifyNextcloud() Apprise URLs."""
254
255 # Run our general tests
256 AppriseURLTester(tests=apprise_url_tests).run_all()
257
258
259 @mock.patch("requests.post")
260 def test_plugin_nextcloud_edge_cases(mock_post):
261 """NotifyNextcloud() Edge Cases."""
262
263 # A response
264 robj = mock.Mock()
265 robj.content = ""
266 robj.status_code = requests.codes.ok
267
268 # Prepare Mock
269 mock_post.return_value = robj
270
271 # Variation Initializations
272 obj = NotifyNextcloud(
273 host="localhost", user="admin", password="pass", targets="user"
274 )
275 assert isinstance(obj, NotifyNextcloud) is True
276 assert isinstance(obj.url(), str) is True
277
278 # An empty body
279 assert obj.send(body="") is True
280 assert "data" in mock_post.call_args_list[0][1]
281 assert "shortMessage" in mock_post.call_args_list[0][1]["data"]
282 # The longMessage argument is not set
283 assert "longMessage" not in mock_post.call_args_list[0][1]["data"]
284
285
286 @mock.patch("requests.post")
287 def test_plugin_nextcloud_url_prefix(mock_post):
288 """NotifyNextcloud() URL Prefix Testing."""
289
290 response = mock.Mock()
291 response.content = ""
292 response.status_code = requests.codes.ok
293
294 # Prepare our mock object
295 mock_post.return_value = response
296
297 # instantiate our object (without a batch mode)
298 obj = Apprise.instantiate(
299 "ncloud://localhost/admin/?version=20&url_prefix=/abcd"
300 )
301
302 assert (
303 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
304 is True
305 )
306
307 # Not set to batch, so we send 2 different messages
308 assert mock_post.call_count == 1
309 assert (
310 mock_post.call_args_list[0][0][0]
311 == "http://localhost/abcd/ocs/v2.php/apps/"
312 "admin_notifications/api/v1/notifications/admin"
313 )
314
315
316 @mock.patch("requests.post")
317 @mock.patch("requests.get")
318 def test_plugin_nextcloud_groups_and_all(mock_get, mock_post):
319 """NotifyNextcloud() Group and All user expansion."""
320
321 # Mock POST success
322 post_resp = mock.Mock()
323 post_resp.content = ""
324 post_resp.status_code = requests.codes.ok
325 mock_post.return_value = post_resp
326
327 # Mock GET responses for group and users listing
328 def get_side_effect(url, *args, **kwargs):
329 resp = mock.Mock()
330 if "/ocs/v1.php/cloud/groups/" in url:
331 # Return JSON for group
332 j = {
333 "ocs": {
334 "meta": {"status": "ok", "statuscode": 100},
335 "data": {"users": ["user1", "user2"]},
336 }
337 }
338 resp.status_code = requests.codes.ok
339 resp.json = lambda: j
340 resp.content = dumps(j).encode()
341 return resp
342
343 elif "/ocs/v1.php/cloud/users" in url:
344 j = {
345 "ocs": {
346 "meta": {"status": "ok", "statuscode": 100},
347 "data": {"users": ["user1", "user3"]},
348 }
349 }
350 resp.status_code = requests.codes.ok
351 resp.json = lambda: j
352 resp.content = dumps(j).encode()
353 return resp
354 # default
355 resp.status_code = requests.codes.ok
356 resp.content = b""
357 resp.json = lambda: {}
358 return resp
359
360 mock_get.side_effect = get_side_effect
361
362 # Instantiate with a mix of targets: group, all, and direct user
363 obj = NotifyNextcloud(
364 host="localhost",
365 user="admin",
366 password="pass",
367 targets=["#devs", "all", "user4"],
368 )
369
370 assert isinstance(obj, NotifyNextcloud)
371
372 # Send notification
373 assert (
374 obj.send(body="body", title="title", notify_type=NotifyType.INFO)
375 is True
376 )
377
378 # Expected resolved users (deduplicated): user1, user2, user3, user4
379 # Hence 4 POST calls
380 assert mock_post.call_count == 4
381
382 # Validate calls were made to expected endpoints
383 called_urls = [c[0][0] for c in mock_post.call_args_list]
384 for u in ("user1", "user2", "user3", "user4"):
385 assert any(u in url for url in called_urls)
386
387
388 @mock.patch("requests.post")
389 @mock.patch("requests.get")
390 def test_plugin_nextcloud_persistent_storage(mock_get, mock_post, tmpdir):
391 """Testing persistent storage"""
392
393 post_resp = mock.Mock()
394 post_resp.content = ""
395 post_resp.status_code = requests.codes.ok
396 mock_post.return_value = post_resp
397
398 # Set up persistent storage
399 asset = AppriseAsset(
400 storage_mode=PersistentStoreMode.FLUSH,
401 storage_path=str(tmpdir),
402 )
403
404 def get_side_effect(url, *args, **kwargs):
405 resp = mock.Mock()
406 # Default json() to empty
407 resp.json = lambda: {}
408
409 if "/ocs/v1.php/cloud/groups" in url:
410 resp.status_code = requests.codes.ok
411 payload = {"ocs": {"data": {"users": ["u1"]}}}
412 resp.json = lambda: payload
413 resp.content = dumps(payload).encode()
414 return resp
415
416 elif "/ocs/v1.php/cloud/users" in url:
417 resp.status_code = requests.codes.ok
418 payload = {"ocs": {"data": {"users": ["u2"]}}}
419 resp.json = lambda: payload
420 resp.content = dumps(payload).encode()
421 return resp
422
423 resp.status_code = 500
424 resp.content = b""
425 return resp
426
427 mock_get.side_effect = get_side_effect
428
429 obj = NotifyNextcloud(
430 host="localhost",
431 user="admin",
432 password="pass",
433 targets=["#devs", "all"],
434 asset=asset,
435 )
436 # We failed to get our list
437 assert (
438 obj.send(body="body", title="title", notify_type=NotifyType.INFO)
439 is True
440 )
441
442 # User and Group looked up
443 assert mock_get.call_count == 2
444
445 # Expect users u1 (group) and u2 (all)
446 assert mock_post.call_count == 2
447 called_urls = [c[0][0] for c in mock_post.call_args_list]
448 for u in ("u1", "u2"):
449 assert any(u in url for url in called_urls)
450
451 mock_get.reset_mock()
452 mock_post.reset_mock()
453
454 obj = NotifyNextcloud(
455 host="localhost",
456 user="admin",
457 password="pass",
458 targets=["#devs"],
459 asset=asset,
460 )
461 # We succeeded this time
462 assert (
463 obj.send(body="body", title="title", notify_type=NotifyType.INFO)
464 is True
465 )
466
467 # Expect users u1 (group) only and pulled from cache
468 assert mock_get.call_count == 0
469 assert mock_post.call_count == 1
470 assert mock_post.call_args_list[0][0][0].endswith("/u1")
471
472
473 @mock.patch("requests.post")
474 @mock.patch("requests.get")
475 def test_plugin_nextcloud_groups_errors_and_dedup(mock_get, mock_post):
476 """Non-200/exception paths return empty lists and dedup still applies."""
477
478 post_resp = mock.Mock()
479 post_resp.content = ""
480 post_resp.status_code = requests.codes.ok
481 mock_post.return_value = post_resp
482
483 # Non-200 for group and users; JSON invalid
484 def get_side_effect(url, *args, **kwargs):
485 resp = mock.Mock()
486 resp.status_code = 401
487 resp.content = b"<ocs><data></data></ocs>"
488 # Return empty/invalid JSON to drive empty path
489 resp.json = lambda: {}
490 return resp
491
492 mock_get.side_effect = get_side_effect
493
494 # Provide duplicates alongside failing expansions
495 obj = NotifyNextcloud(
496 host="localhost",
497 user="admin",
498 password="pass",
499 targets=["#devs", "all", "user1", "user1", "user2"],
500 )
501
502 # We failed to hit the server for data
503 assert obj.send(body="x", title="y", notify_type=NotifyType.INFO) is False
504
505 # we have no control over the order, but we know that on the first
506 # GET call, we'd have gotten a 401 response; so we'd have stopped from
507 # that point further
508 assert mock_get.call_count == 1
509
510 # Nothing notified
511 assert mock_post.call_count == 0
512
513
514 @mock.patch("requests.post")
515 @mock.patch("requests.get")
516 def test_plugin_nextcloud_req_exception_and_empty_targets(mock_get, mock_post):
517 """RequestException returns empty expansion; direct users send."""
518
519 post_resp = mock.Mock()
520 post_resp.content = ""
521 post_resp.status_code = requests.codes.ok
522 mock_post.return_value = post_resp
523
524 def get_side_effect(url, *args, **kwargs):
525 raise requests.RequestException("boom")
526
527 mock_get.side_effect = get_side_effect
528
529 obj = NotifyNextcloud(
530 host="localhost",
531 user="admin",
532 password="pass",
533 targets=["", " ", "#DevTeam", "#", "userX"],
534 )
535
536 # Our Group inquiry failed to respond
537 assert obj.send(body="x", title="y", notify_type=NotifyType.INFO) is False
538 assert mock_post.call_count == 0
539 assert mock_get.call_count == 1
540 assert (
541 mock_get.call_args_list[0][0][0]
542 == "http://localhost/ocs/v1.php/cloud/groups/DevTeam"
543 )
544 assert mock_get.call_args_list[0][1]["params"].get("format") == "json"
545
546
547 @mock.patch("requests.post")
548 @mock.patch("requests.get")
549 def test_plugin_nextcloud_json_empty_returns_empty(mock_get, mock_post):
550 """Invalid/empty JSON returns empty; direct users still send."""
551
552 post_resp = mock.Mock()
553 post_resp.content = ""
554 post_resp.status_code = requests.codes.ok
555 mock_post.return_value = post_resp
556
557 def get_side_effect(url, *args, **kwargs):
558 resp = mock.Mock()
559 resp.json = lambda: {}
560 resp.status_code = requests.codes.ok
561 resp.content = b"{}"
562 return resp
563
564 mock_get.side_effect = get_side_effect
565
566 obj = NotifyNextcloud(
567 host="localhost",
568 user="admin",
569 password="pass",
570 targets=["#broken", "all", "userZ"],
571 )
572
573 # Our notification
574 assert obj.send(body="x", title="y", notify_type=NotifyType.INFO) is True
575 # Only direct userZ posts because both expansions return empty
576 assert mock_get.call_count == 2
577 assert any(
578 "/cloud/users" in call[0][0] for call in mock_get.call_args_list
579 )
580 assert any(
581 "/cloud/groups/broken" in call[0][0]
582 for call in mock_get.call_args_list
583 )
584
585 # userZ would get a notification
586 assert mock_post.call_count == 1
587 assert mock_post.call_args_list[0][0][0].endswith("/userZ")
588
589
590 @mock.patch("requests.post")
591 @mock.patch("requests.get")
592 def test_plugin_nextcloud_caching_group_and_all(mock_get, mock_post):
593 """Cache hits avoid repeat OCS lookups."""
594
595 # First round of GETs return users for group and all
596 def get_side_effect(url, *args, **kwargs):
597 resp = mock.Mock()
598 resp.status_code = requests.codes.ok
599 if "/ocs/v1.php/cloud/groups" in url:
600 j = {
601 "ocs": {
602 "meta": {"status": "ok", "statuscode": 100},
603 "data": {"users": ["g1", "g2"]},
604 }
605 }
606 elif "/ocs/v1.php/cloud/users" in url:
607 j = {
608 "ocs": {
609 "meta": {"status": "ok", "statuscode": 100},
610 "data": {"users": ["a1", "a2"]},
611 }
612 }
613 else:
614 j = {"ocs": {"data": {"users": []}}}
615 resp.json = lambda: j
616 resp.content = dumps(j).encode()
617 return resp
618
619 mock_get.side_effect = get_side_effect
620
621 post_resp = mock.Mock()
622 post_resp.content = ""
623 post_resp.status_code = requests.codes.ok
624 mock_post.return_value = post_resp
625
626 obj = NotifyNextcloud(
627 host="localhost",
628 user="admin",
629 password="pass",
630 targets=["#devs", "all", "@joe"],
631 )
632
633 # First send: resolves via OCS; expect 2 GETs (group + all)
634 assert obj.send(body="b", title="t", notify_type=NotifyType.INFO) is True
635 assert mock_get.call_count == 2
636 called = "".join(c[0][0] for c in mock_get.call_args_list)
637 assert "/cloud/groups/" in called and "/cloud/users" in called
638
639 # we sent 5 notifications
640 assert mock_post.call_count == 5
641 expected_users = {"a1", "a2", "g1", "g2", "joe"}
642
643 # Extract the user segment from the URL of each call
644 actual_users = {
645 call[0][0].split("/")[-1] for call in mock_post.call_args_list
646 }
647
648 # Assert that the set of actual users matches the set of expected users
649 assert actual_users == expected_users
650
651 # Reset our mock object
652 mock_get.reset_mock()
653 mock_post.reset_mock()
654
655 assert obj.send(body="b2", title="t2", notify_type=NotifyType.INFO) is True
656 # Cached responses were used to get our user information
657 assert mock_get.call_count == 0
658 assert mock_post.call_count == 5
659
660 # We can re-verify our notifications went as expected:
661 actual_users = {
662 call[0][0].split("/")[-1] for call in mock_post.call_args_list
663 }
664
665 # Assert that the set of actual users matches the set of expected users
666 assert actual_users == expected_users