Debian Codegraph @

tests/test_plugin_mattermost.py

raw
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 import json
29
30 # Disable logging for a cleaner testing output
31 import logging
32 import os
33 from unittest import mock
34
35 from helpers import AppriseURLTester
36 import pytest
37 import requests
38
39 from apprise import Apprise, AppriseAttachment
40 from apprise.exception import AppriseImproperlyConfigured
41 from apprise.plugins.mattermost import MattermostMode, NotifyMattermost
42
43 # Attachment test fixtures
44 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
45
46 logging.disable(logging.CRITICAL)
47
48 # Our Testing URLs
49 apprise_url_tests = (
50 ("mmost://", {"instance": None}),
51 ("mmosts://", {"instance": None}),
52 ("mmost://:@/", {"instance": None}),
53 (
54 "mmosts://localhost",
55 {
56 # Thrown because there was no webhook id specified
57 "instance": AppriseImproperlyConfigured,
58 },
59 ),
60 (
61 "mmost://localhost/3ccdd113474722377935511fc85d3dd4",
62 {
63 "instance": NotifyMattermost,
64 },
65 ),
66 (
67 (
68 "mmost://localhost/3ccdd113474722377935511fc85d3dd4"
69 "?icon_url=http://localhost/test.png"
70 ),
71 {
72 "instance": NotifyMattermost,
73 },
74 ),
75 (
76 "mmost://user@localhost/3ccdd113474722377935511fc85d3dd4?channel=test",
77 {
78 "instance": NotifyMattermost,
79 },
80 ),
81 (
82 (
83 "mmost://user@localhost/3ccdd113474722377935511fc85d3dd4"
84 "?channels=test"
85 ),
86 {
87 "instance": NotifyMattermost,
88 },
89 ),
90 (
91 "mmost://user@localhost/3ccdd113474722377935511fc85d3dd4?to=test",
92 {
93 "instance": NotifyMattermost,
94 # Our expected url(privacy=True) startswith() response:
95 "privacy_url": "mmost://user@localhost/3...4/",
96 },
97 ),
98 (
99 (
100 "mmost://localhost/3ccdd113474722377935511fc85d3dd4"
101 "?to=test&image=True"
102 ),
103 {"instance": NotifyMattermost},
104 ),
105 (
106 (
107 # Team defined implies bot mode
108 "mmost://localhost/3ccdd113474722377935511fc85d3dd4"
109 "?to=test&team=chester"
110 ),
111 {
112 "instance": NotifyMattermost,
113 # Provide valid upload response so the attachment test passes
114 "requests_response_text": '{"file_infos": [{"id": "abc"}]}',
115 },
116 ),
117 (
118 (
119 # sets botname on webhook
120 "mmost://localhost/3ccdd113474722377935511fc85d3dd4"
121 "?to=general&botname=foobar"
122 ),
123 {"instance": NotifyMattermost},
124 ),
125 (
126 (
127 "mmost://team@localhost/3ccdd113474722377935511fc85d3dd4"
128 "?channel=$!garbag3^&mode=bot"
129 ),
130 {
131 "instance": NotifyMattermost,
132 # We will fail to notify anyone due to the bad entry
133 "notify_response": False,
134 },
135 ),
136 (
137 (
138 "mmost://localhost/3ccdd113474722377935511fc85d3dd4"
139 "?to=test&image=False"
140 ),
141 {"instance": NotifyMattermost},
142 ),
143 (
144 (
145 "mmost://localhost/3ccdd113474722377935511fc85d3dd4"
146 "?to=test&image=True"
147 ),
148 {
149 "instance": NotifyMattermost,
150 # don't include an image by default
151 "include_image": False,
152 },
153 ),
154 (
155 "mmost://localhost:8080/3ccdd113474722377935511fc85d3dd4",
156 {
157 "instance": NotifyMattermost,
158 # Our expected url(privacy=True) startswith() response:
159 "privacy_url": "mmost://localhost:8080/3...4/",
160 },
161 ),
162 (
163 "mmost://localhost:8080/3ccdd113474722377935511fc85d3dd4",
164 {
165 "instance": NotifyMattermost,
166 },
167 ),
168 (
169 "mmost://localhost:invalid-port/3ccdd113474722377935511fc85d3dd4",
170 {
171 "instance": None,
172 },
173 ),
174 (
175 "mmosts://localhost/3ccdd113474722377935511fc85d3dd4",
176 {
177 "instance": NotifyMattermost,
178 },
179 ),
180 (
181 (
182 "https://mattermost.example.com/hooks/"
183 "3ccdd113474722377935511fc85d3dd4"
184 ),
185 {
186 "instance": NotifyMattermost,
187 # Our expected url(privacy=True) startswith() response:
188 "privacy_url": "mmosts://mattermost.example.com/3...4/",
189 },
190 ),
191 # Test our paths
192 (
193 "mmosts://localhost/a/path/3ccdd113474722377935511fc85d3dd4",
194 {"instance": NotifyMattermost},
195 ),
196 (
197 "mmosts://localhost/////3ccdd113474722377935511fc85d3dd4///",
198 {"instance": NotifyMattermost},
199 ),
200 # Mode parsing (prefix support)
201 ("mmost://localhost/token?mode=w", {"instance": NotifyMattermost}),
202 (
203 "mmost://localhost/token?mode=b&to=channel-id-1",
204 {
205 "instance": NotifyMattermost,
206 # Provide valid upload response so the attachment test passes
207 "requests_response_text": '{"file_infos": [{"id": "abc"}]}',
208 },
209 ),
210 (
211 "mmost://localhost/token?mode=invalid",
212 {
213 # invalid mode is detected in __init__
214 "instance": AppriseImproperlyConfigured,
215 },
216 ),
217 (
218 "mmosts://localhost/a/path/3ccdd113474722377935511fc85d3dd4",
219 {
220 "instance": NotifyMattermost,
221 },
222 ),
223 (
224 "mmosts://localhost/////3ccdd113474722377935511fc85d3dd4///",
225 {
226 "instance": NotifyMattermost,
227 },
228 ),
229 (
230 "mmost://localhost/3ccdd113474722377935511fc85d3dd4",
231 {
232 "instance": NotifyMattermost,
233 # force a failure
234 "response": False,
235 "requests_response_code": requests.codes.internal_server_error,
236 },
237 ),
238 (
239 "mmost://localhost/3ccdd113474722377935511fc85d3dd4",
240 {
241 "instance": NotifyMattermost,
242 # throw a bizarre code forcing us to fail to look it up
243 "response": False,
244 "requests_response_code": 999,
245 },
246 ),
247 (
248 "mmost://localhost/3ccdd113474722377935511fc85d3dd4",
249 {
250 "instance": NotifyMattermost,
251 # Throws a series of i/o exceptions with this flag
252 # is set and tests that we gracefully handle them
253 "test_requests_exceptions": True,
254 },
255 ),
256 )
257
258
259 @pytest.fixture
260 def request_get_mock(mocker):
261 """Prepare requests.get mock."""
262 mock_get = mocker.patch("requests.get")
263 mock_get.return_value = requests.Request()
264 mock_get.return_value.status_code = requests.codes.ok
265 mock_get.return_value.content = b'{"id":"abc123"}'
266 return mock_get
267
268
269 @pytest.fixture
270 def request_post_mock(mocker):
271 """Prepare requests mock."""
272 mock_post = mocker.patch("requests.post")
273 mock_post.return_value = requests.Request()
274 mock_post.return_value.status_code = requests.codes.ok
275 mock_post.return_value.content = b""
276 return mock_post
277
278
279 def test_plugin_mattermost_urls():
280 """NotifyMattermost() Apprise URLs."""
281
282 # Run our general tests
283 AppriseURLTester(tests=apprise_url_tests).run_all()
284
285
286 def test_plugin_mattermost_edge_cases():
287 """NotifyMattermost() Edge Cases."""
288
289 # Invalid Authorization Token
290 with pytest.raises(AppriseImproperlyConfigured):
291 NotifyMattermost(None)
292 with pytest.raises(AppriseImproperlyConfigured):
293 NotifyMattermost(" ")
294
295
296 def test_plugin_mattermost_len_webhook_and_bot(
297 request_post_mock, request_get_mock
298 ):
299 """NotifyMattermost() __len__() behaviour."""
300 # webhook: no channels -> 1
301 obj = Apprise.instantiate("mmost://localhost/token")
302 assert isinstance(obj, NotifyMattermost)
303 assert obj.mode == MattermostMode.WEBHOOK
304 assert len(obj) == 1
305
306 # webhook: channels -> count
307 obj = Apprise.instantiate("mmost://localhost/token?channels=a,b,c")
308 assert isinstance(obj, NotifyMattermost)
309 assert obj.mode == MattermostMode.WEBHOOK
310 assert len(obj) == 3
311
312 # bot: channels are channel_id values -> count
313 obj = Apprise.instantiate("mmost://localhost/token?mode=bot&to=id1,id2")
314 assert isinstance(obj, NotifyMattermost)
315 assert obj.mode == MattermostMode.BOT
316 assert len(obj) == 2
317 assert bool(obj.notify("test")) is True
318 assert "mode=bot" in obj.url()
319
320 # bot: channels are channel_id values -> count
321 obj = Apprise.instantiate("mmost://localhost/token?mode=bot&to=#chan,id1")
322 assert isinstance(obj, NotifyMattermost)
323 assert obj.mode == MattermostMode.BOT
324 # our #chan isn't added to the list because no team was provided
325 assert len(obj) == 1
326 assert bool(obj.notify("test")) is True
327 assert "mode=bot" in obj.url()
328
329 obj = Apprise.instantiate("mmost://localhost/token?mode=bot&to=#chan")
330 assert isinstance(obj, NotifyMattermost)
331 assert obj.mode == MattermostMode.BOT
332 # No one to notify (but we always return a minimum of 1)
333 assert len(obj) == 1
334 assert bool(obj.notify("test")) is False
335 assert "mode=bot" in obj.url()
336
337 obj = Apprise.instantiate(
338 "mmost://team@localhost/token?mode=bot&to=#chan,id1"
339 )
340 assert isinstance(obj, NotifyMattermost)
341 assert obj.mode == MattermostMode.BOT
342 assert len(obj) == 2
343 # We can look up the team now
344 assert bool(obj.notify("test")) is True
345 assert "mode=bot" in obj.url()
346 # Second call to notify() pulls from cache
347 assert bool(obj.notify("test")) is True
348
349 obj = Apprise.instantiate(
350 "mmost://team@localhost/token?mode=bot&to=#chan,id1"
351 )
352 assert isinstance(obj, NotifyMattermost)
353 assert obj.mode == MattermostMode.BOT
354 # Invalid response
355 request_get_mock.return_value.content = b"}"
356 assert bool(obj.notify("test")) is False
357
358 obj = Apprise.instantiate(
359 "mmost://team@localhost/token?mode=bot&to=#chan,id1"
360 )
361 assert isinstance(obj, NotifyMattermost)
362 assert obj.mode == MattermostMode.BOT
363 # empty response
364 request_get_mock.return_value.content = b"{}"
365 assert bool(obj.notify("test")) is False
366
367 obj = Apprise.instantiate(
368 "mmost://team@localhost/token?mode=bot&to=#chan,id1"
369 )
370 assert isinstance(obj, NotifyMattermost)
371 assert obj.mode == MattermostMode.BOT
372 # upstream inquiry failure
373 request_get_mock.side_effect = requests.RequestException
374 assert bool(obj.notify("test")) is False
375
376
377 def test_plugin_mattermost_channels(request_post_mock):
378 """NotifyMattermost() Channel Testing."""
379
380 # Test channels with/without hashtag (#)
381 user = "user1"
382 token = "token"
383 channels = ["#one", "two"]
384
385 # Instantiate our URL
386 obj = Apprise.instantiate(
387 "mmost://{user}@localhost:8065/{token}?channels={channels}".format(
388 user=user, token=token, channels=",".join(channels)
389 )
390 )
391
392 assert isinstance(obj, NotifyMattermost)
393 assert bool(obj.notify(body="body", title="title")) is True
394
395 assert request_post_mock.called is True
396 assert request_post_mock.call_count == 2
397 assert request_post_mock.call_args_list[0][0][0].startswith(
398 "http://localhost:8065/hooks/token"
399 )
400
401 # Our Posted JSON Object
402 posted_json = json.loads(request_post_mock.call_args_list[0][1]["data"])
403 assert "username" in posted_json
404 assert "channel" in posted_json
405 assert "text" in posted_json
406 assert posted_json["username"] == "user1"
407 assert posted_json["channel"] == "one"
408 assert posted_json["text"] == "title\r\nbody"
409
410 # Our second Posted JSON Object
411 posted_json = json.loads(request_post_mock.call_args_list[1][1]["data"])
412 assert posted_json["username"] == "user1"
413 assert posted_json["channel"] == "two"
414 assert posted_json["text"] == "title\r\nbody"
415
416
417 def test_mattermost_post_default_port(request_post_mock):
418 """Verify webhook delivery uses the default Mattermost port."""
419 # Test token
420 token = "token"
421
422 # Instantiate our URL
423 obj = Apprise.instantiate(f"mmosts://mattermost.example.com/{token}")
424
425 assert isinstance(obj, NotifyMattermost)
426 assert bool(obj.notify(body="body", title="title")) is True
427
428 # Make sure we don't use port if not provided
429 assert request_post_mock.called is True
430 assert request_post_mock.call_count == 1
431 assert request_post_mock.call_args_list[0][0][0].startswith(
432 "https://mattermost.example.com/hooks/token"
433 )
434
435 # Our Posted JSON Object
436 posted_json = json.loads(request_post_mock.call_args_list[0][1]["data"])
437 assert "text" in posted_json
438 assert posted_json["text"] == "title\r\nbody"
439
440
441 def test_mattermost_icon_override(request_post_mock):
442 """Verify a configured icon URL is included in the webhook payload."""
443 # Test token
444 token = "token"
445 icon_url = "http://localhost/test.png"
446
447 # Instantiate our URL with an icon override
448 obj = Apprise.instantiate(
449 "mmost://mattermost.example.com/{token}?icon_url={icon_url}".format(
450 token=token,
451 icon_url=icon_url,
452 )
453 )
454
455 assert isinstance(obj, NotifyMattermost)
456 assert bool(obj.notify(body="body", title="title")) is True
457
458 assert request_post_mock.called is True
459 assert request_post_mock.call_count == 1
460
461 # Our Posted JSON Object
462 posted_json = json.loads(request_post_mock.call_args_list[0][1]["data"])
463 assert posted_json["icon_url"] == icon_url
464
465
466 def test_plugin_mattermost_webhook_payload_variants(request_post_mock, mocker):
467 """Webhook mode covers icon_url vs include_image branches, and optional
468 channel."""
469 # Force image_url() to be deterministic for coverage
470 mocker.patch.object(
471 NotifyMattermost, "image_url", return_value="http://img/ok.png"
472 )
473
474 # Case 1: include_image=True (default) and no icon_url -> icon_url from
475 obj = Apprise.instantiate("mmost://user@localhost/token?to=test")
476 assert isinstance(obj, NotifyMattermost)
477 assert obj.mode == MattermostMode.WEBHOOK
478 assert bool(obj.notify(body="body", title="title")) is True
479
480 posted_json = json.loads(request_post_mock.call_args_list[-1][1]["data"])
481 assert posted_json["username"] == "user"
482 assert posted_json["channel"] == "test"
483 assert posted_json["text"] == "title\r\nbody"
484 assert posted_json["icon_url"] == "http://img/ok.png"
485
486 # Case 2: icon_url overrides include_image
487 request_post_mock.reset_mock()
488 obj = Apprise.instantiate(
489 "mmost://user@localhost/token?to=test&icon_url=http://x/icon.png"
490 )
491 assert isinstance(obj, NotifyMattermost)
492 assert bool(obj.notify(body="body", title="title")) is True
493
494 posted_json = json.loads(request_post_mock.call_args_list[0][1]["data"])
495 assert posted_json["icon_url"] == "http://x/icon.png"
496
497 # Case 3: no channels specified -> payload has no channel key
498 request_post_mock.reset_mock()
499 obj = Apprise.instantiate("mmost://user@localhost/token")
500 assert isinstance(obj, NotifyMattermost)
501 assert bool(obj.notify(body="body", title="title")) is True
502
503 posted_json = json.loads(request_post_mock.call_args_list[0][1]["data"])
504 assert "channel" not in posted_json
505
506
507 def test_plugin_mattermost_webhook_http_error_and_exception(
508 request_post_mock, mocker
509 ):
510 """Webhook mode error paths."""
511 obj = Apprise.instantiate("mmost://localhost/token?to=test")
512 assert isinstance(obj, NotifyMattermost)
513 assert obj.mode == MattermostMode.WEBHOOK
514
515 # HTTP error
516 request_post_mock.return_value.status_code = requests.codes.bad_request
517 assert bool(obj.notify(body="body", title="title")) is False
518
519 # Request exception
520 request_post_mock.reset_mock()
521 request_post_mock.side_effect = requests.RequestException("boom")
522 assert bool(obj.notify(body="body", title="title")) is False
523
524
525 def test_plugin_mattermost_bot_mode_success_and_payload(request_post_mock):
526 """Bot mode success path, headers and payload."""
527 bearer = "bearerToken"
528 channel_id = "channel-id-123"
529
530 obj = Apprise.instantiate(
531 f"mmosts://mattermost.example.com/{bearer}?mode=bot&to={channel_id}"
532 )
533 assert isinstance(obj, NotifyMattermost)
534 assert obj.mode == MattermostMode.BOT
535
536 # Mattermost returns 201 Created for /api/v4/posts
537 request_post_mock.return_value.status_code = requests.codes.created
538
539 assert bool(obj.notify(body="body", title="title")) is True
540 assert request_post_mock.called is True
541 assert request_post_mock.call_count == 1
542
543 url = request_post_mock.call_args_list[0][0][0]
544 assert url.startswith("https://mattermost.example.com/api/v4/posts")
545
546 headers = request_post_mock.call_args_list[0][1]["headers"]
547 assert headers.get("Authorization") == f"Bearer {bearer}"
548
549 posted_json = json.loads(request_post_mock.call_args_list[0][1]["data"])
550 assert posted_json["channel_id"] == channel_id
551 assert posted_json["message"] == "title\r\nbody"
552 assert "text" not in posted_json
553
554
555 def test_plugin_mattermost_bot_mode_requires_channel_id(request_post_mock):
556 """Bot mode requires at least one channel_id target."""
557 bearer = "bearerToken"
558 obj = Apprise.instantiate(f"mmost://localhost/{bearer}?mode=bot")
559 assert isinstance(obj, NotifyMattermost)
560 assert obj.mode == MattermostMode.BOT
561
562 request_post_mock.return_value.status_code = requests.codes.created
563 assert bool(obj.notify(body="body", title="title")) is False
564 assert request_post_mock.called is False
565
566
567 def test_plugin_mattermost_bot_mode_http_error_and_exception(
568 request_post_mock,
569 ):
570 """Bot mode error paths."""
571 bearer = "bearerToken"
572 obj = Apprise.instantiate(f"mmost://localhost/{bearer}?mode=bot&to=id1")
573 assert isinstance(obj, NotifyMattermost)
574 assert obj.mode == MattermostMode.BOT
575
576 # HTTP error (not 201)
577 request_post_mock.return_value.status_code = requests.codes.unauthorized
578 assert bool(obj.notify(body="body", title="title")) is False
579
580 # Request exception
581 request_post_mock.reset_mock()
582 request_post_mock.side_effect = requests.RequestException("boom")
583 assert bool(obj.notify(body="body", title="title")) is False
584
585
586 def test_plugin_mattermost_bot_channel_lookup_success(
587 request_post_mock, request_get_mock
588 ):
589 """Bot mode resolves #channel via team lookup."""
590 bearer = "bearerToken"
591 team = "myteam"
592 channel = "#general"
593 channel_id = "cid123"
594
595 # Mock channel lookup response
596 request_get_mock.return_value.content = json.dumps(
597 {"id": channel_id}
598 ).encode("utf-8")
599
600 obj = Apprise.instantiate(
601 "mmost://localhost/{bearer}?mode=bot&team={team}&to={chan}".format(
602 bearer=bearer, team=team, chan=channel
603 )
604 )
605 assert isinstance(obj, NotifyMattermost)
606 assert obj.mode == MattermostMode.BOT
607
608 request_post_mock.return_value.status_code = requests.codes.created
609 assert bool(obj.notify(body="body", title="title")) is True
610
611 assert request_get_mock.called is True
612 get_url = request_get_mock.call_args_list[0][0][0]
613 assert "/api/v4/teams/name/" in get_url
614 assert "/channels/name/" in get_url
615
616 posted_json = json.loads(request_post_mock.call_args_list[0][1]["data"])
617 assert posted_json["channel_id"] == channel_id
618 assert posted_json["message"] == "title\r\nbody"
619
620
621 def test_plugin_mattermost_bot_channel_lookup_partial_success(
622 request_post_mock, request_get_mock
623 ):
624 """One lookup fails, one succeeds, overall result is False."""
625 bearer = "bearerToken"
626 team = "myteam"
627
628 def side_effect(*args, **kwargs):
629 r = requests.Request()
630 url = args[0]
631 if url.endswith("/channels/name/good"):
632 r.status_code = requests.codes.ok
633 r.content = b'{"id":"cid-good"}'
634 else:
635 r.status_code = requests.codes.not_found
636 r.content = b""
637 return r
638
639 request_get_mock.side_effect = side_effect
640
641 obj = Apprise.instantiate(
642 "mmost://localhost/{bearer}?mode=bot&team={team}&to=#good,#bad".format(
643 bearer=bearer, team=team
644 )
645 )
646 assert isinstance(obj, NotifyMattermost)
647 request_post_mock.return_value.status_code = requests.codes.created
648
649 assert bool(obj.notify(body="body", title="title")) is False
650 assert request_post_mock.call_count == 1
651 posted_json = json.loads(request_post_mock.call_args_list[0][1]["data"])
652 assert posted_json["channel_id"] == "cid-good"
653
654
655 def test_plugin_mattermost_webhook_attachment_warning(request_post_mock):
656 """Webhook mode has attachment_support=False; pipeline drops attach."""
657 obj = Apprise.instantiate("mmost://localhost/token")
658 assert isinstance(obj, NotifyMattermost)
659 assert obj.mode == MattermostMode.WEBHOOK
660 assert obj.attachment_support is False
661
662 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
663
664 # Pipeline silently drops the attachment; text message still succeeds
665 assert bool(obj.notify(body="body", title="title", attach=attach)) is True
666 assert request_post_mock.call_count == 1
667
668 # No file upload should have been attempted
669 assert "files" not in str(request_post_mock.call_args)
670
671
672 def test_plugin_mattermost_webhook_botname_in_url(request_post_mock):
673 """Webhook botname is the {user}@ URL prefix; ?botname= is an alias."""
674 # Both input forms resolve to the same object
675 obj = Apprise.instantiate("mmost://mybot@localhost/token?to=general")
676 obj2 = Apprise.instantiate(
677 "mmost://localhost/token?botname=mybot&to=general"
678 )
679 assert isinstance(obj, NotifyMattermost)
680 assert isinstance(obj2, NotifyMattermost)
681 assert obj.mode == MattermostMode.WEBHOOK
682 assert obj.user == "mybot"
683 assert obj2.user == "mybot"
684
685 # url() uses the {user}@ prefix -- consistent with all Apprise plugins
686 url = obj.url()
687 assert "mybot@" in url
688 assert "botname" not in url
689
690 # Round-trip preserves the botname
691 obj3 = Apprise.instantiate(url)
692 assert isinstance(obj3, NotifyMattermost)
693 assert obj3.user == "mybot"
694 assert obj3.mode == MattermostMode.WEBHOOK
695
696 # Webhook payload carries username = botname
697 request_post_mock.return_value.status_code = requests.codes.ok
698 assert bool(obj.notify(body="body", title="title")) is True
699 posted = json.loads(request_post_mock.call_args_list[0][1]["data"])
700 assert posted["username"] == "mybot"
701
702
703 def test_plugin_mattermost_bot_team_in_url(request_post_mock):
704 """Bot mode team is the {user}@ URL prefix; ?team= is an alias."""
705 obj = Apprise.instantiate("mmost://myteam@localhost/token?mode=bot&to=id1")
706 assert isinstance(obj, NotifyMattermost)
707 assert obj.mode == MattermostMode.BOT
708 assert obj.user == "myteam"
709
710 # url() uses {user}@ prefix for the team too
711 url = obj.url()
712 assert "myteam@" in url
713 assert "mode=bot" in url
714
715
716 def test_plugin_mattermost_bot_attachments(request_post_mock):
717 """Bot mode uploads attachments and includes file_ids in the post."""
718 bearer = "bearerToken"
719 channel_id = "channel-id-123"
720 file_id = "uploaded-file-id-abc"
721
722 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
723
724 def _mk_resp(content, code=requests.codes.ok):
725 r = requests.Request()
726 r.status_code = code
727 r.content = content
728 return r
729
730 upload_resp = _mk_resp(
731 json.dumps({"file_infos": [{"id": file_id}]}).encode("utf-8")
732 )
733 post_resp = _mk_resp(b"{}", requests.codes.created)
734
735 request_post_mock.side_effect = [upload_resp, post_resp]
736
737 obj = Apprise.instantiate(
738 f"mmost://localhost/{bearer}?mode=bot&to={channel_id}"
739 )
740 assert isinstance(obj, NotifyMattermost)
741 assert obj.mode == MattermostMode.BOT
742
743 assert bool(obj.notify(body="body", title="title", attach=attach)) is True
744 assert request_post_mock.call_count == 2
745
746 # First call is the file upload
747 upload_call = request_post_mock.call_args_list[0]
748 assert "/api/v4/files" in upload_call[0][0]
749 assert upload_call[1]["data"] == {"channel_id": channel_id}
750 assert "files" in upload_call[1]["files"]
751
752 # Second call is the post; it must include file_ids
753 post_call = request_post_mock.call_args_list[1]
754 assert "/api/v4/posts" in post_call[0][0]
755 post_json = json.loads(post_call[1]["data"])
756 assert post_json["file_ids"] == [file_id]
757 assert post_json["message"] == "title\r\nbody"
758 assert post_json["channel_id"] == channel_id
759
760
761 def test_plugin_mattermost_bot_multi_attach_multi_target(request_post_mock):
762 """Multiple attachments and multiple targets each get their own uploads."""
763 bearer = "bearerToken"
764 ch1 = "channel-001"
765 ch2 = "channel-002"
766 fid1 = "fid-001"
767 fid2 = "fid-002"
768
769 attach = AppriseAttachment()
770 attach.add(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
771 attach.add(os.path.join(TEST_VAR_DIR, "apprise-test.png"))
772
773 def _mk_upload(fid):
774 r = requests.Request()
775 r.status_code = requests.codes.ok
776 r.content = json.dumps({"file_infos": [{"id": fid}]}).encode("utf-8")
777 return r
778
779 def _mk_post():
780 r = requests.Request()
781 r.status_code = requests.codes.created
782 r.content = b"{}"
783 return r
784
785 # 2 attachments x 2 targets = 4 upload calls + 2 post calls
786 request_post_mock.side_effect = [
787 _mk_upload(fid1),
788 _mk_upload(fid2),
789 _mk_post(),
790 _mk_upload(fid1),
791 _mk_upload(fid2),
792 _mk_post(),
793 ]
794
795 obj = Apprise.instantiate(
796 "mmost://localhost/{b}?mode=bot&to={c1},{c2}".format(
797 b=bearer, c1=ch1, c2=ch2
798 )
799 )
800 assert isinstance(obj, NotifyMattermost)
801 assert bool(obj.notify(body="body", title="title", attach=attach)) is True
802 assert request_post_mock.call_count == 6
803
804 # Verify file_ids for each post
805 post1 = json.loads(request_post_mock.call_args_list[2][1]["data"])
806 assert post1["file_ids"] == [fid1, fid2]
807 assert post1["channel_id"] == ch1
808
809 post2 = json.loads(request_post_mock.call_args_list[5][1]["data"])
810 assert post2["file_ids"] == [fid1, fid2]
811 assert post2["channel_id"] == ch2
812
813
814 def test_plugin_mattermost_bot_attachment_upload_http_error(
815 request_post_mock,
816 ):
817 """Upload HTTP error marks the whole target as failed."""
818 bearer = "bearerToken"
819 channel_id = "channel-id-123"
820
821 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
822
823 r = requests.Request()
824 r.status_code = requests.codes.internal_server_error
825 r.content = b""
826 request_post_mock.return_value = r
827
828 obj = Apprise.instantiate(
829 f"mmost://localhost/{bearer}?mode=bot&to={channel_id}"
830 )
831 assert isinstance(obj, NotifyMattermost)
832 assert bool(obj.notify(body="body", title="title", attach=attach)) is False
833 # Only the upload was attempted; no post was made
834 assert request_post_mock.call_count == 1
835 assert "/api/v4/files" in request_post_mock.call_args_list[0][0][0]
836
837
838 def test_plugin_mattermost_bot_attachment_request_exception(
839 request_post_mock,
840 ):
841 """RequestException during upload marks the target as failed."""
842 bearer = "bearerToken"
843 channel_id = "channel-id-123"
844
845 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
846
847 request_post_mock.side_effect = requests.RequestException("boom")
848
849 obj = Apprise.instantiate(
850 f"mmost://localhost/{bearer}?mode=bot&to={channel_id}"
851 )
852 assert isinstance(obj, NotifyMattermost)
853 assert bool(obj.notify(body="body", title="title", attach=attach)) is False
854 assert request_post_mock.call_count == 1
855
856
857 def test_plugin_mattermost_bot_attachment_ioerror(request_post_mock):
858 """OSError reading the attachment marks the target as failed."""
859 bearer = "bearerToken"
860 channel_id = "channel-id-123"
861
862 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
863
864 with mock.patch(
865 "apprise.attachment.file.AttachFile.open",
866 side_effect=OSError("disk error"),
867 ):
868 obj = Apprise.instantiate(
869 f"mmost://localhost/{bearer}?mode=bot&to={channel_id}"
870 )
871 assert isinstance(obj, NotifyMattermost)
872 assert (
873 bool(obj.notify(body="body", title="title", attach=attach))
874 is False
875 )
876
877 # No HTTP request should have been made
878 assert request_post_mock.call_count == 0
879
880
881 def test_plugin_mattermost_bot_attachment_valueerror(request_post_mock):
882 """ValueError from a closed stream is handled the same as OSError."""
883 bearer = "bearerToken"
884 channel_id = "channel-id-123"
885
886 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
887
888 with mock.patch(
889 "apprise.attachment.file.AttachFile.open",
890 side_effect=ValueError("I/O operation on closed file"),
891 ):
892 obj = Apprise.instantiate(
893 f"mmost://localhost/{bearer}?mode=bot&to={channel_id}"
894 )
895 assert isinstance(obj, NotifyMattermost)
896 assert (
897 bool(obj.notify(body="body", title="title", attach=attach))
898 is False
899 )
900
901 assert request_post_mock.call_count == 0
902
903
904 def test_plugin_mattermost_bot_attachment_bad_response(request_post_mock):
905 """Unparseable upload response marks the target as failed."""
906 bearer = "bearerToken"
907 channel_id = "channel-id-123"
908
909 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
910
911 r = requests.Request()
912 r.status_code = requests.codes.ok
913 r.content = b"not-json{{{"
914 request_post_mock.return_value = r
915
916 obj = Apprise.instantiate(
917 f"mmost://localhost/{bearer}?mode=bot&to={channel_id}"
918 )
919 assert isinstance(obj, NotifyMattermost)
920 assert bool(obj.notify(body="body", title="title", attach=attach)) is False
921 assert request_post_mock.call_count == 1
922
923
924 def test_plugin_mattermost_bot_attachment_no_file_id(request_post_mock):
925 """Upload response with empty file_id marks the target as failed."""
926 bearer = "bearerToken"
927 channel_id = "channel-id-123"
928
929 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
930
931 r = requests.Request()
932 r.status_code = requests.codes.ok
933 # file_infos present but id is empty
934 r.content = json.dumps({"file_infos": [{"id": ""}]}).encode("utf-8")
935 request_post_mock.return_value = r
936
937 obj = Apprise.instantiate(
938 f"mmost://localhost/{bearer}?mode=bot&to={channel_id}"
939 )
940 assert isinstance(obj, NotifyMattermost)
941 assert bool(obj.notify(body="body", title="title", attach=attach)) is False
942
943
944 def test_plugin_mattermost_bot_attachment_invalid(request_post_mock):
945 """An inaccessible attachment path marks the target as failed."""
946 bearer = "bearerToken"
947 channel_id = "channel-id-123"
948
949 attach = AppriseAttachment("/path/does/not/exist.gif")
950
951 obj = Apprise.instantiate(
952 f"mmost://localhost/{bearer}?mode=bot&to={channel_id}"
953 )
954 assert isinstance(obj, NotifyMattermost)
955 assert bool(obj.notify(body="body", title="title", attach=attach)) is False
956 # No upload request should be made for an invalid attachment
957 assert request_post_mock.call_count == 0
958
959
960 def test_plugin_mattermost_bot_attachment_partial_target_failure(
961 request_post_mock,
962 ):
963 """Attachment upload failure on one target does not prevent others."""
964 bearer = "bearerToken"
965 ch1 = "channel-001"
966 ch2 = "channel-002"
967 fid = "fid-001"
968
969 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
970
971 def _mk_upload_ok():
972 r = requests.Request()
973 r.status_code = requests.codes.ok
974 r.content = json.dumps({"file_infos": [{"id": fid}]}).encode("utf-8")
975 return r
976
977 def _mk_upload_fail():
978 r = requests.Request()
979 r.status_code = requests.codes.internal_server_error
980 r.content = b""
981 return r
982
983 def _mk_post():
984 r = requests.Request()
985 r.status_code = requests.codes.created
986 r.content = b"{}"
987 return r
988
989 # ch1: upload ok, post ok; ch2: upload fails
990 request_post_mock.side_effect = [
991 _mk_upload_ok(),
992 _mk_post(),
993 _mk_upload_fail(),
994 ]
995
996 obj = Apprise.instantiate(
997 "mmost://localhost/{b}?mode=bot&to={c1},{c2}".format(
998 b=bearer, c1=ch1, c2=ch2
999 )
1000 )
1001 assert isinstance(obj, NotifyMattermost)
1002 # One target succeeded, one failed -> overall False
1003 assert bool(obj.notify(body="body", title="title", attach=attach)) is False
1004 # 1 upload + 1 post (ch1) + 1 upload-fail (ch2) = 3 calls
1005 assert request_post_mock.call_count == 3
1006
1007
1008 def test_plugin_mattermost_bot_attachment_memory_multi_target(
1009 request_post_mock,
1010 ):
1011 """Attachment bytes are pre-read once so every target gets a fresh stream.
1012
1013 Simulates an attachment whose open() raises ValueError on the second
1014 call (as AttachMemory does when its BytesIO is closed after the first
1015 read). Our pre-read approach calls open() exactly once per attachment
1016 before the target loop, then wraps the bytes in a fresh io.BytesIO for
1017 each target upload.
1018 """
1019 bearer = "bearerToken"
1020 ch1 = "channel-001"
1021 ch2 = "channel-002"
1022 fid = "fid-001"
1023
1024 attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, "apprise-test.gif"))
1025
1026 # Simulate a stream that closes after the first read: raise ValueError
1027 # on any open() call beyond the first.
1028 _orig_open = attach.attachments[0].open
1029 open_calls = [0]
1030
1031 def _open_once(*args, **kwargs):
1032 open_calls[0] += 1
1033 if open_calls[0] > 1:
1034 raise ValueError("stream already closed")
1035 return _orig_open(*args, **kwargs)
1036
1037 def _mk_upload():
1038 r = requests.Request()
1039 r.status_code = requests.codes.ok
1040 r.content = json.dumps({"file_infos": [{"id": fid}]}).encode("utf-8")
1041 return r
1042
1043 def _mk_post():
1044 r = requests.Request()
1045 r.status_code = requests.codes.created
1046 r.content = b"{}"
1047 return r
1048
1049 # 1 attachment x 2 targets = 2 upload + 2 post calls
1050 request_post_mock.side_effect = [
1051 _mk_upload(),
1052 _mk_post(),
1053 _mk_upload(),
1054 _mk_post(),
1055 ]
1056
1057 obj = Apprise.instantiate(
1058 "mmost://localhost/{b}?mode=bot&to={c1},{c2}".format(
1059 b=bearer, c1=ch1, c2=ch2
1060 )
1061 )
1062 assert isinstance(obj, NotifyMattermost)
1063
1064 with mock.patch.object(attach.attachments[0], "open", _open_once):
1065 assert (
1066 bool(obj.notify(body="body", title="title", attach=attach)) is True
1067 )
1068
1069 # open() was called exactly once (pre-read), not once per target
1070 assert open_calls[0] == 1
1071 # Both targets received their uploads
1072 assert request_post_mock.call_count == 4
1073
1074 post1 = json.loads(request_post_mock.call_args_list[1][1]["data"])
1075 assert post1["file_ids"] == [fid]
1076 assert post1["channel_id"] == ch1
1077
1078 post2 = json.loads(request_post_mock.call_args_list[3][1]["data"])
1079 assert post2["file_ids"] == [fid]
1080 assert post2["channel_id"] == ch2