Debian Codegraph @

tests/test_plugin_humhub.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 import logging
30 from unittest import mock
31
32 from helpers import AppriseURLTester
33 import pytest
34 import requests
35
36 from apprise import Apprise
37 from apprise.plugins.humhub import NotifyHumHub
38
39 logging.disable(logging.CRITICAL)
40
41 # Our Testing URLs
42 apprise_url_tests = (
43 # No host
44 (
45 "humhub://",
46 {
47 "instance": None,
48 },
49 ),
50 # Host present but no user/token
51 (
52 "humhub://hostname",
53 {
54 "instance": TypeError,
55 },
56 ),
57 # Token present but no container ID
58 (
59 "humhub://token@hostname",
60 {
61 "instance": TypeError,
62 },
63 ),
64 # Invalid container ID (not numeric)
65 (
66 "humhubs://token@hostname/invalid",
67 {
68 "instance": TypeError,
69 },
70 ),
71 # Negative container ID (not a positive integer)
72 (
73 "humhubs://token@hostname/-1",
74 {
75 "instance": TypeError,
76 },
77 ),
78 # Zero container ID (not a positive integer)
79 (
80 "humhubs://token@hostname/0",
81 {
82 "instance": TypeError,
83 },
84 ),
85 # Valid bearer token + container ID over HTTP (insecure)
86 (
87 "humhub://mytoken@hostname/1",
88 {
89 "instance": NotifyHumHub,
90 "privacy_url": "humhub://m...n@hostname/1/",
91 "requests_response_text": '{"id": 1}',
92 },
93 ),
94 # Valid bearer token + container ID over HTTPS
95 (
96 "humhubs://mytoken@hostname/1",
97 {
98 "instance": NotifyHumHub,
99 "privacy_url": "humhubs://m...n@hostname/1/",
100 "requests_response_text": '{"id": 1}',
101 },
102 ),
103 # Valid basic auth + container ID
104 (
105 "humhubs://user:pass@hostname/1",
106 {
107 "instance": NotifyHumHub,
108 "privacy_url": "humhubs://u...r:****@hostname/1/",
109 "requests_response_text": '{"id": 1}',
110 },
111 ),
112 # Multiple container IDs in the path
113 (
114 "humhubs://mytoken@hostname/1/2/3",
115 {
116 "instance": NotifyHumHub,
117 "requests_response_text": '{"id": 1}',
118 },
119 ),
120 # Container IDs via ?to= parameter
121 (
122 "humhubs://mytoken@hostname/?to=1,2,3",
123 {
124 "instance": NotifyHumHub,
125 "requests_response_text": '{"id": 1}',
126 },
127 ),
128 # Custom port
129 (
130 "humhubs://mytoken@hostname:8443/1",
131 {
132 "instance": NotifyHumHub,
133 "requests_response_text": '{"id": 1}',
134 },
135 ),
136 # HTTP 500 response -- bearer auth
137 (
138 "humhubs://mytoken@hostname/1",
139 {
140 "instance": NotifyHumHub,
141 "response": False,
142 "requests_response_code": requests.codes.internal_server_error,
143 },
144 ),
145 # Unknown error code -- bearer auth
146 (
147 "humhubs://mytoken@hostname/1",
148 {
149 "instance": NotifyHumHub,
150 "response": False,
151 "requests_response_code": 999,
152 },
153 ),
154 # RequestException -- bearer auth
155 (
156 "humhubs://mytoken@hostname/1",
157 {
158 "instance": NotifyHumHub,
159 "test_requests_exceptions": True,
160 },
161 ),
162 # HTTP 500 response -- basic auth
163 (
164 "humhubs://user:pass@hostname/1",
165 {
166 "instance": NotifyHumHub,
167 "response": False,
168 "requests_response_code": requests.codes.internal_server_error,
169 },
170 ),
171 # Unknown error code -- basic auth
172 (
173 "humhubs://user:pass@hostname/1",
174 {
175 "instance": NotifyHumHub,
176 "response": False,
177 "requests_response_code": 999,
178 },
179 ),
180 # RequestException -- basic auth
181 (
182 "humhubs://user:pass@hostname/1",
183 {
184 "instance": NotifyHumHub,
185 "test_requests_exceptions": True,
186 },
187 ),
188 )
189
190
191 def test_plugin_humhub_urls():
192 """NotifyHumHub() Apprise URLs."""
193 AppriseURLTester(tests=apprise_url_tests).run_all()
194
195
196 def test_plugin_humhub_init():
197 """NotifyHumHub() initialization edge cases."""
198
199 # No user/token at all
200 with pytest.raises(TypeError):
201 NotifyHumHub(user=None, host="hostname", targets=["1"])
202
203 # Empty string user
204 with pytest.raises(TypeError):
205 NotifyHumHub(user="", host="hostname", targets=["1"])
206
207 # No containers specified
208 with pytest.raises(TypeError):
209 NotifyHumHub(user="token", host="hostname", targets=[])
210
211 # None targets
212 with pytest.raises(TypeError):
213 NotifyHumHub(user="token", host="hostname", targets=None)
214
215 # Only invalid targets
216 with pytest.raises(TypeError):
217 NotifyHumHub(user="token", host="hostname", targets=["bad", "0", "-5"])
218
219 # Mixed valid and invalid -- should succeed, dropping the bad ones
220 obj = NotifyHumHub(
221 user="token", host="hostname", targets=["1", "bad", "2"]
222 )
223 assert len(obj.targets) == 2
224 assert "1" in obj.targets
225 assert "2" in obj.targets
226 assert len(obj._invalid_targets) == 1
227 assert "bad" in obj._invalid_targets
228
229 # Valid bearer token
230 obj = NotifyHumHub(user="bearertoken", host="hostname", targets=["42"])
231 assert obj.targets == ["42"]
232 assert obj.password is None
233
234 # Valid basic auth
235 obj = NotifyHumHub(
236 user="admin", password="secret", host="hostname", targets=["5"]
237 )
238 assert obj.targets == ["5"]
239 assert obj.password == "secret"
240
241
242 @mock.patch("requests.post")
243 def test_plugin_humhub_bearer_send(mock_post):
244 """NotifyHumHub() bearer token send."""
245
246 # Successful response
247 mock_post.return_value = requests.Request()
248 mock_post.return_value.status_code = requests.codes.ok
249 mock_post.return_value.content = b""
250
251 obj = NotifyHumHub(user="mytoken", host="localhost", targets=["1"])
252 assert obj.notify(body="Test body") is True
253
254 # Confirm bearer token header was set
255 assert mock_post.called
256 _, kwargs = mock_post.call_args
257 assert "Authorization" in kwargs.get("headers", {})
258 assert kwargs["headers"]["Authorization"] == "Bearer mytoken"
259 assert kwargs.get("auth") is None
260
261
262 @mock.patch("requests.post")
263 def test_plugin_humhub_basic_send(mock_post):
264 """NotifyHumHub() basic auth send."""
265
266 # Successful response
267 mock_post.return_value = requests.Request()
268 mock_post.return_value.status_code = requests.codes.ok
269 mock_post.return_value.content = b""
270
271 obj = NotifyHumHub(
272 user="admin", password="secret", host="localhost", targets=["1"]
273 )
274 assert obj.notify(body="Test body") is True
275
276 # Confirm basic auth tuple was passed and no Authorization header
277 assert mock_post.called
278 _, kwargs = mock_post.call_args
279 assert kwargs.get("auth") == ("admin", "secret")
280 assert "Authorization" not in kwargs.get("headers", {})
281
282
283 @mock.patch("requests.post")
284 def test_plugin_humhub_multi_container(mock_post):
285 """NotifyHumHub() multiple container send."""
286
287 mock_post.return_value = requests.Request()
288 mock_post.return_value.status_code = requests.codes.ok
289 mock_post.return_value.content = b""
290
291 obj = NotifyHumHub(user="token", host="localhost", targets=["1", "2", "3"])
292 assert obj.notify(body="Hello") is True
293
294 # One POST per container
295 assert mock_post.call_count == 3
296
297
298 @mock.patch("requests.post")
299 def test_plugin_humhub_partial_failure(mock_post):
300 """NotifyHumHub() partial failure across multiple containers."""
301
302 def side_effect_fn(*args, **kwargs):
303 # Fail on the second call (container "2"), succeed on others
304 if mock_post.call_count == 2:
305 r = requests.Request()
306 r.status_code = requests.codes.internal_server_error
307 r.content = b"error"
308 return r
309 r = requests.Request()
310 r.status_code = requests.codes.ok
311 r.content = b""
312 return r
313
314 mock_post.side_effect = side_effect_fn
315
316 obj = NotifyHumHub(user="token", host="localhost", targets=["1", "2", "3"])
317 # Partial failure means overall False
318 assert obj.notify(body="msg") is False
319 assert mock_post.call_count == 3
320
321
322 @mock.patch("requests.post")
323 def test_plugin_humhub_http_errors(mock_post):
324 """NotifyHumHub() HTTP error responses."""
325
326 # HTTP 401 Unauthorized
327 mock_post.return_value = requests.Request()
328 mock_post.return_value.status_code = 401
329 mock_post.return_value.content = b"Unauthorized"
330
331 obj = NotifyHumHub(user="token", host="localhost", targets=["1"])
332 assert obj.notify(body="msg") is False
333
334 # HTTP 500 Internal Server Error
335 mock_post.return_value.status_code = requests.codes.internal_server_error
336 assert obj.notify(body="msg") is False
337
338 # Unknown / unexpected code
339 mock_post.return_value.status_code = 999
340 assert obj.notify(body="msg") is False
341
342
343 @mock.patch("requests.post")
344 def test_plugin_humhub_request_exception(mock_post):
345 """NotifyHumHub() RequestException handling."""
346
347 mock_post.side_effect = requests.RequestException("Connection refused")
348
349 obj = NotifyHumHub(user="token", host="localhost", targets=["1", "2"])
350 assert obj.notify(body="msg") is False
351 # Both containers attempted
352 assert mock_post.call_count == 2
353
354
355 def test_plugin_humhub_url_round_trip():
356 """NotifyHumHub() URL round-trip invariant."""
357
358 # Bearer token, single container
359 obj1 = NotifyHumHub(user="mytoken", host="myhost", targets=["7"])
360 result = NotifyHumHub.parse_url(obj1.url())
361 obj2 = NotifyHumHub(**result)
362 assert obj1.url_identifier == obj2.url_identifier
363 assert len(obj1.targets) == len(obj2.targets)
364
365 # Basic auth, multiple containers
366 obj1 = NotifyHumHub(
367 user="admin",
368 password="secret",
369 host="myhost",
370 targets=["1", "2", "3"],
371 )
372 result = NotifyHumHub.parse_url(obj1.url())
373 obj2 = NotifyHumHub(**result)
374 assert obj1.url_identifier == obj2.url_identifier
375 assert len(obj1.targets) == len(obj2.targets)
376
377 # Custom port
378 obj1 = NotifyHumHub(user="tok", host="myhost", port=9090, targets=["10"])
379 result = NotifyHumHub.parse_url(obj1.url())
380 obj2 = NotifyHumHub(**result)
381 assert obj1.url_identifier == obj2.url_identifier
382
383 # Invalid targets round-trip inline in path alongside valid ones
384 obj1 = NotifyHumHub(user="tok", host="myhost", targets=["5", "bad", "0"])
385 assert len(obj1.targets) == 1
386 assert len(obj1._invalid_targets) == 2
387 # url() emits valid + invalid targets together in the path
388 generated = obj1.url()
389 assert "bad" in generated
390 assert "0" in generated
391 result = NotifyHumHub.parse_url(generated)
392 obj2 = NotifyHumHub(**result)
393 # obj2 re-validates: valid target "5" survives, invalid ones re-land in
394 # _invalid_targets so the overall target count is the same
395 assert len(obj2.targets) == 1
396
397
398 def test_plugin_humhub_url_parsing():
399 """NotifyHumHub() parse_url edge cases."""
400
401 # Bearer token from path and ?to= combined
402 result = NotifyHumHub.parse_url("humhubs://mytoken@hostname/1/?to=2,3")
403 assert result is not None
404 assert "1" in result["targets"]
405 assert "2" in result["targets"]
406 assert "3" in result["targets"]
407
408 # Basic auth
409 result = NotifyHumHub.parse_url("humhubs://user:pass@hostname/42")
410 assert result is not None
411 assert result["user"] == "user"
412 assert result["password"] == "pass"
413 assert "42" in result["targets"]
414
415 # Empty / invalid URL returns None (no host)
416 assert NotifyHumHub.parse_url("humhubs://") is None
417 # Only host, no user -- parse_url succeeds; TypeError raised at init
418 result = NotifyHumHub.parse_url("humhubs://hostname/1")
419 assert result is not None
420
421
422 def test_plugin_humhub_privacy_url():
423 """NotifyHumHub() privacy URL masking."""
424
425 obj = NotifyHumHub(user="secrettoken", host="myhost", targets=["1"])
426 priv = obj.url(privacy=True)
427 assert "secrettoken" not in priv
428 assert "myhost" in priv
429
430 obj2 = NotifyHumHub(
431 user="admin", password="topsecret", host="myhost", targets=["1"]
432 )
433 priv2 = obj2.url(privacy=True)
434 assert "topsecret" not in priv2
435 assert "admin" not in priv2 or "****" in priv2
436
437
438 @mock.patch("requests.post")
439 def test_plugin_humhub_apprise_integration(mock_post):
440 """NotifyHumHub() Apprise integration."""
441
442 mock_post.return_value = requests.Request()
443 mock_post.return_value.status_code = requests.codes.ok
444 mock_post.return_value.content = b""
445
446 aobj = Apprise()
447 assert aobj.add("humhubs://mytoken@localhost/1")
448 assert aobj.notify(title="Title", body="Body") is True
449
450 aobj2 = Apprise()
451 assert aobj2.add("humhubs://user:pass@localhost/1")
452 assert aobj2.notify(title="Title", body="Body") is True
453
454
455 @mock.patch("requests.post")
456 def test_plugin_humhub_attachment_success(mock_post):
457 """NotifyHumHub() attachment upload success."""
458 from io import BytesIO
459
460 # First response: post creation with a post ID
461 create_resp = requests.Request()
462 create_resp.status_code = requests.codes.ok
463 create_resp.content = b'{"id": 42}'
464
465 # Second response: attachment upload success
466 upload_resp = requests.Request()
467 upload_resp.status_code = requests.codes.ok
468 upload_resp.content = b"{}"
469
470 mock_post.side_effect = [create_resp, upload_resp]
471
472 # Build a mock accessible attachment
473 attachment = mock.MagicMock()
474 attachment.__bool__ = mock.MagicMock(return_value=True)
475 attachment.name = "test.png"
476 attachment.open = mock.MagicMock(return_value=BytesIO(b"image data"))
477
478 obj = NotifyHumHub(user="token", host="localhost", targets=["1"])
479 assert obj.send(body="Test body", attach=[attachment]) is True
480 # Post creation + file upload
481 assert mock_post.call_count == 2
482
483
484 @mock.patch("requests.post")
485 def test_plugin_humhub_attachment_multiple(mock_post):
486 """NotifyHumHub() multiple attachments all uploaded."""
487 from io import BytesIO
488
489 # Post creation returns a post ID
490 create_resp = requests.Request()
491 create_resp.status_code = requests.codes.ok
492 create_resp.content = b'{"id": 10}'
493
494 # Three attachment upload responses
495 upload_resp = requests.Request()
496 upload_resp.status_code = requests.codes.ok
497 upload_resp.content = b"{}"
498
499 mock_post.side_effect = [
500 create_resp,
501 upload_resp,
502 upload_resp,
503 upload_resp,
504 ]
505
506 def make_attach(name):
507 """Build a mock accessible attachment."""
508 a = mock.MagicMock()
509 a.__bool__ = mock.MagicMock(return_value=True)
510 a.name = name
511 a.open = mock.MagicMock(return_value=BytesIO(b"data"))
512 return a
513
514 attachments = [
515 make_attach("a.png"),
516 make_attach("b.png"),
517 make_attach("c.png"),
518 ]
519
520 obj = NotifyHumHub(user="token", host="localhost", targets=["1"])
521 assert obj.send(body="msg", attach=attachments) is True
522 # 1 creation + 3 uploads
523 assert mock_post.call_count == 4
524
525
526 @mock.patch("requests.post")
527 def test_plugin_humhub_attachment_inaccessible(mock_post):
528 """NotifyHumHub() inaccessible attachment marks failure."""
529
530 # Post creation succeeds with a post ID
531 create_resp = requests.Request()
532 create_resp.status_code = requests.codes.ok
533 create_resp.content = b'{"id": 7}'
534 mock_post.return_value = create_resp
535
536 # Build a mock inaccessible attachment (falsy)
537 attachment = mock.MagicMock()
538 attachment.__bool__ = mock.MagicMock(return_value=False)
539 attachment.url = mock.MagicMock(return_value="file:///tmp/missing")
540
541 obj = NotifyHumHub(user="token", host="localhost", targets=["1"])
542 assert obj.send(body="msg", attach=[attachment]) is False
543 # Only the post creation call was made; upload skipped
544 assert mock_post.call_count == 1
545
546
547 @mock.patch("requests.post")
548 def test_plugin_humhub_attachment_no_post_id(mock_post):
549 """NotifyHumHub() handles missing post ID in creation response."""
550
551 # Post creation returns 200 but no "id" field in the response body
552 create_resp = requests.Request()
553 create_resp.status_code = requests.codes.ok
554 create_resp.content = b"{}"
555 mock_post.return_value = create_resp
556
557 attachment = mock.MagicMock()
558 attachment.__bool__ = mock.MagicMock(return_value=True)
559
560 obj = NotifyHumHub(user="token", host="localhost", targets=["1"])
561 assert obj.send(body="msg", attach=[attachment]) is False
562 # Only the post creation call was made; no upload attempted
563 assert mock_post.call_count == 1
564
565
566 @mock.patch("requests.post")
567 def test_plugin_humhub_attachment_bad_json_response(mock_post):
568 """NotifyHumHub() handles unparseable post creation response."""
569
570 # Post creation returns 200 but a non-JSON body
571 create_resp = requests.Request()
572 create_resp.status_code = requests.codes.ok
573 create_resp.content = b"not json"
574 mock_post.return_value = create_resp
575
576 attachment = mock.MagicMock()
577 attachment.__bool__ = mock.MagicMock(return_value=True)
578
579 obj = NotifyHumHub(user="token", host="localhost", targets=["1"])
580 assert obj.send(body="msg", attach=[attachment]) is False
581 assert mock_post.call_count == 1
582
583
584 @mock.patch("requests.post")
585 def test_plugin_humhub_attachment_upload_failure(mock_post):
586 """NotifyHumHub() attachment upload HTTP failure."""
587 from io import BytesIO
588
589 # Post creation succeeds
590 create_resp = requests.Request()
591 create_resp.status_code = requests.codes.ok
592 create_resp.content = b'{"id": 3}'
593
594 # Attachment upload returns HTTP 500
595 upload_resp = requests.Request()
596 upload_resp.status_code = requests.codes.internal_server_error
597 upload_resp.content = b"error"
598
599 mock_post.side_effect = [create_resp, upload_resp]
600
601 attachment = mock.MagicMock()
602 attachment.__bool__ = mock.MagicMock(return_value=True)
603 attachment.name = "report.pdf"
604 attachment.open = mock.MagicMock(return_value=BytesIO(b"pdf data"))
605
606 obj = NotifyHumHub(user="token", host="localhost", targets=["1"])
607 assert obj.send(body="msg", attach=[attachment]) is False
608 assert mock_post.call_count == 2
609
610
611 @mock.patch("requests.post")
612 def test_plugin_humhub_attachment_request_exception(mock_post):
613 """NotifyHumHub() RequestException during attachment upload."""
614 from io import BytesIO
615
616 # Post creation succeeds
617 create_resp = requests.Request()
618 create_resp.status_code = requests.codes.ok
619 create_resp.content = b'{"id": 5}'
620
621 # Upload raises RequestException
622 mock_post.side_effect = [
623 create_resp,
624 requests.RequestException("Connection refused"),
625 ]
626
627 attachment = mock.MagicMock()
628 attachment.__bool__ = mock.MagicMock(return_value=True)
629 attachment.name = "file.txt"
630 attachment.open = mock.MagicMock(return_value=BytesIO(b"text data"))
631
632 obj = NotifyHumHub(user="token", host="localhost", targets=["1"])
633 assert obj.send(body="msg", attach=[attachment]) is False
634
635
636 @mock.patch("requests.post")
637 def test_plugin_humhub_attachment_oserror(mock_post):
638 """NotifyHumHub() OSError when opening attachment file."""
639
640 # Post creation succeeds
641 create_resp = requests.Request()
642 create_resp.status_code = requests.codes.ok
643 create_resp.content = b'{"id": 8}'
644 mock_post.return_value = create_resp
645
646 # Attachment open() raises OSError before requests.post is reached
647 attachment = mock.MagicMock()
648 attachment.__bool__ = mock.MagicMock(return_value=True)
649 attachment.name = "secret.key"
650 attachment.open = mock.MagicMock(side_effect=OSError("Permission denied"))
651
652 obj = NotifyHumHub(user="token", host="localhost", targets=["1"])
653 assert obj.send(body="msg", attach=[attachment]) is False
654 # OSError fires inside _send() before requests.post; only creation hit
655 assert mock_post.call_count == 1