File: test_plugin_mastodon.py

package info (click to toggle)
apprise 1.9.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,792 kB
  • sloc: python: 74,226; sh: 132; makefile: 6
file content (746 lines) | stat: -rw-r--r-- 25,025 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
# -*- coding: utf-8 -*-
# BSD 2-Clause License
#
# Apprise - Push Notification Library.
# Copyright (c) 2025, Chris Caron <lead2gold@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import os
from unittest import mock

import requests
from json import dumps, loads
from datetime import datetime
from datetime import timezone
from apprise import Apprise
from apprise import NotifyType
from apprise import AppriseAttachment
from apprise.plugins.mastodon import NotifyMastodon
from helpers import AppriseURLTester

# Disable logging for a cleaner testing output
import logging
logging.disable(logging.CRITICAL)

# Attachment Directory
TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), 'var')

# Our Testing URLs
apprise_url_tests = (
    ##################################
    # NotifyMastodon
    ##################################
    ('mastodon://', {
        # Missing Everything :)
        'instance': None,
    }),
    ('mastodon://:@/', {
        'instance': None,
    }),
    ('mastodon://hostname', {
        # Missing Access Token
        'instance': TypeError,
    }),
    ('toot://access_token@hostname', {
        # We're good; it's a simple notification
        'instance': NotifyMastodon,
    }),
    ('toots://access_token@hostname', {
        # We're good; it's another simple notification
        'instance': NotifyMastodon,
        # Our expected url(privacy=True) startswith() response:
        'privacy_url': 'mastodons://****@hostname/'
    }),
    ('mastodon://access_token@hostname/@user/@user2', {
        # We're good; it's another simple notification
        'instance': NotifyMastodon,
        # Our expected url(privacy=True) startswith() response:
        'privacy_url': 'mastodon://****@hostname/@user/@user2'
    }),
    ('mastodon://hostname/@user/@user2?token=abcd123', {
        # Our access token can be provided as a token= variable
        'instance': NotifyMastodon,
        # Our expected url(privacy=True) startswith() response:
        'privacy_url': 'mastodon://****@hostname/@user/@user2'
    }),
    ('mastodon://access_token@hostname?to=@user, @user2', {
        # We're good; it's another simple notification
        'instance': NotifyMastodon,
        # Our expected url(privacy=True) startswith() response:
        'privacy_url': 'mastodon://****@hostname/@user/@user2'
    }),
    ('mastodon://access_token@hostname/?cache=no', {
        # disable cache as a test
        'instance': NotifyMastodon,
    }),
    ('mastodon://access_token@hostname/?spoiler=spoiler%20text', {
        # a public post
        'instance': NotifyMastodon,
    }),
    ('mastodon://access_token@hostname/?language=en', {
        # over-ride our language
        'instance': NotifyMastodon,
    }),
    ('mastodons://access_token@hostname:8443', {
        # A custom port specified
        'instance': NotifyMastodon,
    }),
    ('mastodon://access_token@hostname/?key=My%20Idempotency%20Key', {
        # Prevent duplicate submissions of the same status. Idempotency
        # keys are stored for up to 1 hour, and can be any arbitrary string.
        # Consider using a hash or UUID generated client-side.
        'instance': NotifyMastodon,
    }),
    ('mastodon://access_token@hostname/-/%/', {
        # Invalid users specified
        'instance': TypeError,
    }),
    ('mastodon://access_token@hostname?visibility=invalid', {
        # An invalid visibility
        'instance': TypeError,
    }),
    ('mastodon://access_token@hostname?visibility=direct', {
        # A direct message
        'instance': NotifyMastodon,
        # Expected notify() response False (because we won't
        # get the response we were expecting from the upstream
        # server
        'notify_response': False,
    }),
    ('mastodon://access_token@hostname?visibility=direct', {
        # A direct message
        'instance': NotifyMastodon,
        # Provide a response that allows us to look our content up
        'requests_response_text': {
            'id': '12345',
            'username': 'test',
        },
    }),
    ('toots://access_token@hostname', {
        'instance': NotifyMastodon,
        # Throws a series of connection and transfer exceptions when this flag
        # is set and tests that we gracfully handle them
        'test_requests_exceptions': True,
    }),
)


def test_plugin_mastodon_urls():
    """
    NotifyMastodon() Apprise URLs

    """

    # Run our general tests
    AppriseURLTester(tests=apprise_url_tests).run_all()


@mock.patch('requests.get')
@mock.patch('requests.post')
def test_plugin_mastodon_general(mock_post, mock_get):
    """
    NotifyMastodon() General Tests

    """
    token = 'access_key'
    host = 'nuxref.com'

    response_obj = {
        'username': 'caronc',
        'id': 1234,
    }

    # Epoch time:
    epoch = datetime.fromtimestamp(0, timezone.utc)

    request = mock.Mock()
    request.content = dumps(response_obj)
    request.status_code = requests.codes.ok
    request.headers = {
        'X-RateLimit-Limit': (
            datetime.now(timezone.utc) - epoch).total_seconds(),
        'X-RateLimit-Remaining': 1,
    }

    # Prepare Mock
    mock_get.return_value = request
    mock_post.return_value = request

    # Instantiate our object
    obj = NotifyMastodon(token=token, host=host)

    assert isinstance(obj, NotifyMastodon)
    assert isinstance(obj.url(), str)

    # apprise room was found
    assert obj.send(body="test") is True

    # Change our status code and try again
    request.status_code = 403
    assert obj.send(body="test") is False
    assert obj.ratelimit_remaining == 1

    # Return the status
    request.status_code = requests.codes.ok
    # Force a reset
    request.headers['X-RateLimit-Remaining'] = 0
    # behind the scenes, it should cause us to update our rate limit
    assert obj.send(body="test") is True
    assert obj.ratelimit_remaining == 0

    # This should cause us to block
    request.headers['X-RateLimit-Remaining'] = 10
    assert obj.send(body="test") is True
    assert obj.ratelimit_remaining == 10

    # Handle cases where we simply couldn't get this field
    del request.headers['X-RateLimit-Remaining']
    assert obj.send(body="test") is True
    # It remains set to the last value
    assert obj.ratelimit_remaining == 10

    # Reset our variable back to 1
    request.headers['X-RateLimit-Remaining'] = 1

    # Handle cases where our epoch time is wrong
    del request.headers['X-RateLimit-Limit']
    assert obj.send(body="test") is True

    # Return our object, but place it in the future forcing us to block
    request.headers['X-RateLimit-Limit'] = \
        (datetime.now(timezone.utc) - epoch).total_seconds() + 1
    request.headers['X-RateLimit-Remaining'] = 0
    obj.ratelimit_remaining = 0
    assert obj.send(body="test") is True

    # Return our object, but place it in the future forcing us to block
    request.headers['X-RateLimit-Limit'] = \
        (datetime.now(timezone.utc) - epoch).total_seconds() - 1
    request.headers['X-RateLimit-Remaining'] = 0
    obj.ratelimit_remaining = 0
    assert obj.send(body="test") is True

    # Return our limits to always work
    request.headers['X-RateLimit-Limit'] = \
        (datetime.now(timezone.utc) - epoch).total_seconds()
    request.headers['X-RateLimit-Remaining'] = 1
    obj.ratelimit_remaining = 1

    # Alter pending targets
    obj.targets.append('usera')
    request.content = dumps(response_obj)
    response_obj = {
        'username': 'usera',
        'id': 4321,
    }

    # Cause content response to be None
    request.content = None
    assert obj.send(body="test") is True

    # Invalid JSON
    request.content = '{'
    assert obj.send(body="test") is True

    # Return it to a parseable string
    request.content = '{}'

    results = NotifyMastodon.parse_url(
        'mastodon://{}@{}/@user?visbility=direct'.format(token, host))
    assert isinstance(results, dict)
    assert '@user' in results['targets']

    # cause a json parsing issue now
    response_obj = None
    assert obj.send(body="test") is True

    response_obj = '{'
    assert obj.send(body="test") is True

    mock_get.reset_mock()
    mock_post.reset_mock()

    #
    # Test our lazy lookups
    #

    # Prepare a good status response
    request = mock.Mock()
    request.content = dumps({'id': '1234', 'username': 'caronc'})
    request.status_code = requests.codes.ok
    mock_get.return_value = request

    mastodon_url = 'mastodons://key@host?visibility=direct'
    obj = Apprise.instantiate(mastodon_url)
    obj._whoami(lazy=True)
    assert mock_get.call_count == 1
    assert mock_get.call_args_list[0][0][0] == \
        'https://host/api/v1/accounts/verify_credentials'

    mock_get.reset_mock()
    obj._whoami(lazy=True)
    assert mock_get.call_count == 0

    mock_get.reset_mock()
    obj._whoami(lazy=False)
    assert mock_get.call_count == 1
    assert mock_get.call_args_list[0][0][0] == \
        'https://host/api/v1/accounts/verify_credentials'


@mock.patch('requests.post')
@mock.patch('requests.get')
def test_plugin_mastodon_attachments(mock_get, mock_post):
    """
    NotifyMastodon() Toot Attachment Checks

    """
    akey = 'access_key'
    host = 'nuxref.com'
    username = 'caronc'

    # Prepare a good status response
    good_response_obj = {
        'id': '1234',
    }

    good_response = mock.Mock()
    good_response.content = dumps(good_response_obj)
    good_response.status_code = requests.codes.ok

    # Prepare a good whoami response
    good_whoami_response_obj = {
        'username': username,
        'id': '9876',
    }

    good_whoami_response = mock.Mock()
    good_whoami_response.content = dumps(good_whoami_response_obj)
    good_whoami_response.status_code = requests.codes.ok

    # Prepare bad response
    bad_response = mock.Mock()
    bad_response.content = dumps({})
    bad_response.status_code = requests.codes.internal_server_error

    # Prepare a good media response
    good_media_response = mock.Mock()
    good_media_response.content = dumps({
        "id": '710511363345354753',
        "file_mime": "image/jpeg",
    })
    good_media_response.status_code = requests.codes.ok

    #
    #  Start testing using fixtures above
    #
    mock_post.side_effect = [good_media_response, good_response]
    mock_get.return_value = good_whoami_response

    mastodon_url = 'mastodon://{}@{}'.format(akey, host)

    # attach our content
    attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, 'apprise-test.gif'))

    # instantiate our object
    obj = Apprise.instantiate(mastodon_url)

    # Send our notification
    assert obj.notify(
        body='body', title='title', notify_type=NotifyType.INFO,
        attach=attach) is True

    # Test our call count
    assert mock_get.call_count == 0
    assert mock_post.call_count == 2
    assert mock_post.call_args_list[0][0][0] == \
        'http://nuxref.com/api/v1/media'
    assert mock_post.call_args_list[1][0][0] == \
        'http://nuxref.com/api/v1/statuses'

    # Test our media payload
    assert 'files' in mock_post.call_args_list[0][1]
    assert 'file' in mock_post.call_args_list[0][1]['files']
    assert mock_post.call_args_list[0][1]['files']['file'][0] \
        == 'apprise-test.gif'

    # Test our status payload
    payload = loads(mock_post.call_args_list[1][1]['data'])
    assert 'status' in payload
    assert payload['status'] == 'title\r\nbody'
    assert 'sensitive' in payload
    assert payload['sensitive'] is False
    assert 'media_ids' in payload
    assert isinstance(payload['media_ids'], list)
    assert len(payload['media_ids']) == 1
    assert payload['media_ids'][0] == '710511363345354753'

    # Verify we don't set incorrect keys not otherwise specified
    assert 'spoiler_text' not in payload

    mock_get.reset_mock()
    mock_post.reset_mock()

    #
    # Handle the query again, but this time perform a direct message
    # requiring us to look up who we are
    #
    mock_post.side_effect = [good_media_response, good_response]
    mock_get.return_value = good_whoami_response

    mastodon_url = 'mastodon://{}@{}?visibility=direct'.format(akey, host)

    # attach our content
    attach = AppriseAttachment(os.path.join(TEST_VAR_DIR, 'apprise-test.gif'))

    # instantiate our object
    obj = Apprise.instantiate(mastodon_url)

    # Send our notification
    assert obj.notify(
        body='body', title='title', notify_type=NotifyType.INFO,
        attach=attach) is True

    # Test our call count
    assert mock_get.call_count == 1
    assert mock_post.call_count == 2
    assert mock_get.call_args_list[0][0][0] == \
        'http://nuxref.com/api/v1/accounts/verify_credentials'
    assert mock_post.call_args_list[0][0][0] == \
        'http://nuxref.com/api/v1/media'
    assert mock_post.call_args_list[1][0][0] == \
        'http://nuxref.com/api/v1/statuses'

    # Test our status payload
    payload = loads(mock_post.call_args_list[1][1]['data'])
    assert 'status' in payload
    # Our ID was added into the payload
    assert payload['status'] == '@caronc title\r\nbody'
    assert 'sensitive' in payload
    assert payload['sensitive'] is False
    assert 'media_ids' in payload
    assert isinstance(payload['media_ids'], list)
    assert len(payload['media_ids']) == 1
    assert payload['media_ids'][0] == '710511363345354753'

    mock_get.reset_mock()
    mock_post.reset_mock()

    # Store 3 attachments
    attach = (
        AppriseAttachment(os.path.join(TEST_VAR_DIR, 'apprise-test.gif')),
        AppriseAttachment(os.path.join(TEST_VAR_DIR, 'apprise-test.png')),
        AppriseAttachment(os.path.join(TEST_VAR_DIR, 'apprise-test.jpeg')),
    )

    # Prepare a good media response
    mr1 = mock.Mock()
    mr1.content = dumps({
        "id": '1',
        "file_mime": "image/gif",
    })
    mr1.status_code = requests.codes.ok

    mr2 = mock.Mock()
    mr2.content = dumps({
        "id": '2',
        "file_mime": "image/png",
    })
    mr2.status_code = requests.codes.ok

    mr3 = mock.Mock()
    mr3.content = dumps({
        "id": '3',
        "file_mime": "image/jpeg",
    })
    mr3.status_code = requests.codes.ok

    # Return 3 good uploads and a good status response
    mock_post.side_effect = [mr1, mr2, mr3, good_response, good_response]
    mock_get.return_value = good_whoami_response

    # instantiate our object
    mastodon_url = 'mastodons://{}@{}' \
        '?visibility=direct&sensitive=yes&key=abcd'.format(akey, host)
    obj = Apprise.instantiate(mastodon_url)

    # Send ourselves a direct message where our ID was already found
    # in the body.  This smart detection method will prevent us from
    # adding the @caronc to the begining of the same message (since it's a
    # direct message)
    assert obj.notify(
        body='Check this out @caronc', title='Apprise',
        notify_type=NotifyType.INFO,
        attach=attach) is True

    # Test our call count
    assert mock_get.call_count == 1
    assert mock_post.call_count == 5
    assert mock_post.call_args_list[0][0][0] == \
        'https://nuxref.com/api/v1/media'
    assert mock_post.call_args_list[1][0][0] == \
        'https://nuxref.com/api/v1/media'
    assert mock_post.call_args_list[2][0][0] == \
        'https://nuxref.com/api/v1/media'
    # Our status's will batch up and send the last 2 images in one
    # and our animated gif in one.
    assert mock_post.call_args_list[3][0][0] == \
        'https://nuxref.com/api/v1/statuses'
    assert mock_post.call_args_list[4][0][0] == \
        'https://nuxref.com/api/v1/statuses'
    assert mock_get.call_args_list[0][0][0] == \
        'https://nuxref.com/api/v1/accounts/verify_credentials'

    # Test our status payload
    payload = loads(mock_post.call_args_list[3][1]['data'])
    assert 'status' in payload
    assert payload['status'] == 'Apprise\r\nCheck this out @caronc'
    assert 'sensitive' in payload
    assert payload['sensitive'] is True
    assert 'language' not in payload
    assert 'Idempotency-Key' in payload
    assert payload['Idempotency-Key'] == 'abcd'
    assert 'media_ids' in payload
    assert isinstance(payload['media_ids'], list)
    assert len(payload['media_ids']) == 1
    assert payload['media_ids'][0] == '1'

    payload = loads(mock_post.call_args_list[4][1]['data'])
    assert 'status' in payload
    assert payload['status'] == '02/02'
    assert 'sensitive' in payload
    assert payload['sensitive'] is False
    assert 'language' not in payload
    assert 'Idempotency-Key' in payload
    assert payload['Idempotency-Key'] == 'abcd-part01'
    assert 'media_ids' in payload
    assert isinstance(payload['media_ids'], list)
    assert len(payload['media_ids']) == 2
    assert '2' in payload['media_ids']
    assert '3' in payload['media_ids']

    # A second call does not cause us to look up our ID as we already know it
    mock_get.reset_mock()
    mock_post.reset_mock()
    mock_post.side_effect = [mr1, mr2, mr3, good_response, good_response]
    mock_get.return_value = good_whoami_response
    assert obj.notify(
        body='Check this out @caronc', title='Apprise',
        notify_type=NotifyType.INFO,
        attach=attach) is True

    # Same number of posts
    assert mock_post.call_count == 5
    # But no lookup was made
    assert mock_get.call_count == 0

    mock_get.reset_mock()
    mock_post.reset_mock()

    # Prepare an attach list
    attach = (
        os.path.join(TEST_VAR_DIR, 'apprise-test.png'),
        os.path.join(TEST_VAR_DIR, 'apprise-test.jpeg'),
    )

    mock_post.side_effect = [mr2, mr3, good_response, good_response]
    mock_get.return_value = good_whoami_response

    # instantiate our object (but turn off the batch mode)
    mastodon_url = 'mastodons://{}@{}?batch=no'.format(
        akey, host)
    obj = Apprise.instantiate(mastodon_url)

    assert obj.notify(
        body='Check this out @caronc', title='Apprise',
        notify_type=NotifyType.INFO,
        attach=attach) is True

    # 2 attachments + 2 different status messages
    assert mock_post.call_count == 4

    # But no lookup was made
    assert mock_get.call_count == 0

    assert mock_post.call_args_list[0][0][0] == \
        'https://nuxref.com/api/v1/media'
    assert mock_post.call_args_list[1][0][0] == \
        'https://nuxref.com/api/v1/media'
    assert mock_post.call_args_list[2][0][0] == \
        'https://nuxref.com/api/v1/statuses'
    assert mock_post.call_args_list[3][0][0] == \
        'https://nuxref.com/api/v1/statuses'

    mock_get.reset_mock()
    mock_post.reset_mock()

    # Prepare a bad media response
    bad_response = mock.Mock()
    bad_response.status_code = requests.codes.internal_server_error

    bad_responses = (
        dumps({"error": "authorized scopes"}),
        '',
    )

    #
    # Test our Media failures
    #

    # Try several bad responses so we can capture the block of code where
    # we try to help the end user to remind them what scope they're missing
    for response in bad_responses:
        mock_post.side_effect = [good_media_response, bad_response]
        bad_response.content = response

        # instantiate our object
        mastodon_url = \
            'mastodons://{}@{}?visibility=public&spoiler=uhoh'.format(
                akey, host)
        obj = Apprise.instantiate(mastodon_url)

        # Our notification will fail now since our toot will error out
        # This is the same test as above, except our error response isn't
        # parseable
        assert obj.notify(
            body='body', title='title', notify_type=NotifyType.INFO,
            attach=attach) is False

        # Test our call count
        assert mock_get.call_count == 0
        assert mock_post.call_count == 2
        assert mock_post.call_args_list[0][0][0] == \
            'https://nuxref.com/api/v1/media'
        assert mock_post.call_args_list[1][0][0] == \
            'https://nuxref.com/api/v1/media'

        mock_get.reset_mock()
        mock_post.reset_mock()

    #
    # Test our Status failures
    #

    # Try several bad responses so we can capture the block of code where
    # we try to help the end user to remind them what scope they're missing
    for response in bad_responses:
        mock_post.side_effect = [bad_response]
        bad_response.content = response

        # instantiate our object
        mastodon_url = 'mastodons://{}@{}'.format(akey, host)
        obj = Apprise.instantiate(mastodon_url)

        # Our notification will fail now since our toot will error out
        # This is the same test as above, except our error response isn't
        # parseable
        assert obj.notify(
            body='body', title='title', notify_type=NotifyType.INFO) is False

        # Test our call count
        assert mock_get.call_count == 0
        assert mock_post.call_count == 1
        assert mock_post.call_args_list[0][0][0] == \
            'https://nuxref.com/api/v1/statuses'

        mock_get.reset_mock()
        mock_post.reset_mock()

    #
    # Test our whoami failures
    #

    # Try several bad responses so we can capture the block of code where
    # we try to help the end user to remind them what scope they're missing
    for response in bad_responses:
        mock_get.side_effect = [bad_response]
        bad_response.content = response

        # instantiate our object
        mastodon_url = 'mastodons://{}@{}?visibility=direct'.format(akey, host)
        obj = Apprise.instantiate(mastodon_url)

        # Our notification will fail now since our toot will error out
        # This is the same test as above, except our error response isn't
        # parseable
        assert obj.notify(
            body='body', title='title', notify_type=NotifyType.INFO) is False

        # Test our call count
        assert mock_get.call_count == 1
        assert mock_post.call_count == 0
        assert mock_get.call_args_list[0][0][0] == \
            'https://nuxref.com/api/v1/accounts/verify_credentials'

        mock_get.reset_mock()
        mock_post.reset_mock()

    mock_post.side_effect = [mr1, mr2, mr3, good_response, good_response]
    mock_get.return_value = None

    # instantiate our object
    mastodon_url = 'mastodons://{}@{}'.format(akey, host)
    obj = Apprise.instantiate(mastodon_url)

    # An invalid attachment will cause a failure
    path = os.path.join(TEST_VAR_DIR, '/invalid/path/to/an/invalid/file.jpg')
    assert obj.notify(
        body='body', title='title', notify_type=NotifyType.INFO,
        attach=path) is False

    # No get requests are made
    assert mock_get.call_count == 0

    # No post request as attachment is no good anyway
    assert mock_post.call_count == 0

    mock_get.reset_mock()
    mock_post.reset_mock()

    # We have an OSError thrown in the middle of our preparation
    mock_post.side_effect = [
        good_media_response, OSError(), good_media_response]
    mock_get.return_value = good_response

    # 3 images are produced
    attach = [
        os.path.join(TEST_VAR_DIR, 'apprise-test.gif'),
        # This one is not supported, so it's ignored gracefully
        os.path.join(TEST_VAR_DIR, 'apprise-archive.zip'),
        # A supported video file
        os.path.join(TEST_VAR_DIR, 'apprise-test.mp4'),
    ]

    # We'll fail to send this time
    assert obj.notify(
        body='body', title='title', notify_type=NotifyType.INFO,
        attach=attach) is False

    assert mock_get.call_count == 0
    # No get request as cached response is used
    assert mock_post.call_count == 2
    assert mock_post.call_args_list[0][0][0] == \
        'https://nuxref.com/api/v1/media'
    assert mock_post.call_args_list[1][0][0] == \
        'https://nuxref.com/api/v1/media'