File: test_apprise_cli.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 (1795 lines) | stat: -rw-r--r-- 54,177 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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
# -*- 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
import re
from unittest import mock
import pytest
import sys
import requests
import json
from inspect import cleandoc
from os.path import dirname
from os.path import join
from apprise import cli
from apprise import NotifyBase
from apprise import NotificationManager
from click.testing import CliRunner
from helpers import environ
from apprise.locale import gettext_lazy as _

from importlib import reload

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

# Grant access to our Notification Manager Singleton
N_MGR = NotificationManager()


def test_apprise_cli_nux_env(tmpdir):
    """
    CLI: Nux Environment

    """

    class GoodNotification(NotifyBase):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

        def notify(self, **kwargs):
            # Pretend everything is okay (when passing --disable-async)
            return True

        async def async_notify(self, **kwargs):
            # Pretend everything is okay
            return True

        def url(self, *args, **kwargs):
            # Support url()
            return 'good://'

    class BadNotification(NotifyBase):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

        async def async_notify(self, **kwargs):
            # Pretend everything is okay
            return False

        def url(self, *args, **kwargs):
            # Support url()
            return 'bad://'

    # Set up our notification types
    N_MGR['good'] = GoodNotification
    N_MGR['bad'] = BadNotification

    runner = CliRunner()
    result = runner.invoke(cli.main)
    # no servers specified; we return 1 (non-zero)
    assert result.exit_code == 1

    result = runner.invoke(cli.main, ['-v'])
    assert result.exit_code == 1

    result = runner.invoke(cli.main, ['-vv'])
    assert result.exit_code == 1

    result = runner.invoke(cli.main, ['-vvv'])
    assert result.exit_code == 1

    result = runner.invoke(cli.main, ['-vvvv'])
    assert result.exit_code == 1

    # Display version information and exit
    result = runner.invoke(cli.main, ['-V'])
    assert result.exit_code == 0

    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        'good://localhost',
    ])
    assert result.exit_code == 0

    with mock.patch('requests.post') as mock_post:
        # Prepare Mock
        mock_post.return_value = requests.Request()
        mock_post.return_value.status_code = requests.codes.ok

        result = runner.invoke(cli.main, [
            '-t', 'test title',
            '-b', 'test body\\nsNewLine',
            # Test using interpret escapes
            '-e',
            # Use our JSON query
            'json://localhost',
        ])
        assert result.exit_code == 0

        # Test our call count
        assert mock_post.call_count == 1

        # Our string is now escaped correctly
        json.loads(mock_post.call_args_list[0][1]['data'])\
            .get('message', '') == 'test body\nsNewLine'

        # Reset
        mock_post.reset_mock()

        result = runner.invoke(cli.main, [
            '-t', 'test title',
            '-b', 'test body\\nsNewLine',
            # No -e switch at all (so we don't escape the above)
            # Use our JSON query
            'json://localhost',
        ])
        assert result.exit_code == 0

        # Test our call count
        assert mock_post.call_count == 1

        # Our string is now escaped correctly
        json.loads(mock_post.call_args_list[0][1]['data'])\
            .get('message', '') == 'test body\\nsNewLine'

    # Run in synchronous mode
    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        'good://localhost',
        '--disable-async',
    ])
    assert result.exit_code == 0

    # Test Debug Mode (--debug)
    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        'good://localhost',
        '--debug',
    ])
    assert result.exit_code == 0

    # Test Debug Mode (-D)
    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        'good://localhost',
        '-D',
    ])
    assert result.exit_code == 0

    result = runner.invoke(cli.main, [
        '-t', 'test title',
        'good://localhost',
    ], input='test stdin body\n')
    assert result.exit_code == 0

    # Run in synchronous mode
    result = runner.invoke(cli.main, [
        '-t', 'test title',
        'good://localhost',
        '--disable-async',
    ], input='test stdin body\n')
    assert result.exit_code == 0

    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        'bad://localhost',
    ])
    assert result.exit_code == 1

    # Run in synchronous mode
    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        'bad://localhost',
        '-Da',
    ])
    assert result.exit_code == 1

    # Testing with the --dry-run flag reveals a successful response since we
    # don't actually execute the bad:// notification; we only display it
    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        'bad://localhost',
        '--dry-run',
    ])
    assert result.exit_code == 0

    # Write a simple text based configuration file
    t = tmpdir.mkdir("apprise-obj").join("apprise")
    buf = """
    # Include ourselves
    include {}

    taga,tagb=good://localhost
    tagc=good://nuxref.com
    """.format(str(t))
    t.write(buf)

    # This will read our configuration and not send any notices at all
    # because we assigned tags to all of our urls and didn't identify
    # a specific match below.

    # 'include' reference in configuration file would have included the file a
    # second time (since recursion default is 1).
    result = runner.invoke(cli.main, [
        '-b', 'test config',
        '--config', str(t),
    ])
    # Even when recursion take place, tags are all honored
    # so 2 is returned because nothing was notified
    assert result.exit_code == 3

    # This will send out 1 notification because our tag matches
    # one of the entries above
    # translation: has taga
    result = runner.invoke(cli.main, [
        '-b', 'has taga',
        '--config', str(t),
        '--tag', 'taga',
    ])
    assert result.exit_code == 0

    # Test recursion
    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        '--config', str(t),
        '--tag', 'tagc',
        # Invalid entry specified for recursion
        '-R', 'invalid',
    ])
    assert result.exit_code == 2

    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        '--config', str(t),
        '--tag', 'tagc',
        # missing entry specified for recursion
        '--recursive-depth',
    ])
    assert result.exit_code == 2

    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        '--config', str(t),
        '--tag', 'tagc',
        # Disable recursion (thus inclusion will be ignored)
        '-R', '0',
    ])
    assert result.exit_code == 0

    # Test recursion
    result = runner.invoke(cli.main, [
        '-t', 'test title',
        '-b', 'test body',
        '--config', str(t),
        '--tag', 'tagc',
        # Recurse up to 5 times
        '--recursion-depth', '5',
    ])
    assert result.exit_code == 0

    # This will send out 2 notifications because by specifying 2 tag
    # entries, we 'or' them together:
    # translation: has taga or tagb or tagd
    result = runner.invoke(cli.main, [
        '-b', 'has taga OR tagc OR tagd',
        '--config', str(t),
        '--tag', 'taga',
        '--tag', 'tagc',
        '--tag', 'tagd',
    ])
    assert result.exit_code == 0

    # Write a simple text based configuration file
    t = tmpdir.mkdir("apprise-obj2").join("apprise-test2")
    buf = """
    good://localhost/1
    good://localhost/2
    good://localhost/3
    good://localhost/4
    good://localhost/5
    myTag=good://localhost/6
    """
    t.write(buf)

    # This will read our configuration and send a notification to
    # the first 5 entries in the list, but not the one that has
    # the tag associated with it
    result = runner.invoke(cli.main, [
        '-b', 'test config',
        '--config', str(t),
    ])
    assert result.exit_code == 0

    # Test our notification type switch (it defaults to info) so we want to
    # try it as a different value. Should return without a problem
    result = runner.invoke(cli.main, [
        '-b', '# test config',
        '--config', str(t),
        '-n', 'success',
    ])
    assert result.exit_code == 0

    # Test our notification type switch when set to something unsupported
    result = runner.invoke(cli.main, [
        '-b', 'test config',
        '--config', str(t),
        '--notification-type', 'invalid',
    ])
    # An error code of 2 is returned if invalid input is specified on the
    # command line
    assert result.exit_code == 2

    # The notification type switch is case-insensitive
    result = runner.invoke(cli.main, [
        '-b', 'test config',
        '--config', str(t),
        '--notification-type', 'WARNING',
    ])
    assert result.exit_code == 0

    # Test our formatting switch (it defaults to text) so we want to try it as
    # a different value. Should return without a problem
    result = runner.invoke(cli.main, [
        '-b', '# test config',
        '--config', str(t),
        '-i', 'markdown',
    ])
    assert result.exit_code == 0

    # Test our formatting switch when set to something unsupported
    result = runner.invoke(cli.main, [
        '-b', 'test config',
        '--config', str(t),
        '--input-format', 'invalid',
    ])
    # An error code of 2 is returned if invalid input is specified on the
    # command line
    assert result.exit_code == 2

    # The formatting switch is not case sensitive
    result = runner.invoke(cli.main, [
        '-b', '# test config',
        '--config', str(t),
        '--input-format', 'HTML',
    ])
    assert result.exit_code == 0

    # As a way of ensuring we match the first 5 entries, we can run a
    # --dry-run against the same result set above and verify the output
    result = runner.invoke(cli.main, [
        '-b', 'test config',
        '--config', str(t),
        '--dry-run',
    ])
    assert result.exit_code == 0
    lines = re.split(r'[\r\n]', result.output.strip())
    # 5 lines of all good:// entries matched + url id underneath
    assert len(lines) == 10
    # Verify we match against the remaining good:// entries
    for i in range(0, 10, 2):
        assert lines[i].endswith('good://')

    # This will fail because nothing matches mytag. It's case sensitive
    # and we would only actually match against myTag
    result = runner.invoke(cli.main, [
        '-b', 'has mytag',
        '--config', str(t),
        '--tag', 'mytag',
    ])
    assert result.exit_code == 3

    # Same command as the one identified above except we set the --dry-run
    # flag. This causes our list of matched results to be printed only.
    # However, since we don't match anything; we still fail with a return code
    # of 2.
    result = runner.invoke(cli.main, [
        '-b', 'has mytag',
        '--config', str(t),
        '--tag', 'mytag',
        '--dry-run'
    ])
    assert result.exit_code == 3

    # Here is a case where we get what was expected; we also attach a file
    result = runner.invoke(cli.main, [
        '-b', 'has myTag',
        '--config', str(t),
        '--attach', join(dirname(__file__), 'var', 'apprise-test.gif'),
        '--tag', 'myTag',
    ])
    assert result.exit_code == 0

    # Testing with the --dry-run flag reveals the same positive results
    # because there was at least one match
    result = runner.invoke(cli.main, [
        '-b', 'has myTag',
        '--config', str(t),
        '--tag', 'myTag',
        '--dry-run',
    ])
    assert result.exit_code == 0

    #
    # Test environment variables
    #
    # Write a simple text based configuration file
    t2 = tmpdir.mkdir("apprise-obj-env").join("apprise")
    buf = """
    # A general one
    good://localhost

    # A failure (if we use the fail tag)
    fail=bad://localhost

    # A normal one tied to myTag
    myTag=good://nuxref.com
    """
    t2.write(buf)

    with environ(APPRISE_URLS="good://localhost"):
        # This will load okay because we defined the environment
        # variable with a valid URL
        result = runner.invoke(cli.main, [
            '-b', 'test environment',
            # Test that we ignore our tag
            '--tag', 'mytag',
        ])
        assert result.exit_code == 0

        # Same action but without --tag
        result = runner.invoke(cli.main, [
            '-b', 'test environment',
        ])
        assert result.exit_code == 0

    with mock.patch('apprise.cli.DEFAULT_CONFIG_PATHS', []):
        with environ(APPRISE_URLS="      "):
            # An empty string is not valid and therefore not loaded so the
            # below fails. We override the DEFAULT_CONFIG_PATHS because we
            # don't want to detect ones loaded on the machine running the unit
            # tests
            result = runner.invoke(cli.main, [
                '-b', 'test environment',
            ])
            assert result.exit_code == 1

    with environ(APPRISE_URLS="bad://localhost"):
        result = runner.invoke(cli.main, [
            '-b', 'test environment',
        ])
        assert result.exit_code == 1

        # If we specify an inline URL, it will over-ride the environment
        # variable
        result = runner.invoke(cli.main, [
            '-t', 'test title',
            '-b', 'test body',
            'good://localhost',
        ])
        assert result.exit_code == 0

        # A Config file also over-rides the environment variable if
        # specified on the command line:
        result = runner.invoke(cli.main, [
            '-b', 'has myTag',
            '--config', str(t2),
            '--tag', 'myTag',
        ])
        assert result.exit_code == 0

    with environ(APPRISE_CONFIG=str(t2)):
        # Deprecated test case
        result = runner.invoke(cli.main, [
            '-b', 'has myTag',
            '--tag', 'myTag',
        ])
        assert result.exit_code == 0

    with environ(APPRISE_CONFIG_PATH=str(t2)):
        # Our configuration file will load from our environmment variable
        result = runner.invoke(cli.main, [
            '-b', 'has myTag',
            '--tag', 'myTag',
        ])
        assert result.exit_code == 0

    with environ(APPRISE_CONFIG_PATH=str(t2) + ';/another/path'):
        # Our configuration file will load from our environmment variable
        result = runner.invoke(cli.main, [
            '-b', 'has myTag',
            '--tag', 'myTag',
        ])
        assert result.exit_code == 0

    with mock.patch('apprise.cli.DEFAULT_CONFIG_PATHS', []):
        with environ(APPRISE_CONFIG="      "):
            # We will fail to send the notification as no path was
            # specified.
            # We override the DEFAULT_CONFIG_PATHS because we don't
            # want to detect ones loaded on the machine running the unit tests
            result = runner.invoke(cli.main, [
                '-b', 'my message',
            ])
            assert result.exit_code == 1

    with environ(APPRISE_CONFIG="garbage/file/path.yaml"):
        # We will fail to send the notification as the path
        # specified is not loadable
        result = runner.invoke(cli.main, [
            '-b', 'my message',
        ])
        assert result.exit_code == 1

        # We can force an over-ride by specifying a config file on the
        # command line options:
        result = runner.invoke(cli.main, [
            '-b', 'has myTag',
            '--config', str(t2),
            '--tag', 'myTag',
        ])
        assert result.exit_code == 0

    # Just a general test; if both the --config and urls are specified
    # then the the urls trumps all
    result = runner.invoke(cli.main, [
        '-b', 'has myTag',
        '--config', str(t2),
        'good://localhost',
        '--tag', 'fail',
    ])
    # Tags are ignored, URL specified, so it trump config
    assert result.exit_code == 0

    # we just repeat the test as a proof that it only executes
    # the urls despite the fact the --config was specified
    result = runner.invoke(cli.main, [
        '-b', 'reads the url entry only',
        '--config', str(t2),
        'good://localhost',
        '--tag', 'fail',
    ])
    # Tags are ignored, URL specified, so it trump config
    assert result.exit_code == 0

    # once agian, but we call bad://
    result = runner.invoke(cli.main, [
        '-b', 'reads the url entry only',
        '--config', str(t2),
        'bad://localhost',
        '--tag', 'myTag',
    ])
    assert result.exit_code == 1

    # Test Escaping:
    result = runner.invoke(cli.main, [
        '-e',
        '-t', 'test\ntitle',
        '-b', 'test\nbody',
        'good://localhost',
    ])
    assert result.exit_code == 0

    # Test Escaping (without title)
    result = runner.invoke(cli.main, [
        '--interpret-escapes',
        '-b', 'test\nbody',
        'good://localhost',
    ])
    assert result.exit_code == 0

    # Test Emojis:
    result = runner.invoke(cli.main, [
        '-j',
        '-t', ':smile:',
        '-b', ':grin:',
        'good://localhost',
    ])
    assert result.exit_code == 0

    result = runner.invoke(cli.main, [
        '--interpret-emojis',
        '-t', ':smile:',
        '-b', ':grin:',
        'good://localhost',
    ])
    assert result.exit_code == 0


def test_apprise_cli_modules(tmpdir):
    """
    CLI: --plugin (-P)

    """

    runner = CliRunner()

    #
    # Loading of modules works correctly
    #
    notify_cmod_base = tmpdir.mkdir('cli_modules')
    notify_cmod = notify_cmod_base.join('hook.py')
    notify_cmod.write(cleandoc("""
    from apprise.decorators import notify

    @notify(on="climod")
    def mywrapper(body, title, notify_type, *args, **kwargs):
        pass
    """))

    result = runner.invoke(cli.main, [
        '--plugin-path', str(notify_cmod),
        '-t', 'title',
        '-b', 'body',
        'climod://',
    ])

    assert result.exit_code == 0

    # Test -P
    result = runner.invoke(cli.main, [
        '-P', str(notify_cmod),
        '-t', 'title',
        '-b', 'body',
        'climod://',
    ])

    assert result.exit_code == 0

    # Test double hooks
    notify_cmod2 = notify_cmod_base.join('hook2.py')
    notify_cmod2.write(cleandoc("""
    from apprise.decorators import notify

    @notify(on="climod2")
    def mywrapper(body, title, notify_type, *args, **kwargs):
        pass
    """))

    result = runner.invoke(cli.main, [
        '--plugin-path', str(notify_cmod),
        '--plugin-path', str(notify_cmod2),
        '-t', 'title',
        '-b', 'body',
        'climod://',
        'climod2://',
    ])

    assert result.exit_code == 0

    with environ(
            APPRISE_PLUGIN_PATH=str(notify_cmod) + ';' + str(notify_cmod2)):
        # Leverage our environment variables to specify the plugin path
        result = runner.invoke(cli.main, [
            '-b', 'body',
            'climod://',
            'climod2://',
        ])

        assert result.exit_code == 0


@pytest.mark.skipif(
    sys.platform == "win32", reason="Unreliable results to be determined")
def test_apprise_cli_persistent_storage(tmpdir):
    """
    CLI: test persistent storage

    """

    # This is a made up class that is just used to verify
    class NoURLIDNotification(NotifyBase):
        """
        A no URL ID
        """

        # Update URL identifier
        url_identifier = False

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

        def send(self, **kwargs):

            # Pretend everything is okay
            return True

        def url(self, *args, **kwargs):
            # Support URL
            return 'noper://'

        def parse_url(self, *args, **kwargs):
            # parse our url
            return {'schema': 'noper'}

    # This is a made up class that is just used to verify
    class TestNotification(NotifyBase):
        """
        A Testing Script
        """

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

        def send(self, **kwargs):

            # Test our persistent settings
            self.store.set('key', 'value')
            assert self.store.get('key') == 'value'

            # Pretend everything is okay
            return True

        def url(self, *args, **kwargs):
            # Support URL
            return 'test://'

        def parse_url(self, *args, **kwargs):
            # parse our url
            return {'schema': 'test'}

    # assign test:// to our  notification defined above
    N_MGR['test'] = TestNotification
    N_MGR['noper'] = NoURLIDNotification

    # Write a simple text based configuration file
    config = tmpdir.join("apprise.cfg")
    buf = cleandoc("""
    # Create a config file we can source easily
    test=test://
    noper=noper://

    # Define a second test URL that will
    two-urls=test://

    # Create another entry that has no tag associatd with it
    test://?entry=2
    """)
    config.write(buf)

    runner = CliRunner()

    # Generate notification that creates persistent data
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'list',
    ])
    # list our entries
    assert result.exit_code == 0

    # our persist storage has not been created yet
    _stdout = result.stdout.strip()
    assert re.match(
        r'^1\.\s+[a-z0-9]{8}\s+0\.00B\s+unused\s+-\s+test://\s*', _stdout,
        re.MULTILINE)

    # An invalid mode specified
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--storage-mode', 'invalid',
        '--config', str(config),
        '-g', 'test',
        '-t', 'title',
        '-b', 'body',
    ])
    # Bad mode specified
    assert result.exit_code == 2

    # Invalid uid lenth specified
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--storage-mode', 'flush',
        '--storage-uid-length', 1,
        '--config', str(config),
        '-g', 'test',
        '-t', 'title',
        '-b', 'body',
    ])
    # storage uid length to small
    assert result.exit_code == 2

    # No files written yet; just config file exists
    dir_content = os.listdir(str(tmpdir))
    assert len(dir_content) == 1
    assert 'apprise.cfg' in dir_content

    # Generate notification that creates persistent data
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--storage-mode', 'flush',
        '--config', str(config),
        '-t', 'title',
        '-b', 'body',
        '-g', 'test',
    ])
    # We parsed our data accordingly
    assert result.exit_code == 0

    dir_content = os.listdir(str(tmpdir))
    assert len(dir_content) == 2
    assert 'apprise.cfg' in dir_content
    assert 'ea482db7' in dir_content

    # Have a look at our storage listings
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'list',
    ])
    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    assert re.match(
        r'^1\.\s+[a-z0-9_-]{8}\s+81\.00B\s+active\s+-\s+test://$', _stdout,
        re.MULTILINE)

    # keyword list is not required
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
    ])
    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    assert re.match(
        r'^1\.\s+[a-z0-9_-]{8}\s+81\.00B\s+active\s+-\s+test://$', _stdout,
        re.MULTILINE)

    # search on something that won't match
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'list',
        'nomatch',
    ])
    # list our entries
    assert result.exit_code == 0

    assert not result.stdout.strip()

    # closest match search
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'list',
        # Closest match will hit a result
        'ea',
    ])
    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    assert re.match(
        r'^1\.\s+[a-z0-9_-]{8}\s+81\.00B\s+active\s+-\s+test://$', _stdout,
        re.MULTILINE)

    # list is the presumed option if no match
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        # Closest match will hit a result
        'ea',
    ])
    # list our entries successfully again..
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    assert re.match(
        r'^1\.\s+[a-z0-9_-]{8}\s+81\.00B\s+active\s+-\s+test://$', _stdout,
        re.MULTILINE)

    # Search based on tag
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'list',
        # We can match by tags too
        '-g', 'test',
    ])
    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    assert re.match(
        r'^1\.\s+[a-z0-9_-]{8}\s+81\.00B\s+active\s+-\s+test://$', _stdout,
        re.MULTILINE)

    # Prune call but prune-days set incorrectly
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--storage-prune-days', -1,
        'storage',
        'prune',
    ])
    # storage prune days is invalid
    assert result.exit_code == 2

    # Create a tmporary namespace
    tmpdir.mkdir('namespace')

    # Generates another listing
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
    ])

    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    assert re.match(
        r'^[0-9]\.\s+[a-z0-9_-]{8}\s+81\.00B\s+active\s+-\s+test://$', _stdout,
        re.MULTILINE)
    assert re.match(
        r'.*\s*[0-9]\.\s+namespace\s+0\.00B\s+stale.*', _stdout,
        (re.MULTILINE | re.DOTALL))

    # Generates another listing but utilize the tag
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        '--tag', 'test',
        'storage',
    ])

    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    assert re.match(
        r'^[0-9]\.\s+[a-z0-9_-]{8}\s+81\.00B\s+active\s+-\s+test://$', _stdout,
        re.MULTILINE)
    assert re.match(
        r'.*\s*[0-9]\.\s+namespace\s+0\.00B\s+stale.*', _stdout,
        (re.MULTILINE | re.DOTALL)) is None

    # Clear all of our accumulated disk space
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'clear',
    ])

    # successful
    assert result.exit_code == 0

    # Generate another listing
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
    ])

    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    # back to unused state and 0 bytes
    assert re.match(
        r'^[0-9]\.\s+[a-z0-9_-]{8}\s+0\.00B\s+unused\s+-\s+test://$', _stdout,
        re.MULTILINE)
    # namespace is gone now
    assert re.match(
        r'.*\s*[0-9]\.\s+namespace\s+0\.00B\s+stale.*', _stdout,
        (re.MULTILINE | re.DOTALL)) is None

    # Provide both tags and uid
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'ea',
        '-g', 'test',
    ])

    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    # back to unused state and 0 bytes
    assert re.match(
        r'^[0-9]\.\s+[a-z0-9_-]{8}\s+0\.00B\s+unused\s+-\s+test://$', _stdout,
        re.MULTILINE)

    # Generate notification that creates persistent data
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--storage-mode', 'flush',
        '--config', str(config),
        '-t', 'title',
        '-b', 'body',
        '-g', 'test',
    ])
    # We parsed our data accordingly
    assert result.exit_code == 0

    # Have a look at our storage listings
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'list',
    ])
    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    assert re.match(
        r'^1\.\s+[a-z0-9_-]{8}\s+81\.00B\s+active\s+-\s+test://$', _stdout,
        re.MULTILINE)

    # Prune call but prune-days set incorrectly
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        'storage',
        'prune',
    ])

    # Run our prune successfully
    assert result.exit_code == 0

    # Have a look at our storage listings (expected no change in output)
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'list',
    ])
    # list our entries
    assert result.exit_code == 0

    _stdout = result.stdout.strip()
    assert re.match(
        r'^1\.\s+[a-z0-9_-]{8}\s+81\.00B\s+active\s+-\s+test://$', _stdout,
        re.MULTILINE)

    # Prune call but prune-days set incorrectly
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        # zero simulates a full clean
        '--storage-prune-days', 0,
        'storage',
        'prune',
    ])

    # Run our prune successfully
    assert result.exit_code == 0

    # Have a look at our storage listings (expected no change in output)
    result = runner.invoke(cli.main, [
        '--storage-path', str(tmpdir),
        '--config', str(config),
        'storage',
        'list',
    ])
    # list our entries
    assert result.exit_code == 0

    # Note: An prune/expiry of zero gets everything except for MS Windows
    # during testing only.
    # Until this can be resolved, this is the section of the test that
    # caused us to disable it in MS Windows
    _stdout = result.stdout.strip()
    assert re.match(
        r'^1\.\s+[a-z0-9_-]{8}\s+0\.00B\s+unused\s+-\s+test://$', _stdout,
        re.MULTILINE)

    # New Temporary namespace
    new_persistent_base = tmpdir.mkdir('namespace')
    with environ(APPRISE_STORAGE_PATH=str(new_persistent_base)):
        # Reload our module
        reload(cli)

        # Nothing in our directory yet
        dir_content = os.listdir(str(new_persistent_base))
        assert len(dir_content) == 0

        # Generate notification that creates persistent data
        # storage path is pulled out of our environment variable
        result = runner.invoke(cli.main, [
            '--storage-mode', 'flush',
            '--config', str(config),
            '-t', 'title',
            '-b', 'body',
            '-g', 'test',
        ])
        # We parsed our data accordingly
        assert result.exit_code == 0

        # Now content exists
        dir_content = os.listdir(str(new_persistent_base))
        assert len(dir_content) == 1

    # Reload our module with our environment variable gone
    reload(cli)

    # Clear loaded modules
    N_MGR.unload_modules()


def test_apprise_cli_details(tmpdir):
    """
    CLI: --details (-l)

    """

    runner = CliRunner()

    #
    # Testing the printout of our details
    #   --details or -l
    #
    result = runner.invoke(cli.main, [
        '--details',
    ])
    assert result.exit_code == 0

    result = runner.invoke(cli.main, [
        '-l',
    ])
    assert result.exit_code == 0

    # Clear loaded modules
    N_MGR.unload_modules()

    # This is a made up class that is just used to verify
    class TestReq01Notification(NotifyBase):
        """
        This class is used to test various requirement configurations
        """

        # Set some requirements
        requirements = {
            'packages_required': [
                'cryptography <= 3.4',
                'ultrasync',
            ],
            'packages_recommended': 'django',
        }

        def url(self, **kwargs):
            # Support URL
            return ''

        def send(self, **kwargs):
            # Pretend everything is okay (so we don't break other tests)
            return True

    N_MGR['req01'] = TestReq01Notification

    # This is a made up class that is just used to verify
    class TestReq02Notification(NotifyBase):
        """
        This class is used to test various requirement configurations
        """

        # Just not enabled at all
        enabled = False

        # Set some requirements
        requirements = {
            # None and/or [] is implied, but jsut to show that the code won't
            # crash if explicitly set this way:
            'packages_required': None,

            'packages_recommended': [
                'cryptography <= 3.4',
            ]
        }

        def url(self, **kwargs):
            # Support URL
            return ''

        def send(self, **kwargs):
            # Pretend everything is okay (so we don't break other tests)
            return True

    N_MGR['req02'] = TestReq02Notification

    # This is a made up class that is just used to verify
    class TestReq03Notification(NotifyBase):
        """
        This class is used to test various requirement configurations
        """

        # Set some requirements (but additionally include a details over-ride)
        requirements = {
            # We can over-ride the default details assigned to our plugin if
            # specified
            'details': _('some specified requirement details'),

            # We can set a string value as well (it does not have to be a list)
            'packages_recommended': 'cryptography <= 3.4'
        }

        def url(self, **kwargs):
            # Support URL
            return ''

        def send(self, **kwargs):
            # Pretend everything is okay (so we don't break other tests)
            return True

    N_MGR['req03'] = TestReq03Notification

    # This is a made up class that is just used to verify
    class TestReq04Notification(NotifyBase):
        """
        This class is used to test a case where our requirements is fixed
        to a None
        """

        # This is the same as saying there are no requirements
        requirements = None

        def url(self, **kwargs):
            # Support URL
            return ''

        def send(self, **kwargs):
            # Pretend everything is okay (so we don't break other tests)
            return True

    N_MGR['req04'] = TestReq04Notification

    # This is a made up class that is just used to verify
    class TestReq05Notification(NotifyBase):
        """
        This class is used to test a case where only packages_recommended
        is identified
        """

        requirements = {
            'packages_recommended': 'cryptography <= 3.4'
        }

        def url(self, **kwargs):
            # Support URL
            return ''

        def send(self, **kwargs):
            # Pretend everything is okay (so we don't break other tests)
            return True

    N_MGR['req05'] = TestReq05Notification

    class TestDisabled01Notification(NotifyBase):
        """
        This class is used to test a pre-disabled state
        """

        # Just flat out disable our service
        enabled = False

        # we'll use this as a key to make our service easier to find
        # in the next part of the testing
        service_name = 'na01'

        def url(self, **kwargs):
            # Support URL
            return ''

        def notify(self, **kwargs):
            # Pretend everything is okay (so we don't break other tests)
            return True

    N_MGR['na01'] = TestDisabled01Notification

    class TestDisabled02Notification(NotifyBase):
        """
        This class is used to test a post-disabled state
        """

        # we'll use this as a key to make our service easier to find
        # in the next part of the testing
        service_name = 'na02'

        def __init__(self, *args, **kwargs):
            super().__init__(**kwargs)

            # enable state changes **AFTER** we initialize
            self.enabled = False

        def url(self, **kwargs):
            # Support URL
            return ''

        def notify(self, **kwargs):
            # Pretend everything is okay (so we don't break other tests)
            return True

    N_MGR['na02'] = TestDisabled02Notification

    # We'll add a good notification to our list
    class TesEnabled01Notification(NotifyBase):
        """
        This class is just a simple enabled one
        """

        # we'll use this as a key to make our service easier to find
        # in the next part of the testing
        service_name = 'good'

        def url(self, **kwargs):
            # Support URL
            return ''

        def send(self, **kwargs):
            # Pretend everything is okay (so we don't break other tests)
            return True

    N_MGR['good'] = TesEnabled01Notification

    # Verify that we can pass through all of our different details
    result = runner.invoke(cli.main, [
        '--details',
    ])
    assert result.exit_code == 0

    result = runner.invoke(cli.main, [
        '-l',
    ])
    assert result.exit_code == 0

    # Clear loaded modules
    N_MGR.unload_modules()


def test_apprise_cli_print_help():
    """
    CLI: --help (-h)

    """
    runner = CliRunner()

    # Clear our working variables so they don't obstruct the next test
    # This simulates an actual call from the CLI.  Unfortunately through
    # testing were occupying the same memory space so our singleton's
    # have already been populated
    N_MGR._paths_previously_scanned.clear()
    N_MGR._custom_module_map.clear()

    # Print help and exit
    result = runner.invoke(cli.main, ['--help'])
    assert result.exit_code == 0

    result = runner.invoke(cli.main, ['-h'])
    assert result.exit_code == 0


@mock.patch('requests.post')
def test_apprise_cli_plugin_loading(mock_post, tmpdir):
    """
    CLI: --plugin-path (-P)

    """
    # Prepare Mock
    mock_post.return_value = requests.Request()
    mock_post.return_value.status_code = requests.codes.ok

    runner = CliRunner()

    # Clear our working variables so they don't obstruct the next test
    # This simulates an actual call from the CLI.  Unfortunately through
    # testing were occupying the same memory space so our singleton's
    # have already been populated
    N_MGR._paths_previously_scanned.clear()
    N_MGR._custom_module_map.clear()

    # Test a path that has no files to load in it
    result = runner.invoke(cli.main, [
        '--plugin-path', join(str(tmpdir), 'invalid_path'),
        '-b', 'test\nbody',
        'json://localhost',
    ])
    # The path is silently loaded but fails... it's okay because the
    # notification we're choosing to notify does exist
    assert result.exit_code == 0

    # Directories that don't exist passed in by the CLI aren't even scanned
    assert len(N_MGR._paths_previously_scanned) == 0
    assert len(N_MGR._custom_module_map) == 0

    # Test our current existing path that has no entries in it
    result = runner.invoke(cli.main, [
        '--plugin-path', str(tmpdir.mkdir('empty')),
        '-b', 'test\nbody',
        'json://localhost',
    ])
    # The path is silently loaded but fails... it's okay because the
    # notification we're choosing to notify does exist
    assert result.exit_code == 0
    assert len(N_MGR._paths_previously_scanned) == 1
    assert join(str(tmpdir), 'empty') in \
        N_MGR._paths_previously_scanned

    # However there was nothing to load
    assert len(N_MGR._custom_module_map) == 0

    # Clear our working variables so they don't obstruct the next test
    # This simulates an actual call from the CLI.  Unfortunately through
    # testing were occupying the same memory space so our singleton's
    # have already been populated
    N_MGR._paths_previously_scanned.clear()
    N_MGR._custom_module_map.clear()

    # Prepare ourselves a file to work with
    notify_hook_a_base = tmpdir.mkdir('random')
    notify_hook_a = notify_hook_a_base.join('myhook01.py')
    notify_hook_a.write(cleandoc("""
    raise ImportError
    """))

    result = runner.invoke(cli.main, [
        '--plugin-path', str(notify_hook_a),
        '-b', 'test\nbody',
        # A custom hook:
        'clihook://',
    ])
    # It doesn't exist so it will fail
    # meanwhile we would have failed to load the myhook path
    assert result.exit_code == 1

    # The path is silently loaded but fails... it's okay because the
    # notification we're choosing to notify does exist
    assert len(N_MGR._paths_previously_scanned) == 1
    assert str(notify_hook_a) in N_MGR._paths_previously_scanned
    # However there was nothing to load
    assert len(N_MGR._custom_module_map) == 0

    # Prepare ourselves a file to work with
    notify_hook_aa = notify_hook_a_base.join('myhook02.py')
    notify_hook_aa.write(cleandoc("""
    garbage entry
    """))

    N_MGR.plugins()
    result = runner.invoke(cli.main, [
        '--plugin-path', str(notify_hook_aa),
        '-b', 'test\nbody',
        # A custom hook:
        'clihook://custom',
    ])
    # It doesn't exist so it will fail
    # meanwhile we would have failed to load the myhook path
    assert result.exit_code == 1

    # The path is silently loaded but fails...
    # as a result the path stacks with the last
    assert len(N_MGR._paths_previously_scanned) == 2
    assert str(notify_hook_a) in \
        N_MGR._paths_previously_scanned
    assert str(notify_hook_aa) in \
        N_MGR._paths_previously_scanned
    # However there was nothing to load
    assert len(N_MGR._custom_module_map) == 0

    # Clear our working variables so they don't obstruct the next test
    # This simulates an actual call from the CLI.  Unfortunately through
    # testing were occupying the same memory space so our singleton's
    # have already been populated
    N_MGR._paths_previously_scanned.clear()
    N_MGR._custom_module_map.clear()

    # Prepare ourselves a file to work with
    notify_hook_b = tmpdir.mkdir('goodmodule').join('__init__.py')
    notify_hook_b.write(cleandoc("""
    from apprise.decorators import notify

    # We want to trigger on anyone who configures a call to clihook://
    @notify(on="clihook")
    def mywrapper(body, title, notify_type, *args, **kwargs):
        # A simple test - print to screen
        print("{}: {} - {}".format(notify_type, title, body))

        # No return (so a return of None) get's translated to True

    # Define another in the same file
    @notify(on="clihookA")
    def mywrapper(body, title, notify_type, *args, **kwargs):
        # A simple test - print to screen
        print("!! {}: {} - {}".format(notify_type, title, body))

        # No return (so a return of None) get's translated to True
    """))

    result = runner.invoke(cli.main, [
        '--plugin-path', str(tmpdir),
        '-b', 'test body',
        # A custom hook:
        'clihook://still/valid',
    ])

    # We can detect the goodmodule (which has an __init__.py in it)
    # so we'll load okay
    assert result.exit_code == 0

    # Let's see how things got loaded:
    assert len(N_MGR._paths_previously_scanned) == 2
    assert str(tmpdir) in N_MGR._paths_previously_scanned
    # absolute path to detected module is also added
    assert join(str(tmpdir), 'goodmodule', '__init__.py') \
        in N_MGR._paths_previously_scanned

    # We also loaded our clihook properly
    assert len(N_MGR._custom_module_map) == 1

    # We can find our new hook loaded in our schema map now...
    assert 'clihook' in N_MGR

    # Capture our key for reference
    key = [k for k in N_MGR._custom_module_map.keys()][0]

    # We loaded 2 entries from the same file
    assert len(N_MGR._custom_module_map[key]['notify']) == 2
    assert 'clihook' in N_MGR._custom_module_map[key]['notify']
    # Converted to lower case
    assert 'clihooka' in N_MGR._custom_module_map[key]['notify']

    # Our function name
    assert N_MGR._custom_module_map[key]['notify']['clihook']['fn_name'] \
        == 'mywrapper'
    # What we parsed from the `on` keyword in the @notify decorator
    assert N_MGR._custom_module_map[key]['notify']['clihook']['url'] \
        == 'clihook://'
    # our default name Assignment.  This can be-overridden on the @notify
    # decorator by just adding a name= to the parameter list
    assert N_MGR['clihook'].service_name == 'Custom - clihook'

    # Our Base Notification object when initialized:
    assert len(
        N_MGR._module_map[N_MGR._custom_module_map[key]['name']]['plugin']) \
        == 2
    for plugin in \
            N_MGR._module_map[N_MGR._custom_module_map[key]['name']]['plugin']:
        assert isinstance(plugin(), NotifyBase)

    # Clear our working variables so they don't obstruct the next test
    # This simulates an actual call from the CLI.  Unfortunately through
    # testing were occupying the same memory space so our singleton's
    # have already been populated
    N_MGR._paths_previously_scanned.clear()
    N_MGR._custom_module_map.clear()
    del N_MGR['clihook']

    result = runner.invoke(cli.main, [
        '--plugin-path', str(notify_hook_b),
        '-b', 'test body',
        # A custom hook:
        'clihook://',
    ])

    # Absolute path to __init__.py is okay
    assert result.exit_code == 0

    # we can verify that it prepares our message
    assert result.stdout.strip() == 'info:  - test body'

    # Clear our working variables so they don't obstruct the next test
    # This simulates an actual call from the CLI.  Unfortunately through
    # testing were occupying the same memory space so our singleton's
    # have already been populated
    N_MGR._paths_previously_scanned.clear()
    N_MGR._custom_module_map.clear()
    del N_MGR['clihook']

    result = runner.invoke(cli.main, [
        '--plugin-path', dirname(str(notify_hook_b)),
        '-b', 'test body',
        # A custom hook:
        'clihook://',
    ])

    # Now we succeed to load our module when pointed to it only because
    # an __init__.py is found on the inside of it
    assert result.exit_code == 0

    # we can verify that it prepares our message
    assert result.stdout.strip() == 'info:  - test body'

    # Test double paths that are the same; this ensures we only
    # load the plugin once
    result = runner.invoke(cli.main, [
        '--plugin-path', dirname(str(notify_hook_b)),
        '--plugin-path', str(notify_hook_b),
        '--details',
    ])

    # Now we succeed to load our module when pointed to it only because
    # an __init__.py is found on the inside of it
    assert result.exit_code == 0

    # Clear our working variables so they don't obstruct the next test
    # This simulates an actual call from the CLI.  Unfortunately through
    # testing were occupying the same memory space so our singleton's
    # have already been populated
    N_MGR._paths_previously_scanned.clear()
    N_MGR._custom_module_map.clear()
    del N_MGR['clihook']

    # Prepare ourselves a file to work with
    notify_hook_b = tmpdir.mkdir('complex').join('complex.py')
    notify_hook_b.write(cleandoc("""
    from apprise.decorators import notify

    # We can't over-ride an element that already exists
    # in this case json://
    @notify(on="json")
    def mywrapper_01(body, title, notify_type, *args, **kwargs):
        # Return True (same as None)
        return True

    @notify(on="willfail", name="always failing...")
    def mywrapper_02(body, title, notify_type, *args, **kwargs):
        # Simply fail
        return False

    @notify(on="clihook1", name="the original clihook entry")
    def mywrapper_03(body, title, notify_type, *args, **kwargs):
        # Return True
        return True

    # This is a duplicate o the entry above, so it can not be
    # loaded...
    @notify(on="clihook1", name="a duplicate of the clihook entry")
    def mywrapper_04(body, title, notify_type, *args, **kwargs):
        # Return True
        return True

    # This is where things get realy cool... we can not only
    # define the schema we want to over-ride, but we can define
    # some default values to pass into our wrapper function to
    # act as a base before whatever was actually passed in is
    # applied ontop.... think of it like templating information
    @notify(on="clihook2://localhost")
    def mywrapper_05(body, title, notify_type, *args, **kwargs):
        # Return True
        return True


    # This can't load because of the defined schema/on definition
    @notify(on="", name="an invalid schema was specified")
    def mywrapper_06(body, title, notify_type, *args, **kwargs):
        return True
    """))

    result = runner.invoke(cli.main, [
        '--plugin-path', join(str(tmpdir), 'complex'),
        '-b', 'test body',
        # A custom hook that does not exist
        'clihook://',
    ])

    # Since clihook:// isn't in our complex listing, this will fail
    assert result.exit_code == 1

    # Let's see how things got loaded
    assert len(N_MGR._paths_previously_scanned) == 2
    # Our path we specified on the CLI...
    assert join(str(tmpdir), 'complex') in N_MGR._paths_previously_scanned

    # absolute path to detected module is also added
    assert join(str(tmpdir), 'complex', 'complex.py') \
        in N_MGR._paths_previously_scanned

    # We loaded our one module successfuly
    assert len(N_MGR._custom_module_map) == 1

    # We can find our new hook loaded in our SCHEMA_MAP now...
    assert 'willfail' in N_MGR
    assert 'clihook1' in N_MGR
    assert 'clihook2' in N_MGR

    # Capture our key for reference
    key = [k for k in N_MGR._custom_module_map.keys()][0]

    assert len(N_MGR._custom_module_map[key]['notify']) == 3
    assert 'willfail' in N_MGR._custom_module_map[key]['notify']
    assert 'clihook1' in N_MGR._custom_module_map[key]['notify']
    # We only load 1 instance of the clihook2, the second will fail
    assert 'clihook2' in N_MGR._custom_module_map[key]['notify']
    # We can never load previously created notifications
    assert 'json' not in N_MGR._custom_module_map[key]['notify']

    result = runner.invoke(cli.main, [
        '--plugin-path', join(str(tmpdir), 'complex'),
        '-b', 'test body',
        # A custom notification set up for failure
        'willfail://',
    ])
    # Note that the failure of the decorator carries all the way back
    # to the CLI
    assert result.exit_code == 1

    result = runner.invoke(cli.main, [
        '--plugin-path', join(str(tmpdir), 'complex'),
        '-b', 'test body',
        # our clihook that returns true
        'clihook1://',
        # our other loaded clihook
        'clihook2://',
    ])
    # Note that the failure of the decorator carries all the way back
    # to the CLI
    assert result.exit_code == 0

    result = runner.invoke(cli.main, [
        '--plugin-path', join(str(tmpdir), 'complex'),
        # Print our custom details to the screen
        '--details',
    ])
    assert 'willfail' in result.stdout
    assert 'always failing...' in result.stdout

    assert 'clihook1' in result.stdout
    assert 'the original clihook entry' in result.stdout
    assert 'a duplicate of the clihook entry' not in result.stdout

    assert 'clihook2' in result.stdout
    assert 'Custom - clihook2' in result.stdout

    # Note that the failure of the decorator carries all the way back
    # to the CLI
    assert result.exit_code == 0


@mock.patch('platform.system')
def test_apprise_cli_windows_env(mock_system):
    """
    CLI: Windows Environment

    """
    # Force a windows environment
    mock_system.return_value = 'Windows'

    # Reload our module
    reload(cli)