Debian Codegraph @

tests/test_plugin_office365.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 from datetime import datetime
29 from json import dumps, loads
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import os
34 from unittest import mock
35
36 from helpers import AppriseURLTester
37 import pytest
38 import requests
39
40 from apprise import Apprise, AppriseAttachment, NotifyType
41 from apprise.exception import AppriseImproperlyConfigured
42 from apprise.plugins.office365 import NotifyOffice365
43
44 logging.disable(logging.CRITICAL)
45
46 # Attachment Directory
47 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
48
49 # Our Testing URLs
50 apprise_url_tests = (
51 ##################################
52 # NotifyOffice365
53 ##################################
54 (
55 "o365://",
56 {
57 # Missing tenant, client_id, secret, and targets!
58 "instance": AppriseImproperlyConfigured,
59 },
60 ),
61 (
62 "o365://:@/",
63 {
64 # invalid url
65 "instance": AppriseImproperlyConfigured,
66 },
67 ),
68 (
69 "o365://{aid}/{tenant}/{cid}/{secret}/{targets}".format(
70 # invalid tenant
71 tenant=",",
72 cid="ab-cd-ef-gh",
73 aid="[email protected]",
74 secret="abcd/123/3343/@jack/test",
75 targets="/".join(["[email protected]"]),
76 ),
77 {
78 # Expected failure
79 "instance": AppriseImproperlyConfigured,
80 },
81 ),
82 (
83 "o365://{aid}/{tenant}/{cid}/{secret}/{targets}".format(
84 tenant="tenant",
85 # invalid client id
86 cid="ab.",
87 aid="[email protected]",
88 secret="abcd/123/3343/@jack/test",
89 targets="/".join(["[email protected]"]),
90 ),
91 {
92 # Expected failure
93 "instance": AppriseImproperlyConfigured,
94 },
95 ),
96 (
97 "o365://{tenant}/{cid}/{secret}/{targets}".format(
98 # email not required if mode is set to self
99 tenant="tenant",
100 cid="ab-cd-ef-gh",
101 secret="abcd/123/3343/@jack/test",
102 targets="/".join(["[email protected]"]),
103 ),
104 {
105 # We're valid and good to go
106 "instance": NotifyOffice365,
107 # Test what happens if a batch send fails to return a messageCount
108 "requests_response_text": {
109 "expires_in": 2000,
110 "access_token": "abcd1234",
111 "mail": "[email protected]",
112 },
113 },
114 ),
115 (
116 "o365://{aid}/{tenant}/{cid}/{secret}/{targets}".format(
117 tenant="tenant",
118 cid="ab-cd-ef-gh",
119 aid="[email protected]",
120 secret="abcd/123/3343/@jack/test",
121 targets="/".join(["[email protected]"]),
122 ),
123 {
124 # We're valid and good to go
125 "instance": NotifyOffice365,
126 # Test what happens if a batch send fails to return a messageCount
127 "requests_response_text": {
128 "expires_in": 2000,
129 "access_token": "abcd1234",
130 # For 'From:' Lookup
131 "mail": "[email protected]",
132 },
133 # Our expected url(privacy=True) startswith() response:
134 "privacy_url": (
135 "azure://[email protected]/t...t/a...h/****/[email protected]/"
136 ),
137 "force_debug": True,
138 },
139 ),
140 (
141 "o365://{aid}/{tenant}/{cid}/{secret}/{targets}".format(
142 tenant="tenant",
143 cid="ab-cd-ef-gh",
144 # Source can also be Object ID
145 aid="hg-fe-dc-ba",
146 secret="abcd/123/3343/@jack/test",
147 targets="/".join(["[email protected]"]),
148 ),
149 {
150 # We're valid and good to go
151 "instance": NotifyOffice365,
152 # Test what happens if a batch send fails to return a messageCount
153 "requests_response_text": {
154 "expires_in": 2000,
155 "access_token": "abcd1234",
156 "mail": "[email protected]",
157 "displayName": "John",
158 },
159 # Our expected url(privacy=True) startswith() response:
160 "privacy_url": (
161 "azure://hg-fe-dc-ba/t...t/a...h/****/[email protected]/"
162 ),
163 },
164 ),
165 # ObjectID Specified, but no targets
166 (
167 "o365://{aid}/{tenant}/{cid}/{secret}/".format(
168 tenant="tenant",
169 cid="ab-cd-ef-gh",
170 # Source can also be Object ID
171 aid="hg-fe-dc-ba",
172 secret="abcd/123/3343/@jack/test",
173 ),
174 {
175 # We're valid and good to go
176 "instance": NotifyOffice365,
177 # Test what happens if a batch send fails to return a messageCount
178 "requests_response_text": {
179 "expires_in": 2000,
180 "access_token": "abcd1234",
181 "mail": "[email protected]",
182 },
183 # No emails detected
184 "notify_response": False,
185 # Our expected url(privacy=True) startswith() response:
186 "privacy_url": "azure://hg-fe-dc-ba/t...t/a...h/****",
187 },
188 ),
189 # ObjectID Specified, but no targets
190 (
191 "o365://{aid}/{tenant}/{cid}/{secret}/".format(
192 tenant="tenant",
193 cid="ab-cd-ef-gh",
194 # Source can also be Object ID
195 aid="hg-fe-dc-ba",
196 secret="abcd/123/3343/@jack/test",
197 ),
198 {
199 # We're valid and good to go
200 "instance": NotifyOffice365,
201 # Test what happens if a batch send fails to return a messageCount
202 "requests_response_text": {
203 "expires_in": 2000,
204 "access_token": "abcd1234",
205 "userPrincipalName": "[email protected]",
206 },
207 # No emails detected
208 "notify_response": False,
209 # Our expected url(privacy=True) startswith() response:
210 "privacy_url": "azure://hg-fe-dc-ba/t...t/a...h/****",
211 },
212 ),
213 # test our arguments
214 (
215 "o365://_/?oauth_id={cid}&oauth_secret={secret}&tenant={tenant}"
216 "&to={targets}&from={aid}".format(
217 tenant="tenant",
218 cid="ab-cd-ef-gh",
219 aid="[email protected]",
220 secret="abcd/123/3343/@jack/test",
221 targets="[email protected]",
222 ),
223 {
224 # We're valid and good to go
225 "instance": NotifyOffice365,
226 # Test what happens if a batch send fails to return a messageCount
227 "requests_response_text": {
228 "expires_in": 2000,
229 "access_token": "abcd1234",
230 "mail": "[email protected]",
231 },
232 # Our expected url(privacy=True) startswith() response:
233 "privacy_url": (
234 "azure://[email protected]/t...t/a...h/****/[email protected]/"
235 ),
236 },
237 ),
238 # Test invalid JSON (no tenant defaults to email domain)
239 (
240 "o365://{aid}/{tenant}/{cid}/{secret}/{targets}".format(
241 tenant="tenant",
242 cid="ab-cd-ef-gh",
243 aid="[email protected]",
244 secret="abcd/123/3343/@jack/test",
245 targets="/".join(["[email protected]"]),
246 ),
247 {
248 # We're valid and good to go
249 "instance": NotifyOffice365,
250 # invalid JSON response
251 "requests_response_text": "{",
252 "notify_response": False,
253 },
254 ),
255 # No Targets specified
256 (
257 "o365://{aid}/{tenant}/{cid}/{secret}".format(
258 tenant="tenant",
259 cid="ab-cd-ef-gh",
260 aid="[email protected]",
261 secret="abcd/123/3343/@jack/test",
262 ),
263 {
264 # We're valid and good to go
265 "instance": NotifyOffice365,
266 # There were no targets to notify; so we use our own email
267 "requests_response_text": {
268 "expires_in": 2000,
269 "access_token": "abcd1234",
270 "userPrincipalName": "[email protected]",
271 },
272 },
273 ),
274 (
275 "o365://{aid}/{tenant}/{cid}/{secret}/{targets}".format(
276 tenant="tenant",
277 cid="zz-zz-zz-zz",
278 aid="[email protected]",
279 secret="abcd/abc/dcba/@john/test",
280 targets="/".join(["[email protected]"]),
281 ),
282 {
283 "instance": NotifyOffice365,
284 # throw a bizarre code forcing us to fail to look it up
285 "response": False,
286 "requests_response_code": 999,
287 },
288 ),
289 (
290 "o365://{tenant}:{aid}/{cid}/{secret}/{targets}".format(
291 tenant="tenant",
292 cid="01-12-23-34",
293 aid="[email protected]",
294 secret="abcd/321/4321/@test/test",
295 targets="/".join(["[email protected]"]),
296 ),
297 {
298 "instance": NotifyOffice365,
299 # Throws a series of i/o exceptions with this flag
300 # is set and tests that we gracefully handle them
301 "test_requests_exceptions": True,
302 },
303 ),
304 # reply_to support — plain address
305 (
306 "o365://{aid}/{tenant}/{cid}/{secret}/{targets}"
307 "[email protected]".format(
308 tenant="tenant",
309 cid="ab-cd-ef-gh",
310 aid="[email protected]",
311 secret="abcd/123/3343/@jack/test",
312 targets="[email protected]",
313 ),
314 {
315 "instance": NotifyOffice365,
316 "requests_response_text": {
317 "expires_in": 2000,
318 "access_token": "abcd1234",
319 "mail": "[email protected]",
320 },
321 "privacy_url": (
322 "azure://[email protected]/t...t/a...h/****/[email protected]/"
323 ),
324 },
325 ),
326 # Disable Save Sent Items
327 (
328 "o365://{aid}/{tenant}/{cid}/{secret}/{targets}?savesent=no".format(
329 tenant="tenant",
330 cid="ab-cd-ef-gh",
331 aid="[email protected]",
332 secret="abcd/123/3343/@jack/test",
333 targets="[email protected]",
334 ),
335 {
336 "instance": NotifyOffice365,
337 "requests_response_text": {
338 "expires_in": 2000,
339 "access_token": "abcd1234",
340 "mail": "[email protected]",
341 },
342 "privacy_url": (
343 "azure://[email protected]/t...t/a...h/****/[email protected]/"
344 ),
345 },
346 ),
347 # reply_to with URL-encoded (+) spaces in name
348 (
349 "o365://{aid}/{tenant}/{cid}/{secret}/{targets}"
350 "[email protected]".format(
351 tenant="tenant",
352 cid="ab-cd-ef-gh",
353 aid="[email protected]",
354 secret="abcd/123/3343/@jack/test",
355 targets="[email protected]",
356 ),
357 {
358 "instance": NotifyOffice365,
359 "requests_response_text": {
360 "expires_in": 2000,
361 "access_token": "abcd1234",
362 "mail": "[email protected]",
363 },
364 "privacy_url": (
365 "azure://[email protected]/t...t/a...h/****/[email protected]/"
366 ),
367 },
368 ),
369 )
370
371
372 def test_plugin_office365_urls():
373 """NotifyOffice365() Apprise URLs."""
374
375 # Run our general tests
376 AppriseURLTester(tests=apprise_url_tests).run_all()
377
378
379 @mock.patch("requests.get")
380 @mock.patch("requests.post")
381 def test_plugin_office365_general(mock_get, mock_post):
382 """NotifyOffice365() General Testing."""
383
384 # Initialize some generic (but valid) tokens
385 email = "[email protected]"
386 tenant = "ff-gg-hh-ii-jj"
387 client_id = "aa-bb-cc-dd-ee"
388 secret = "abcd/1234/abcd@ajd@/test"
389 targets = "[email protected]"
390
391 # Prepare Mock return object
392 payload = {
393 "token_type": "Bearer",
394 "expires_in": 6000,
395 "access_token": "abcd1234",
396 # For 'From:' Lookup
397 "mail": "[email protected]",
398 # For our Draft Email ID:
399 "id": "draft-id-no",
400 }
401 response = mock.Mock()
402 response.content = dumps(payload)
403 response.status_code = requests.codes.ok
404 mock_post.return_value = response
405 mock_get.return_value = response
406
407 # Instantiate our object
408 obj = Apprise.instantiate(f"o365://{email}/{tenant}/{secret}/{targets}")
409
410 assert isinstance(obj, NotifyOffice365)
411
412 # Test our URL generation
413 assert isinstance(obj.url(), str)
414
415 # Test our notification
416 assert bool(obj.notify(title="title", body="test")) is True
417
418 # Instantiate our object
419 obj = Apprise.instantiate(
420 "o365://{email}/{tenant}/{client_id}/{secret}/{targets}"
421 "?bcc={bcc}&cc={cc}".format(
422 tenant=tenant,
423 email=email,
424 client_id=client_id,
425 secret=secret,
426 targets=targets,
427 # Test the cc and bcc list (use good and bad email)
428 cc="Chuck Norris [email protected], [email protected], invalid@!",
429 bcc="Bruce Willis [email protected], [email protected] invalid@!",
430 )
431 )
432
433 assert isinstance(obj, NotifyOffice365)
434
435 # Test our URL generation
436 assert isinstance(obj.url(), str)
437
438 # Test our notification
439 assert bool(obj.notify(title="title", body="test")) is True
440
441 with pytest.raises(AppriseImproperlyConfigured):
442 # No secret
443 NotifyOffice365(
444 email=email,
445 client_id=client_id,
446 tenant=tenant,
447 secret=None,
448 targets=None,
449 )
450
451 # One of the targets are invalid
452 obj = NotifyOffice365(
453 email=email,
454 client_id=client_id,
455 tenant=tenant,
456 secret=secret,
457 targets=("Management [email protected]", "garbage"),
458 )
459 # Test our notification (this will work and only notify [email protected])
460 assert bool(obj.notify(title="title", body="test")) is True
461
462 # all of the targets are invalid
463 obj = NotifyOffice365(
464 email=email,
465 client_id=client_id,
466 tenant=tenant,
467 secret=secret,
468 targets=("invalid", "garbage"),
469 )
470
471 # Test our notification (which will fail because of no entries)
472 assert bool(obj.notify(title="title", body="test")) is False
473
474
475 @mock.patch("requests.get")
476 @mock.patch("requests.post")
477 def test_plugin_office365_authentication(mock_get, mock_post):
478 """NotifyOffice365() Authentication Testing."""
479
480 # Initialize some generic (but valid) tokens
481 tenant = "ff-gg-hh-ii-jj"
482 email = "[email protected]"
483 client_id = "aa-bb-cc-dd-ee"
484 secret = "abcd/1234/abcd@ajd@/test"
485 targets = "[email protected]"
486
487 # Prepare Mock return object
488 authentication_okay = {
489 "token_type": "Bearer",
490 "expires_in": 6000,
491 "access_token": "abcd1234",
492 }
493 authentication_failure = {
494 "error": "invalid_scope",
495 "error_description": "AADSTS70011: Blah... Blah Blah... Blah",
496 "error_codes": [70011],
497 "timestamp": "2020-01-09 02:02:12Z",
498 "trace_id": "255d1aef-8c98-452f-ac51-23d051240864",
499 "correlation_id": "fb3d2015-bc17-4bb9-bb85-30c5cf1aaaa7",
500 }
501 response = mock.Mock()
502 response.content = dumps(authentication_okay)
503 response.status_code = requests.codes.ok
504 mock_post.return_value = response
505 mock_get.return_value = response
506
507 # Instantiate our object
508 obj = Apprise.instantiate(
509 f"azure://{email}/{tenant}/{client_id}/{secret}/{targets}"
510 )
511
512 assert isinstance(obj, NotifyOffice365)
513
514 # Authenticate
515 assert obj.authenticate() is True
516
517 # We're already authenticated
518 assert obj.authenticate() is True
519
520 # Expire our token
521 obj.token_expiry = datetime.now()
522
523 # Re-authentiate
524 assert obj.authenticate() is True
525
526 # Change our response
527 response.status_code = 400
528
529 # We'll fail to send a notification now...
530 assert bool(obj.notify(title="title", body="test")) is False
531
532 # Expire our token
533 obj.token_expiry = datetime.now()
534
535 # Set a failure response
536 response.content = dumps(authentication_failure)
537
538 # We will fail to authenticate at this point
539 assert obj.authenticate() is False
540
541 # Notifications will also fail in this case
542 assert bool(obj.notify(title="title", body="test")) is False
543
544 # We will fail to authenticate with invalid data
545
546 invalid_auth_entries = authentication_okay.copy()
547 invalid_auth_entries["expires_in"] = "garbage"
548 response.content = dumps(invalid_auth_entries)
549 response.status_code = requests.codes.ok
550 assert obj.authenticate() is False
551
552 invalid_auth_entries["expires_in"] = None
553 response.content = dumps(invalid_auth_entries)
554 assert obj.authenticate() is False
555
556 invalid_auth_entries["expires_in"] = ""
557 response.content = dumps(invalid_auth_entries)
558 assert obj.authenticate() is False
559
560 del invalid_auth_entries["expires_in"]
561 response.content = dumps(invalid_auth_entries)
562 assert obj.authenticate() is False
563
564
565 @mock.patch("requests.put")
566 @mock.patch("requests.get")
567 @mock.patch("requests.post")
568 def test_plugin_office365_queries(mock_post, mock_get, mock_put):
569 """NotifyOffice365() General Queries."""
570
571 # Initialize some generic (but valid) tokens
572 source = "abc-1234-object-id"
573 tenant = "ff-gg-hh-ii-jj"
574 client_id = "aa-bb-cc-dd-ee"
575 secret = "abcd/1234/abcd@ajd@/test"
576 targets = "[email protected]"
577
578 # Prepare Mock return object
579 payload = {
580 "token_type": "Bearer",
581 "expires_in": 6000,
582 "access_token": "abcd1234",
583 # For 'From:' Lookup (email)
584 "mail": "[email protected]",
585 # For 'From:' Lookup (name)
586 "displayName": "John",
587 # For our Draft Email ID:
588 "id": "draft-id-no",
589 # For FIle Uploads
590 "uploadUrl": "https://my.url.path/",
591 }
592
593 okay_response = mock.Mock()
594 okay_response.content = dumps(payload)
595 okay_response.status_code = requests.codes.ok
596 mock_post.return_value = okay_response
597 mock_put.return_value = okay_response
598
599 bad_response = mock.Mock()
600 bad_response.content = dumps(payload)
601 bad_response.status_code = requests.codes.forbidden
602
603 # Assign our GET a bad response so we fail to look up the user
604 mock_get.return_value = bad_response
605
606 #
607 # Early exit: source is an Object ID (GUID) and lookup fails
608 #
609 guid_source = "e2a9db46-5714-44c2-87bf-c33bf236f42a"
610
611 not_found_payload = {
612 "error": {
613 "code": "Request_ResourceNotFound",
614 "message": "Resource not found.",
615 }
616 }
617 not_found_response = mock.Mock()
618 not_found_response.content = dumps(not_found_payload)
619 not_found_response.status_code = requests.codes.not_found
620
621 # Force the sender lookup to fail for a GUID based source
622 mock_get.return_value = not_found_response
623
624 obj = Apprise.instantiate(
625 f"azure://{guid_source}/{tenant}/{client_id}{secret}/{targets}"
626 )
627 assert isinstance(obj, NotifyOffice365)
628
629 # Notify must exit early since the source Object ID could not be resolved
630 assert (
631 bool(
632 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
633 )
634 is False
635 )
636
637 # 1) Authenticate (POST token)
638 assert mock_post.call_count == 1
639 # 2) Attempt user lookup (GET)
640 assert mock_get.call_count == 1
641
642 mock_post.reset_mock()
643 mock_get.reset_mock()
644
645 # Restore GET failure behaviour used by remaining tests
646 mock_get.return_value = bad_response
647
648 # Instantiate our object
649 obj = Apprise.instantiate(
650 f"azure://{source}/{tenant}/{client_id}{secret}/{targets}"
651 )
652
653 assert isinstance(obj, NotifyOffice365)
654
655 # We can still send a notification even if we can't look up the email
656 assert (
657 bool(
658 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
659 )
660 is True
661 )
662
663 assert mock_post.call_count == 2
664 assert (
665 mock_post.call_args_list[0][0][0]
666 == f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"
667 )
668 assert (
669 mock_post.call_args_list[1][0][0]
670 == "https://graph.microsoft.com/v1.0/users/abc-1234-object-id/sendMail"
671 )
672 payload = loads(mock_post.call_args_list[1][1]["data"])
673 assert payload == {
674 "message": {
675 "subject": "title",
676 "body": {
677 "contentType": "HTML",
678 "content": "body",
679 },
680 "toRecipients": [
681 {"emailAddress": {"address": "[email protected]"}}
682 ],
683 },
684 "saveToSentItems": "true",
685 }
686 mock_post.reset_mock()
687
688 # Now test a case where we just couldn't get any email details from the
689 # payload returned
690
691 # Prepare Mock return object
692 temp_payload = {
693 "token_type": "Bearer",
694 "expires_in": 6000,
695 "access_token": "abcd1234",
696 # For our Draft Email ID:
697 "id": "draft-id-no",
698 # For FIle Uploads
699 "uploadUrl": "https://my.url.path/",
700 }
701
702 bad_response.content = dumps(temp_payload)
703 bad_response.status_code = requests.codes.okay
704 mock_get.return_value = bad_response
705
706 obj = Apprise.instantiate(
707 f"azure://{source}/{tenant}/{client_id}{secret}/{targets}"
708 )
709
710 assert isinstance(obj, NotifyOffice365)
711
712 # We can still send a notification even if we can't look up the email
713 assert (
714 bool(
715 obj.notify(body="body", title="title", notify_type=NotifyType.INFO)
716 )
717 is True
718 )
719
720
721 @mock.patch("requests.put")
722 @mock.patch("requests.get")
723 @mock.patch("requests.post")
724 def test_plugin_office365_attachments(mock_post, mock_get, mock_put):
725 """NotifyOffice365() Attachments."""
726
727 # Initialize some generic (but valid) tokens
728 source = "[email protected]"
729 tenant = "ff-gg-hh-ii-jj"
730 client_id = "aa-bb-cc-dd-ee"
731 secret = "abcd/1234/abcd@ajd@/test"
732 targets = "[email protected]"
733
734 # Prepare Mock return object
735 payload = {
736 "token_type": "Bearer",
737 "expires_in": 6000,
738 "access_token": "abcd1234",
739 # For 'From:' Lookup
740 "mail": "[email protected]",
741 # For our Draft Email ID:
742 "id": "draft-id-no",
743 # For FIle Uploads
744 "uploadUrl": "https://my.url.path/",
745 }
746 okay_response = mock.Mock()
747 okay_response.content = dumps(payload)
748 okay_response.status_code = requests.codes.ok
749 mock_post.return_value = okay_response
750 mock_get.return_value = okay_response
751 mock_put.return_value = okay_response
752
753 # Instantiate our object
754 obj = Apprise.instantiate(
755 f"azure://{source}/{tenant}/{client_id}{secret}/{targets}"
756 )
757
758 assert isinstance(obj, NotifyOffice365)
759
760 # Test Valid Attachment
761 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
762 attach = AppriseAttachment(path)
763 assert (
764 bool(
765 obj.notify(
766 body="body",
767 title="title",
768 notify_type=NotifyType.INFO,
769 attach=attach,
770 )
771 )
772 is True
773 )
774
775 assert mock_post.call_count == 2
776 assert (
777 mock_post.call_args_list[0][0][0]
778 == f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"
779 )
780 assert (
781 mock_post.call_args_list[0][1]["headers"].get("Content-Type")
782 == "application/x-www-form-urlencoded"
783 )
784 assert (
785 mock_post.call_args_list[1][0][0]
786 == f"https://graph.microsoft.com/v1.0/users/{source}/sendMail"
787 )
788 assert (
789 mock_post.call_args_list[1][1]["headers"].get("Content-Type")
790 == "application/json"
791 )
792 mock_post.reset_mock()
793
794 # Test Authentication Failure
795 obj = Apprise.instantiate(
796 "azure://{source}/{tenant}/{client_id}{secret}/{targets}".format(
797 client_id=client_id,
798 tenant=tenant,
799 source="object-id-requiring-lookup",
800 secret=secret,
801 targets=targets,
802 )
803 )
804
805 bad_response = mock.Mock()
806 bad_response.content = dumps(payload)
807 bad_response.status_code = requests.codes.forbidden
808 mock_post.return_value = bad_response
809
810 assert isinstance(obj, NotifyOffice365)
811 # Authentication will fail
812 assert (
813 bool(
814 obj.notify(
815 body="auth-fail", title="title", notify_type=NotifyType.INFO
816 )
817 )
818 is False
819 )
820 assert mock_post.call_count == 1
821 assert (
822 mock_post.call_args_list[0][0][0]
823 == "https://login.microsoftonline.com/ff-gg-hh-ii-jj/oauth2/v2.0/token"
824 )
825 mock_post.reset_mock()
826
827 #
828 # Test invalid attachment
829 #
830
831 # Instantiate our object
832 obj = Apprise.instantiate(
833 f"azure://{source}/{tenant}/{client_id}{secret}/{targets}"
834 )
835
836 assert isinstance(obj, NotifyOffice365)
837
838 mock_post.return_value = okay_response
839 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
840 assert (
841 bool(
842 obj.notify(
843 body="body",
844 title="title",
845 notify_type=NotifyType.INFO,
846 attach=path,
847 )
848 )
849 is False
850 )
851 assert mock_post.call_count == 0
852 mock_post.reset_mock()
853
854 with mock.patch("base64.b64encode", side_effect=OSError()):
855 # We can't send the message if we fail to parse the data
856 assert (
857 bool(
858 obj.notify(
859 body="body",
860 title="title",
861 notify_type=NotifyType.INFO,
862 attach=attach,
863 )
864 )
865 is False
866 )
867 assert mock_post.call_count == 0
868 mock_post.reset_mock()
869
870 #
871 # Test case where we can't authenticate
872 #
873 obj = Apprise.instantiate(
874 f"azure://{source}/{tenant}/{client_id}{secret}/{targets}"
875 )
876
877 # Force a smaller attachment size forcing us to create an attachment
878 obj.outlook_attachment_inline_max = 50
879
880 assert isinstance(obj, NotifyOffice365)
881
882 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
883 attach = AppriseAttachment(path)
884 mock_post.return_value = bad_response
885 assert obj.upload_attachment(attach[0], "id") is False
886 assert mock_post.call_count == 1
887 assert (
888 mock_post.call_args_list[0][0][0]
889 == "https://login.microsoftonline.com/ff-gg-hh-ii-jj/oauth2/v2.0/token"
890 )
891
892 mock_post.reset_mock()
893
894 mock_post.side_effect = (okay_response, bad_response)
895 mock_post.return_value = None
896 assert obj.upload_attachment(attach[0], "id") is False
897 assert mock_post.call_count == 2
898 assert (
899 mock_post.call_args_list[0][0][0]
900 == "https://login.microsoftonline.com/ff-gg-hh-ii-jj/oauth2/v2.0/token"
901 )
902 assert (
903 mock_post.call_args_list[1][0][0]
904 == f"https://graph.microsoft.com/v1.0/users/{source}/"
905 + "message/id/attachments/createUploadSession"
906 )
907
908 mock_post.reset_mock()
909 # Return our status
910 mock_post.side_effect = None
911
912 # Prepare Mock return object
913 payload_no_upload_url = {
914 "token_type": "Bearer",
915 "expires_in": 6000,
916 "access_token": "abcd1234",
917 # For 'From:' Lookup
918 "mail": "[email protected]",
919 # For our Draft Email ID:
920 "id": "draft-id-no",
921 }
922 tmp_response = mock.Mock()
923 tmp_response.content = dumps(payload_no_upload_url)
924 tmp_response.status_code = requests.codes.ok
925 mock_post.return_value = tmp_response
926
927 assert obj.upload_attachment(attach[0], "id") is False
928 assert mock_post.call_count == 1
929 assert (
930 mock_post.call_args_list[0][0][0]
931 == f"https://graph.microsoft.com/v1.0/users/{source}/"
932 + "message/id/attachments/createUploadSession"
933 )
934
935 mock_post.reset_mock()
936 # Return our status
937 mock_post.side_effect = None
938 mock_post.return_value = okay_response
939
940 obj = Apprise.instantiate(
941 f"azure://{source}/{tenant}/{client_id}{secret}/{targets}"
942 )
943
944 # Force a smaller attachment size forcing us to create an attachment
945 obj.outlook_attachment_inline_max = 50
946
947 assert isinstance(obj, NotifyOffice365)
948
949 # We now have to prepare sepparate session attachments using draft emails
950 assert (
951 bool(
952 obj.notify(
953 body="body",
954 title="title-test",
955 notify_type=NotifyType.INFO,
956 attach=attach,
957 )
958 )
959 is True
960 )
961
962 # Large Attachments
963 assert mock_post.call_count == 4
964 assert (
965 mock_post.call_args_list[0][0][0]
966 == "https://login.microsoftonline.com/ff-gg-hh-ii-jj/oauth2/v2.0/token"
967 )
968 assert (
969 mock_post.call_args_list[1][0][0]
970 == f"https://graph.microsoft.com/v1.0/users/{source}/messages"
971 )
972 assert (
973 mock_post.call_args_list[2][0][0]
974 == f"https://graph.microsoft.com/v1.0/users/{source}/"
975 + "message/draft-id-no/attachments/createUploadSession"
976 )
977 assert (
978 mock_post.call_args_list[3][0][0]
979 == "https://graph.microsoft.com/v1.0/users/"
980 + f"{source}/messages/draft-id-no/send"
981 )
982 mock_post.reset_mock()
983
984 #
985 # Handle another case where can't upload the attachment at all
986 #
987 path = os.path.join(TEST_VAR_DIR, "/invalid/path/to/an/invalid/file.jpg")
988 bad_attach = AppriseAttachment(path)
989 assert obj.upload_attachment(bad_attach[0], "id") is False
990
991 mock_post.reset_mock()
992 #
993 # Handle test case where we can't send the draft email after everything
994 # has been prepared
995 #
996 mock_post.return_value = None
997 mock_post.side_effect = (okay_response, okay_response, bad_response)
998 assert (
999 bool(
1000 obj.notify(
1001 body="body",
1002 title="title-test",
1003 notify_type=NotifyType.INFO,
1004 attach=attach,
1005 )
1006 )
1007 is False
1008 )
1009
1010 assert mock_post.call_count == 3
1011 assert (
1012 mock_post.call_args_list[0][0][0]
1013 == f"https://graph.microsoft.com/v1.0/users/{source}/messages"
1014 )
1015 assert (
1016 mock_post.call_args_list[1][0][0]
1017 == f"https://graph.microsoft.com/v1.0/users/{source}/"
1018 + "message/draft-id-no/attachments/createUploadSession"
1019 )
1020 assert (
1021 mock_post.call_args_list[2][0][0]
1022 == "https://graph.microsoft.com/v1.0/users/"
1023 + f"{source}/messages/draft-id-no/send"
1024 )
1025 mock_post.reset_mock()
1026 mock_post.side_effect = None
1027 mock_post.return_value = okay_response
1028
1029 #
1030 # Handle test case where we can not upload chunks
1031 #
1032 mock_put.return_value = bad_response
1033
1034 # We now have to prepare sepparate session attachments using draft emails
1035 assert (
1036 bool(
1037 obj.notify(
1038 body="body",
1039 title="title-no-chunk",
1040 notify_type=NotifyType.INFO,
1041 attach=attach,
1042 )
1043 )
1044 is False
1045 )
1046
1047 assert mock_post.call_count == 2
1048 assert (
1049 mock_post.call_args_list[0][0][0]
1050 == f"https://graph.microsoft.com/v1.0/users/{source}/messages"
1051 )
1052 assert (
1053 mock_post.call_args_list[1][0][0]
1054 == f"https://graph.microsoft.com/v1.0/users/{source}/"
1055 + "message/draft-id-no/attachments/createUploadSession"
1056 )
1057
1058 mock_put.return_value = okay_response
1059 mock_post.reset_mock()
1060
1061 # Prepare Mock return object
1062 payload_missing_id = {
1063 "token_type": "Bearer",
1064 "expires_in": 6000,
1065 "access_token": "abcd1234",
1066 # For 'From:' Lookup
1067 "mail": "[email protected]",
1068 # For FIle Uploads
1069 "uploadUrl": "https://my.url.path/",
1070 }
1071 temp_response = mock.Mock()
1072 temp_response.content = dumps(payload_missing_id)
1073 temp_response.status_code = requests.codes.ok
1074 mock_post.return_value = temp_response
1075
1076 # We could not acquire an attachment id, so we'll fail to send our
1077 # notification
1078 assert (
1079 bool(
1080 obj.notify(
1081 body="body",
1082 title="title-test",
1083 notify_type=NotifyType.INFO,
1084 attach=attach,
1085 )
1086 )
1087 is False
1088 )
1089
1090 # Large Attachments
1091 assert mock_post.call_count == 1
1092 assert (
1093 mock_post.call_args_list[0][0][0]
1094 == "https://graph.microsoft.com/v1.0/users/[email protected]/messages"
1095 )
1096
1097 mock_post.reset_mock()
1098
1099 # Reset attachment size
1100 obj.outlook_attachment_inline_max = 50 * 1024 * 1024
1101 assert (
1102 bool(
1103 obj.notify(
1104 body="body",
1105 title="title",
1106 notify_type=NotifyType.INFO,
1107 attach=attach,
1108 )
1109 )
1110 is True
1111 )
1112
1113 # already authenticated
1114 assert mock_post.call_count == 1
1115 assert (
1116 mock_post.call_args_list[0][0][0]
1117 == f"https://graph.microsoft.com/v1.0/users/{source}/sendMail"
1118 )
1119 mock_post.reset_mock()
1120
1121
1122 @mock.patch("requests.get")
1123 @mock.patch("requests.post")
1124 def test_plugin_office365_inline_mimetype(mock_post, mock_get):
1125 """NotifyOffice365() inline attachments carry their real MIME type."""
1126
1127 # Initialize some generic (but valid) tokens
1128 source = "[email protected]"
1129 tenant = "ff-gg-hh-ii-jj"
1130 client_id = "aa-bb-cc-dd-ee"
1131 secret = "abcd/1234/abcd@ajd@/test"
1132 targets = "[email protected]"
1133
1134 payload = {
1135 "token_type": "Bearer",
1136 "expires_in": 6000,
1137 "access_token": "abcd1234",
1138 }
1139 okay_response = mock.Mock()
1140 okay_response.content = dumps(payload)
1141 okay_response.status_code = requests.codes.ok
1142 mock_post.return_value = okay_response
1143 mock_get.return_value = okay_response
1144
1145 obj = Apprise.instantiate(
1146 f"azure://{source}/{tenant}/{client_id}{secret}/{targets}"
1147 )
1148 assert isinstance(obj, NotifyOffice365)
1149
1150 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
1151 attach = AppriseAttachment(path)
1152
1153 # Attachment is small enough to be sent inline (base64) with sendMail
1154 assert len(attach[0]) < obj.outlook_attachment_inline_max
1155 assert (
1156 obj.notify(
1157 body="body",
1158 title="title",
1159 notify_type=NotifyType.INFO,
1160 attach=attach,
1161 )
1162 is True
1163 )
1164
1165 # The token request comes first, then the sendMail call
1166 assert mock_post.call_count == 2
1167 assert (
1168 mock_post.call_args_list[1][0][0]
1169 == f"https://graph.microsoft.com/v1.0/users/{source}/sendMail"
1170 )
1171
1172 posted = loads(mock_post.call_args_list[1][1]["data"])
1173 attachments = posted["message"]["attachments"]
1174 assert len(attachments) == 1
1175
1176 # The attachment carries the file's real MIME type
1177 assert attachments[0]["contentType"] == attach[0].mimetype
1178 assert attachments[0]["contentType"] == "image/gif"
1179
1180
1181 @mock.patch("requests.get")
1182 @mock.patch("requests.post")
1183 def test_plugin_office365_reply_to(mock_post, mock_get):
1184 """NotifyOffice365() reply_to parameter support."""
1185
1186 tenant = "ff-gg-hh-ii-jj"
1187 email = "[email protected]"
1188 client_id = "aa-bb-cc-dd-ee"
1189 secret = "abcd/1234/abcd@ajd@/test"
1190 targets = "[email protected]"
1191
1192 payload = {
1193 "token_type": "Bearer",
1194 "expires_in": 6000,
1195 "access_token": "abcd1234",
1196 "mail": "[email protected]",
1197 }
1198 okay_response = mock.Mock()
1199 okay_response.content = dumps(payload)
1200 okay_response.status_code = requests.codes.ok
1201 mock_post.return_value = okay_response
1202 mock_get.return_value = okay_response
1203
1204 # named reply_to via direct instantiation
1205 obj = NotifyOffice365(
1206 source=email,
1207 tenant=tenant,
1208 client_id=client_id,
1209 secret=secret,
1210 targets=[targets],
1211 reply_to=["Reply Person <[email protected]>"],
1212 )
1213
1214 assert isinstance(obj, NotifyOffice365)
1215 assert len(obj.reply_to) == 1
1216 assert "[email protected]" in obj.reply_to
1217
1218 # url() round-trip includes reply_to
1219 url = obj.url()
1220 assert "reply_to=" in url
1221
1222 # send() adds replyTo with name to the payload
1223 assert bool(obj.notify(title="title", body="test")) is True
1224 assert mock_post.call_count == 2
1225 sent_payload = loads(mock_post.call_args_list[1][1]["data"])
1226 assert "replyTo" in sent_payload["message"]
1227 assert (
1228 sent_payload["message"]["replyTo"][0]["emailAddress"]["address"]
1229 == "[email protected]"
1230 )
1231 assert (
1232 sent_payload["message"]["replyTo"][0]["emailAddress"]["name"]
1233 == "Reply Person"
1234 )
1235 mock_post.reset_mock()
1236
1237 # reply_to without a name via URL query string
1238 obj2 = Apprise.instantiate(
1239 "o365://{email}/{tenant}/{client_id}/{secret}/{targets}"
1240 "[email protected]".format(
1241 tenant=tenant,
1242 email=email,
1243 client_id=client_id,
1244 secret=secret,
1245 targets=targets,
1246 )
1247 )
1248
1249 assert isinstance(obj2, NotifyOffice365)
1250 assert bool(obj2.notify(title="t", body="b")) is True
1251 sent_payload = loads(mock_post.call_args_list[1][1]["data"])
1252 assert "replyTo" in sent_payload["message"]
1253 assert "name" not in sent_payload["message"]["replyTo"][0]["emailAddress"]
1254 mock_post.reset_mock()
1255
1256 # invalid reply_to address is dropped silently
1257 obj3 = NotifyOffice365(
1258 source=email,
1259 tenant=tenant,
1260 client_id=client_id,
1261 secret=secret,
1262 targets=[targets],
1263 reply_to=["not-a-valid-email"],
1264 )
1265 assert isinstance(obj3, NotifyOffice365)
1266 assert len(obj3.reply_to) == 0
1267 # No replyTo in payload when reply_to is empty
1268 assert bool(obj3.notify(title="t", body="b")) is True
1269 sent_payload = loads(mock_post.call_args_list[1][1]["data"])
1270 assert "replyTo" not in sent_payload["message"]
1271 mock_post.reset_mock()
1272
1273 # parse_url picks up ?reply_to=
1274 parsed = NotifyOffice365.parse_url(
1275 "o365://{email}/{tenant}/{client_id}/{secret}/{targets}"
1276 "[email protected]".format(
1277 tenant=tenant,
1278 email=email,
1279 client_id=client_id,
1280 secret=secret,
1281 targets=targets,
1282 )
1283 )
1284 assert parsed is not None
1285 assert "reply_to" in parsed
1286 assert "[email protected]" in parsed["reply_to"]
1287
1288
1289 @mock.patch("requests.get")
1290 @mock.patch("requests.post")
1291 def test_plugin_office365_personal_mode(mock_post, mock_get):
1292 """NotifyOffice365() personal mode (refresh_token / consumer accounts)."""
1293 from apprise.plugins.office365 import (
1294 Office365Mode,
1295 )
1296
1297 client_id = "aa-bb-cc-dd-ee"
1298 seed_token = "seed-refresh-token-abc123"
1299 new_token = "rotated-refresh-token-xyz789"
1300 access_token = "access-token-live"
1301
1302 auth_payload = {
1303 "token_type": "Bearer",
1304 "expires_in": 3600,
1305 "access_token": access_token,
1306 "refresh_token": new_token,
1307 }
1308 okay_response = mock.Mock()
1309 okay_response.content = dumps(auth_payload)
1310 okay_response.status_code = requests.codes.ok
1311 bad_response = mock.Mock()
1312 bad_response.content = dumps({"error": "bad"})
1313 bad_response.status_code = requests.codes.internal_server_error
1314
1315 mock_post.return_value = okay_response
1316 mock_get.return_value = okay_response
1317
1318 #
1319 # Auto-detection: @live.com triggers personal mode
1320 #
1321 obj = NotifyOffice365(
1322 source="[email protected]",
1323 client_id=client_id,
1324 secret=seed_token,
1325 )
1326 assert isinstance(obj, NotifyOffice365)
1327 assert obj.mode == Office365Mode.PERSONAL
1328 assert obj.tenant is None
1329 assert obj.from_email == "[email protected]"
1330 assert obj.source_is_object_id is False
1331
1332 # All known personal domains trigger personal mode
1333 for domain in ("hotmail.com", "outlook.com", "live.com", "msn.com"):
1334 o = NotifyOffice365(
1335 source=f"user@{domain}",
1336 client_id=client_id,
1337 secret=seed_token,
1338 )
1339 assert o.mode == Office365Mode.PERSONAL, (
1340 f"expected personal mode for {domain}"
1341 )
1342
1343 #
1344 # Explicit mode=personal on a non-personal domain
1345 #
1346 obj_explicit = NotifyOffice365(
1347 source="[email protected]",
1348 client_id=client_id,
1349 secret=seed_token,
1350 mode=Office365Mode.PERSONAL,
1351 )
1352 assert obj_explicit.mode == Office365Mode.PERSONAL
1353
1354 #
1355 # Explicit mode=org on a personal domain — still requires valid email
1356 # source (no tenant needed for the personal flow, but org requires tenant)
1357 #
1358 with pytest.raises(AppriseImproperlyConfigured):
1359 # tenant is None but mode=org demands a valid tenant
1360 NotifyOffice365(
1361 source="[email protected]",
1362 client_id=client_id,
1363 secret=seed_token,
1364 mode=Office365Mode.ORG,
1365 )
1366
1367 #
1368 # Personal mode requires source to be a valid email
1369 #
1370 with pytest.raises(AppriseImproperlyConfigured):
1371 NotifyOffice365(
1372 source="not-an-email",
1373 client_id=client_id,
1374 secret=seed_token,
1375 mode=Office365Mode.PERSONAL,
1376 )
1377
1378 #
1379 # An invalid mode is rejected.
1380 #
1381 with pytest.raises(AppriseImproperlyConfigured):
1382 NotifyOffice365(
1383 source="[email protected]",
1384 client_id=client_id,
1385 secret=seed_token,
1386 mode="invalid-mode",
1387 )
1388
1389 #
1390 # send() uses me/sendMail and me/messages (not users/{source}/...)
1391 #
1392 obj = NotifyOffice365(
1393 source="[email protected]",
1394 client_id=client_id,
1395 secret=seed_token,
1396 targets=["[email protected]"],
1397 )
1398 assert obj.mode == Office365Mode.PERSONAL
1399 assert bool(obj.notify(title="title", body="body")) is True
1400
1401 # POST 0: token refresh POST 1: sendMail
1402 assert mock_post.call_count == 2
1403 assert (
1404 mock_post.call_args_list[0][0][0]
1405 == "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"
1406 )
1407 assert (
1408 mock_post.call_args_list[1][0][0]
1409 == "https://graph.microsoft.com/v1.0/me/sendMail"
1410 )
1411 mock_post.reset_mock()
1412
1413 #
1414 # Refresh token rotation: store holds the new token; url() emits it
1415 #
1416 stored = obj.store.get("refresh_token")
1417 assert stored == new_token
1418
1419 generated_url = obj.url()
1420 assert new_token in generated_url
1421 assert seed_token not in generated_url
1422 assert "mode=personal" in generated_url
1423
1424 # Privacy URL masks the token
1425 private_url = obj.url(privacy=True)
1426 assert new_token not in private_url
1427 assert seed_token not in private_url
1428
1429 #
1430 # Auth failure (bad token response) propagates correctly
1431 #
1432 mock_post.return_value = bad_response
1433 obj2 = NotifyOffice365(
1434 source="[email protected]",
1435 client_id=client_id,
1436 secret=seed_token,
1437 )
1438 assert bool(obj2.notify(title="t", body="b")) is False
1439 mock_post.reset_mock()
1440 mock_post.return_value = okay_response
1441
1442 #
1443 # Auth response missing expires_in
1444 #
1445 broken_payload = {"access_token": access_token}
1446 broken_response = mock.Mock()
1447 broken_response.content = dumps(broken_payload)
1448 broken_response.status_code = requests.codes.ok
1449 mock_post.return_value = broken_response
1450 obj3 = NotifyOffice365(
1451 source="[email protected]",
1452 client_id=client_id,
1453 secret=seed_token,
1454 )
1455 assert bool(obj3.notify(title="t", body="b")) is False
1456 mock_post.reset_mock()
1457 mock_post.return_value = okay_response
1458
1459 #
1460 # parse_url: personal domain auto-detects without mode= param
1461 #
1462 parsed = NotifyOffice365.parse_url(
1463 f"o365://[email protected]/{client_id}/{seed_token}/"
1464 )
1465 assert parsed is not None
1466 assert parsed["mode"] == Office365Mode.PERSONAL
1467 assert parsed["tenant"] is None
1468 assert parsed["client_id"] == client_id
1469 assert parsed["secret"] == seed_token
1470
1471 # Reconstructed object from parse_url
1472 obj4 = Apprise.instantiate(
1473 f"o365://[email protected]/{client_id}/{seed_token}/"
1474 )
1475 assert isinstance(obj4, NotifyOffice365)
1476 assert obj4.mode == Office365Mode.PERSONAL
1477
1478 #
1479 # parse_url: explicit ?mode=personal on non-personal domain
1480 #
1481 parsed2 = NotifyOffice365.parse_url(
1482 f"o365://[email protected]/{client_id}/{seed_token}/?mode=personal"
1483 )
1484 assert parsed2 is not None
1485 assert parsed2["mode"] == Office365Mode.PERSONAL
1486
1487 #
1488 # parse_url: explicit ?mode=org on personal domain
1489 #
1490 parsed3 = NotifyOffice365.parse_url(
1491 f"o365://[email protected]/tenant-id/{client_id}/{seed_token}/?mode=org"
1492 )
1493 assert parsed3 is not None
1494 assert parsed3["mode"] == Office365Mode.ORG
1495 assert parsed3["tenant"] == "tenant-id"
1496
1497 #
1498 # url() round-trip for personal mode
1499 #
1500 obj5 = NotifyOffice365(
1501 source="[email protected]",
1502 client_id=client_id,
1503 secret=seed_token,
1504 targets=["[email protected]"],
1505 )
1506 url = obj5.url()
1507 assert "mode=personal" in url
1508 assert "outlook.com" in url
1509 assert client_id in url
1510 # No tenant segment
1511 assert "tenant" not in url
1512
1513 # Round-trip: parse and reconstruct
1514 parsed4 = NotifyOffice365.parse_url(url)
1515 assert parsed4 is not None
1516 assert parsed4["mode"] == Office365Mode.PERSONAL
1517 obj6 = Apprise.instantiate(url)
1518 assert isinstance(obj6, NotifyOffice365)
1519 assert obj6.mode == Office365Mode.PERSONAL
1520
1521 #
1522 # parse_url: unrecognised ?mode= value falls back to auto-detection
1523 # (covers the branch where _mode is NOT in OFFICE365_MODES)
1524 #
1525 parsed5 = NotifyOffice365.parse_url(
1526 f"o365://[email protected]/{client_id}/{seed_token}/?mode=bogus-value"
1527 )
1528 assert parsed5 is not None
1529 # bogus mode is ignored; auto-detection kicks in → personal
1530 assert parsed5["mode"] == Office365Mode.PERSONAL
1531
1532 #
1533 # Personal mode supports cc/bcc/reply_to and emits them via url()
1534 #
1535 mock_post.reset_mock()
1536 mock_post.return_value = okay_response
1537 obj7 = NotifyOffice365(
1538 source="[email protected]",
1539 client_id=client_id,
1540 secret=seed_token,
1541 targets=["[email protected]"],
1542 cc=["Carbon Copy <[email protected]>"],
1543 bcc=["Blind Copy <[email protected]>"],
1544 reply_to=["Reply Person <[email protected]>"],
1545 )
1546 assert isinstance(obj7, NotifyOffice365)
1547
1548 personal_url = obj7.url()
1549 assert "mode=personal" in personal_url
1550 assert "cc=Carbon%20Copy%3Acc%40example.com" in personal_url
1551 assert "bcc=Blind%20Copy%3Abcc%40example.com" in personal_url
1552 assert "reply_to=Reply%20Person%3Areply%40example.org" in personal_url
1553
1554 assert bool(obj7.notify(title="title", body="body")) is True
1555 assert mock_post.call_count == 2
1556 assert (
1557 mock_post.call_args_list[1][0][0]
1558 == "https://graph.microsoft.com/v1.0/me/sendMail"
1559 )
1560 sent_payload = loads(mock_post.call_args_list[1][1]["data"])
1561 assert sent_payload["message"]["ccRecipients"][0]["emailAddress"] == {
1562 "address": "[email protected]",
1563 "name": "Carbon Copy",
1564 }
1565 assert sent_payload["message"]["bccRecipients"][0]["emailAddress"] == {
1566 "address": "[email protected]",
1567 "name": "Blind Copy",
1568 }
1569 assert sent_payload["message"]["replyTo"][0]["emailAddress"] == {
1570 "address": "[email protected]",
1571 "name": "Reply Person",
1572 }
1573
1574 #
1575 # Auth succeeds but server returns no new refresh_token
1576 # (covers the branch where `if new_refresh:` is falsy)
1577 #
1578 no_rotate_payload = {
1579 "token_type": "Bearer",
1580 "expires_in": 3600,
1581 "access_token": access_token,
1582 # no "refresh_token" key
1583 }
1584 no_rotate_response = mock.Mock()
1585 no_rotate_response.content = dumps(no_rotate_payload)
1586 no_rotate_response.status_code = requests.codes.ok
1587 send_response = mock.Mock()
1588 send_response.content = dumps({})
1589 send_response.status_code = requests.codes.accepted
1590
1591 mock_post.side_effect = [no_rotate_response, send_response]
1592 obj_nr = NotifyOffice365(
1593 source="[email protected]",
1594 client_id=client_id,
1595 secret=seed_token,
1596 targets=["[email protected]"],
1597 )
1598 assert bool(obj_nr.notify(title="t", body="b")) is True
1599 # No new token stored — seed_token still in url()
1600 assert obj_nr.store.get("refresh_token") is None
1601 mock_post.reset_mock()
1602 mock_post.side_effect = None
1603 mock_post.return_value = okay_response
1604
1605
1606 @mock.patch("requests.put")
1607 @mock.patch("requests.get")
1608 @mock.patch("requests.post")
1609 def test_plugin_office365_personal_large_attachment(
1610 mock_post, mock_get, mock_put
1611 ):
1612 """Personal mode large-attachment path (me/messages draft + send)."""
1613 from apprise.plugins.office365 import Office365Mode
1614
1615 client_id = "aa-bb-cc-dd-ee"
1616 seed_token = "seed-refresh-token-abc123"
1617 new_token = "rotated-refresh-token-xyz789"
1618 access_token = "access-token-live"
1619
1620 # Response that covers auth tokens, draft ID, and upload URL
1621 payload = {
1622 "token_type": "Bearer",
1623 "expires_in": 3600,
1624 "access_token": access_token,
1625 "refresh_token": new_token,
1626 "id": "draft-id-no",
1627 "uploadUrl": "https://upload.url.example/session",
1628 }
1629 okay_response = mock.Mock()
1630 okay_response.content = dumps(payload)
1631 okay_response.status_code = requests.codes.ok
1632 mock_post.return_value = okay_response
1633 mock_get.return_value = okay_response
1634 mock_put.return_value = okay_response
1635
1636 path = os.path.join(TEST_VAR_DIR, "apprise-test.gif")
1637 attach = AppriseAttachment(path)
1638
1639 obj = NotifyOffice365(
1640 source="[email protected]",
1641 client_id=client_id,
1642 secret=seed_token,
1643 targets=["[email protected]"],
1644 )
1645 assert obj.mode == Office365Mode.PERSONAL
1646
1647 # Force all attachments to be "large" so the draft path is used
1648 obj.outlook_attachment_inline_max = 50
1649
1650 assert (
1651 bool(
1652 obj.notify(
1653 body="body",
1654 title="title",
1655 notify_type=NotifyType.INFO,
1656 attach=attach,
1657 )
1658 )
1659 is True
1660 )
1661
1662 # POST 0: token refresh POST 1: draft create POST 2: upload session
1663 # POST 3: send draft
1664 assert mock_post.call_count == 4
1665 assert (
1666 mock_post.call_args_list[0][0][0]
1667 == "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"
1668 )
1669 assert (
1670 mock_post.call_args_list[1][0][0]
1671 == "https://graph.microsoft.com/v1.0/me/messages"
1672 )
1673 assert (
1674 mock_post.call_args_list[2][0][0]
1675 == "https://graph.microsoft.com/v1.0/me/"
1676 "message/draft-id-no/attachments/createUploadSession"
1677 )
1678 assert (
1679 mock_post.call_args_list[3][0][0] == "https://graph.microsoft.com/v1.0"
1680 "/me/messages/draft-id-no/send"
1681 )
1682
1683
1684 def test_plugin_office365_cc_bcc_invalid_branch():
1685 """NotifyOffice365() CC/BCC/Reply-To invalid entries dropped."""
1686
1687 # Build a NotifyOffice365 in personal mode with:
1688 # cc = one valid address + one that parse_emails passes through
1689 # but is_email rejects (hits the FALSE branch in the CC loop).
1690 # A list must be used -- parse_emails filters invalid tokens
1691 # out of comma-separated strings before is_email is called.
1692 # bcc = same, for the FALSE branch in the BCC loop
1693 # reply_to = same, for the FALSE branch in the Reply-To loop
1694 obj = NotifyOffice365(
1695 client_id="aa-bb-cc",
1696 secret="seed-refresh-token",
1697 source="[email protected]",
1698 targets=["[email protected]"],
1699 cc=["[email protected]", "notanemail"],
1700 bcc=["[email protected]", "alsonotanemail"],
1701 reply_to=["[email protected]", "badreply"],
1702 )
1703
1704 # Valid CC entry was added; invalid one was silently dropped
1705 assert "[email protected]" in obj.cc
1706 assert len(obj.cc) == 1
1707
1708 # Valid BCC entry was added; invalid one was silently dropped
1709 assert "[email protected]" in obj.bcc
1710 assert len(obj.bcc) == 1
1711
1712 # Valid Reply-To entry was added; invalid one was silently dropped
1713 assert "[email protected]" in obj.reply_to
1714 assert len(obj.reply_to) == 1