Debian Codegraph @

tests/test_apprise_utils.py

raw symbols SCIP
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from datetime import tzinfo
29 from inspect import cleandoc
30
31 # Disable logging for a cleaner testing output
32 import logging
33 import os
34 import re
35 import sys
36 import time
37 from unittest import mock
38 from urllib.parse import unquote
39
40 from apprise import NotificationManager, utils
41 from apprise.tag import AppriseTag
42
43 logging.disable(logging.CRITICAL)
44
45 # Ensure we don't create .pyc files for these tests
46 sys.dont_write_bytecode = True
47
48 # Grant access to our Notification Manager Singleton
49 N_MGR = NotificationManager()
50
51
52 def test_parse_qsd():
53 "utils: parse_qsd() testing"
54
55 result = utils.parse.parse_qsd("a=1&b=&c&d=abcd")
56 assert isinstance(result, dict)
57 assert len(result) == 4
58 assert "qsd" in result
59 assert "qsd+" in result
60 assert "qsd-" in result
61 assert "qsd:" in result
62
63 assert len(result["qsd"]) == 4
64 assert "a" in result["qsd"]
65 assert "b" in result["qsd"]
66 assert "c" in result["qsd"]
67 assert "d" in result["qsd"]
68
69 assert len(result["qsd-"]) == 0
70 assert len(result["qsd+"]) == 0
71 assert len(result["qsd:"]) == 0
72
73
74 def test_parse_url_general():
75 "utils: parse_url() testing"
76
77 result = utils.parse.parse_url("http://hostname")
78 assert result["schema"] == "http"
79 assert result["host"] == "hostname"
80 assert result["port"] is None
81 assert result["user"] is None
82 assert result["password"] is None
83 assert result["fullpath"] is None
84 assert result["path"] is None
85 assert result["query"] is None
86 assert result["url"] == "http://hostname"
87 assert result["qsd"] == {}
88 assert result["qsd-"] == {}
89 assert result["qsd+"] == {}
90 assert result["qsd:"] == {}
91
92 # GitHub Ticket 1234 - Unparseable Hostname
93 result = utils.parse.parse_url("http://5t4m59hl-34343.euw.devtunnels.ms")
94 assert result["schema"] == "http"
95 assert result["host"] == "5t4m59hl-34343.euw.devtunnels.ms"
96 assert result["port"] is None
97 assert result["user"] is None
98 assert result["password"] is None
99 assert result["fullpath"] is None
100 assert result["path"] is None
101 assert result["query"] is None
102 assert result["url"] == "http://5t4m59hl-34343.euw.devtunnels.ms"
103 assert result["qsd"] == {}
104 assert result["qsd-"] == {}
105 assert result["qsd+"] == {}
106 assert result["qsd:"] == {}
107
108 result = utils.parse.parse_url("http://hostname/")
109 assert result["schema"] == "http"
110 assert result["host"] == "hostname"
111 assert result["port"] is None
112 assert result["user"] is None
113 assert result["password"] is None
114 assert result["fullpath"] == "/"
115 assert result["path"] == "/"
116 assert result["query"] is None
117 assert result["url"] == "http://hostname/"
118 assert result["qsd"] == {}
119 assert result["qsd-"] == {}
120 assert result["qsd+"] == {}
121 assert result["qsd:"] == {}
122
123 # colon after hostname without port number is no good
124 assert utils.parse.parse_url("http://hostname:") is None
125
126 # An invalid port
127 result = utils.parse.parse_url(
128 "http://hostname:invalid", verify_host=False, strict_port=True
129 )
130 assert result["schema"] == "http"
131 assert result["host"] == "hostname"
132 assert result["port"] == "invalid"
133 assert result["user"] is None
134 assert result["password"] is None
135 assert result["fullpath"] is None
136 assert result["path"] is None
137 assert result["query"] is None
138 assert result["url"] == "http://hostname:invalid"
139 assert result["qsd"] == {}
140 assert result["qsd-"] == {}
141 assert result["qsd+"] == {}
142 assert result["qsd:"] == {}
143
144 # However if we don't verify the host, it is okay
145 result = utils.parse.parse_url("http://hostname:", verify_host=False)
146 assert result["schema"] == "http"
147 assert result["host"] == "hostname:"
148 assert result["port"] is None
149 assert result["user"] is None
150 assert result["password"] is None
151 assert result["fullpath"] is None
152 assert result["path"] is None
153 assert result["query"] is None
154 assert result["url"] == "http://hostname:"
155 assert result["qsd"] == {}
156 assert result["qsd-"] == {}
157 assert result["qsd+"] == {}
158 assert result["qsd:"] == {}
159
160 # A port of Zero is not valid with strict port checking
161 assert utils.parse.parse_url("http://hostname:0", strict_port=True) is None
162
163 # Without strict port checking however, it is okay
164 result = utils.parse.parse_url("http://hostname:0", strict_port=False)
165 assert result["schema"] == "http"
166 assert result["host"] == "hostname"
167 assert result["port"] == 0
168 assert result["user"] is None
169 assert result["password"] is None
170 assert result["fullpath"] is None
171 assert result["path"] is None
172 assert result["query"] is None
173 assert result["url"] == "http://hostname:0"
174 assert result["qsd"] == {}
175 assert result["qsd-"] == {}
176 assert result["qsd+"] == {}
177 assert result["qsd:"] == {}
178
179 # A negative port is not valid
180 assert (
181 utils.parse.parse_url("http://hostname:-92", strict_port=True) is None
182 )
183 result = utils.parse.parse_url(
184 "http://hostname:-92", verify_host=False, strict_port=True
185 )
186 assert result["schema"] == "http"
187 assert result["host"] == "hostname"
188 assert result["port"] == -92
189 assert result["user"] is None
190 assert result["password"] is None
191 assert result["fullpath"] is None
192 assert result["path"] is None
193 assert result["query"] is None
194 assert result["url"] == "http://hostname:-92"
195 assert result["qsd"] == {}
196 assert result["qsd-"] == {}
197 assert result["qsd+"] == {}
198 assert result["qsd:"] == {}
199
200 # A port that is too large is not valid
201 assert (
202 utils.parse.parse_url("http://hostname:65536", strict_port=True)
203 is None
204 )
205
206 # This is an accetable port (the maximum)
207 result = utils.parse.parse_url("http://hostname:65535", strict_port=True)
208 assert result["schema"] == "http"
209 assert result["host"] == "hostname"
210 assert result["port"] == 65535
211 assert result["user"] is None
212 assert result["password"] is None
213 assert result["fullpath"] is None
214 assert result["path"] is None
215 assert result["query"] is None
216 assert result["url"] == "http://hostname:65535"
217 assert result["qsd"] == {}
218 assert result["qsd-"] == {}
219 assert result["qsd+"] == {}
220 assert result["qsd:"] == {}
221
222 # This is an accetable port (the maximum)
223 result = utils.parse.parse_url("http://hostname:1", strict_port=True)
224 assert result["schema"] == "http"
225 assert result["host"] == "hostname"
226 assert result["port"] == 1
227 assert result["user"] is None
228 assert result["password"] is None
229 assert result["fullpath"] is None
230 assert result["path"] is None
231 assert result["query"] is None
232 assert result["url"] == "http://hostname:1"
233 assert result["qsd"] == {}
234 assert result["qsd-"] == {}
235 assert result["qsd+"] == {}
236 assert result["qsd:"] == {}
237
238 # A port that was identfied as a string is invalid
239 assert (
240 utils.parse.parse_url("http://hostname:invalid", strict_port=True)
241 is None
242 )
243 result = utils.parse.parse_url(
244 "http://hostname:invalid", verify_host=False, strict_port=True
245 )
246 assert result["schema"] == "http"
247 assert result["host"] == "hostname"
248 assert result["port"] == "invalid"
249 assert result["user"] is None
250 assert result["password"] is None
251 assert result["fullpath"] is None
252 assert result["path"] is None
253 assert result["query"] is None
254 assert result["url"] == "http://hostname:invalid"
255 assert result["qsd"] == {}
256 assert result["qsd-"] == {}
257 assert result["qsd+"] == {}
258 assert result["qsd:"] == {}
259
260 result = utils.parse.parse_url(
261 "http://hostname:invalid", verify_host=False, strict_port=False
262 )
263 assert result["schema"] == "http"
264 assert result["host"] == "hostname:invalid"
265 assert result["port"] is None
266 assert result["user"] is None
267 assert result["password"] is None
268 assert result["fullpath"] is None
269 assert result["path"] is None
270 assert result["query"] is None
271 assert result["url"] == "http://hostname:invalid"
272 assert result["qsd"] == {}
273 assert result["qsd-"] == {}
274 assert result["qsd+"] == {}
275 assert result["qsd:"] == {}
276
277 result = utils.parse.parse_url(
278 "http://hostname:invalid?key=value&-minuskey=mvalue",
279 verify_host=False,
280 strict_port=False,
281 )
282 assert result["schema"] == "http"
283 assert result["host"] == "hostname:invalid"
284 assert result["port"] is None
285 assert result["user"] is None
286 assert result["password"] is None
287 assert result["fullpath"] is None
288 assert result["path"] is None
289 assert result["query"] is None
290 assert result["url"] == "http://hostname:invalid"
291 assert unquote(result["qsd"]["-minuskey"]) == "mvalue"
292 assert unquote(result["qsd"]["key"]) == "value"
293 assert unquote(result["qsd-"]["minuskey"]) == "mvalue"
294 assert result["qsd+"] == {}
295 assert result["qsd:"] == {}
296
297 # Handling of floats
298 assert (
299 utils.parse.parse_url("http://hostname:4.2", strict_port=True) is None
300 )
301 result = utils.parse.parse_url(
302 "http://hostname:4.2", verify_host=False, strict_port=True
303 )
304 assert result["schema"] == "http"
305 assert result["host"] == "hostname"
306 assert result["port"] == "4.2"
307 assert result["user"] is None
308 assert result["password"] is None
309 assert result["fullpath"] is None
310 assert result["path"] is None
311 assert result["query"] is None
312 assert result["url"] == "http://hostname:4.2"
313 assert result["qsd"] == {}
314 assert result["qsd-"] == {}
315 assert result["qsd+"] == {}
316 assert result["qsd:"] == {}
317
318 # A Port of zero is not acceptable for a regular hostname
319 assert utils.parse.parse_url("http://hostname:0", strict_port=True) is None
320
321 # No host verification (zero is an acceptable port when this is the case
322 result = utils.parse.parse_url("http://hostname:0", verify_host=False)
323 assert result["schema"] == "http"
324 assert result["host"] == "hostname"
325 assert result["port"] == 0
326 assert result["user"] is None
327 assert result["password"] is None
328 assert result["fullpath"] is None
329 assert result["path"] is None
330 assert result["query"] is None
331 assert result["url"] == "http://hostname:0"
332 assert result["qsd"] == {}
333 assert result["qsd-"] == {}
334 assert result["qsd+"] == {}
335 assert result["qsd:"] == {}
336
337 result = utils.parse.parse_url(
338 "http://[2001:db8:002a:3256:adfe:05c0:0003:0006]:8080",
339 verify_host=False,
340 )
341 assert result["schema"] == "http"
342 assert result["host"] == "[2001:db8:002a:3256:adfe:05c0:0003:0006]"
343 assert result["port"] == 8080
344 assert result["user"] is None
345 assert result["password"] is None
346 assert result["fullpath"] is None
347 assert result["path"] is None
348 assert result["query"] is None
349 assert (
350 result["url"] == "http://[2001:db8:002a:3256:adfe:05c0:0003:0006]:8080"
351 )
352 assert result["qsd"] == {}
353 assert result["qsd-"] == {}
354 assert result["qsd+"] == {}
355 assert result["qsd:"] == {}
356
357 result = utils.parse.parse_url(
358 "http://hostname:0", verify_host=False, strict_port=True
359 )
360 assert result["schema"] == "http"
361 assert result["host"] == "hostname"
362 assert result["port"] == 0
363 assert result["user"] is None
364 assert result["password"] is None
365 assert result["fullpath"] is None
366 assert result["path"] is None
367 assert result["query"] is None
368 assert result["url"] == "http://hostname:0"
369 assert result["qsd"] == {}
370 assert result["qsd-"] == {}
371 assert result["qsd+"] == {}
372 assert result["qsd:"] == {}
373
374 result = utils.parse.parse_url("http://hostname/?-KeY=Value")
375 assert result["schema"] == "http"
376 assert result["host"] == "hostname"
377 assert result["port"] is None
378 assert result["user"] is None
379 assert result["password"] is None
380 assert result["fullpath"] == "/"
381 assert result["path"] == "/"
382 assert result["query"] is None
383 assert result["url"] == "http://hostname/"
384 assert "-key" in result["qsd"]
385 assert unquote(result["qsd"]["-key"]) == "Value"
386 assert "KeY" in result["qsd-"]
387 assert unquote(result["qsd-"]["KeY"]) == "Value"
388 assert result["qsd+"] == {}
389 assert result["qsd:"] == {}
390
391 result = utils.parse.parse_url("http://hostname/?+KeY=Value")
392 assert result["schema"] == "http"
393 assert result["host"] == "hostname"
394 assert result["port"] is None
395 assert result["user"] is None
396 assert result["password"] is None
397 assert result["fullpath"] == "/"
398 assert result["path"] == "/"
399 assert result["query"] is None
400 assert result["url"] == "http://hostname/"
401 assert "+key" in result["qsd"]
402 assert "KeY" in result["qsd+"]
403 assert result["qsd+"]["KeY"] == "Value"
404 assert result["qsd-"] == {}
405 assert result["qsd:"] == {}
406
407 result = utils.parse.parse_url("http://hostname/?:kEy=vALUE")
408 assert result["schema"] == "http"
409 assert result["host"] == "hostname"
410 assert result["port"] is None
411 assert result["user"] is None
412 assert result["password"] is None
413 assert result["fullpath"] == "/"
414 assert result["path"] == "/"
415 assert result["query"] is None
416 assert result["url"] == "http://hostname/"
417 assert ":key" in result["qsd"]
418 assert "kEy" in result["qsd:"]
419 assert result["qsd:"]["kEy"] == "vALUE"
420 assert result["qsd+"] == {}
421 assert result["qsd-"] == {}
422
423 result = utils.parse.parse_url(
424 "http://hostname/?+KeY=ValueA&-kEy=ValueB&KEY=Value%20+C&:colon=y"
425 )
426 assert result["schema"] == "http"
427 assert result["host"] == "hostname"
428 assert result["port"] is None
429 assert result["user"] is None
430 assert result["password"] is None
431 assert result["fullpath"] == "/"
432 assert result["path"] == "/"
433 assert result["query"] is None
434 assert result["url"] == "http://hostname/"
435 assert "+key" in result["qsd"]
436 assert "-key" in result["qsd"]
437 assert ":colon" in result["qsd"]
438 assert result["qsd:"]["colon"] == "y"
439 assert "key" in result["qsd"]
440 assert "KeY" in result["qsd+"]
441 assert result["qsd+"]["KeY"] == "ValueA"
442 assert "kEy" in result["qsd-"]
443 assert result["qsd-"]["kEy"] == "ValueB"
444 assert result["qsd"]["key"] == "Value +C"
445 assert result["qsd"]["+key"] == result["qsd+"]["KeY"]
446 assert result["qsd"]["-key"] == result["qsd-"]["kEy"]
447
448 result = utils.parse.parse_url(
449 "http://hostname/?+KeY=ValueA&-kEy=ValueB&KEY=Value%20+C&:colon=y",
450 plus_to_space=True,
451 )
452 assert result["schema"] == "http"
453 assert result["host"] == "hostname"
454 assert result["port"] is None
455 assert result["user"] is None
456 assert result["password"] is None
457 assert result["fullpath"] == "/"
458 assert result["path"] == "/"
459 assert result["query"] is None
460 assert result["url"] == "http://hostname/"
461 assert "+key" in result["qsd"]
462 assert "-key" in result["qsd"]
463 assert ":colon" in result["qsd"]
464 assert result["qsd:"]["colon"] == "y"
465 assert "key" in result["qsd"]
466 assert "KeY" in result["qsd+"]
467 assert result["qsd+"]["KeY"] == "ValueA"
468 assert "kEy" in result["qsd-"]
469 assert result["qsd-"]["kEy"] == "ValueB"
470 assert result["qsd"]["key"] == "Value C"
471 assert result["qsd"]["+key"] == result["qsd+"]["KeY"]
472 assert result["qsd"]["-key"] == result["qsd-"]["kEy"]
473
474 result = utils.parse.parse_url("http://hostname////")
475 assert result["schema"] == "http"
476 assert result["host"] == "hostname"
477 assert result["port"] is None
478 assert result["user"] is None
479 assert result["password"] is None
480 assert result["fullpath"] == "/"
481 assert result["path"] == "/"
482 assert result["query"] is None
483 assert result["url"] == "http://hostname/"
484 assert result["qsd"] == {}
485 assert result["qsd-"] == {}
486 assert result["qsd+"] == {}
487 assert result["qsd:"] == {}
488
489 result = utils.parse.parse_url("http://hostname:40////")
490 assert result["schema"] == "http"
491 assert result["host"] == "hostname"
492 assert result["port"] == 40
493 assert result["user"] is None
494 assert result["password"] is None
495 assert result["fullpath"] == "/"
496 assert result["path"] == "/"
497 assert result["query"] is None
498 assert result["url"] == "http://hostname:40/"
499 assert result["qsd"] == {}
500 assert result["qsd-"] == {}
501 assert result["qsd+"] == {}
502 assert result["qsd:"] == {}
503
504 result = utils.parse.parse_url("HTTP://HoStNaMe:40/test.php")
505 assert result["schema"] == "http"
506 assert result["host"] == "HoStNaMe"
507 assert result["port"] == 40
508 assert result["user"] is None
509 assert result["password"] is None
510 assert result["fullpath"] == "/test.php"
511 assert result["path"] == "/"
512 assert result["query"] == "test.php"
513 assert result["url"] == "http://HoStNaMe:40/test.php"
514 assert result["qsd"] == {}
515 assert result["qsd-"] == {}
516 assert result["qsd+"] == {}
517 assert result["qsd:"] == {}
518
519 result = utils.parse.parse_url("HTTPS://user@hostname/test.py")
520 assert result["schema"] == "https"
521 assert result["host"] == "hostname"
522 assert result["port"] is None
523 assert result["user"] == "user"
524 assert result["password"] is None
525 assert result["fullpath"] == "/test.py"
526 assert result["path"] == "/"
527 assert result["query"] == "test.py"
528 assert result["url"] == "https://user@hostname/test.py"
529 assert result["qsd"] == {}
530 assert result["qsd-"] == {}
531 assert result["qsd+"] == {}
532 assert result["qsd:"] == {}
533
534 result = utils.parse.parse_url(" HTTPS://///user@@@hostname///test.py ")
535 assert result["schema"] == "https"
536 assert result["host"] == "hostname"
537 assert result["port"] is None
538 assert result["user"] == "user"
539 assert result["password"] is None
540 assert result["fullpath"] == "/test.py"
541 assert result["path"] == "/"
542 assert result["query"] == "test.py"
543 assert result["url"] == "https://user@hostname/test.py"
544 assert result["qsd"] == {}
545 assert result["qsd-"] == {}
546 assert result["qsd+"] == {}
547 assert result["qsd:"] == {}
548
549 result = utils.parse.parse_url(
550 "HTTPS://user:password@otherHost/full///path/name/",
551 )
552 assert result["schema"] == "https"
553 assert result["host"] == "otherHost"
554 assert result["port"] is None
555 assert result["user"] == "user"
556 assert result["password"] == "password"
557 assert result["fullpath"] == "/full/path/name/"
558 assert result["path"] == "/full/path/name/"
559 assert result["query"] is None
560 assert result["url"] == "https://user:password@otherHost/full/path/name/"
561 assert result["qsd"] == {}
562 assert result["qsd-"] == {}
563 assert result["qsd+"] == {}
564 assert result["qsd:"] == {}
565
566 result = utils.parse.parse_url(
567 "HTTPS://hostname/a/path/ending/with/slash/?key=value",
568 )
569 assert result["schema"] == "https"
570 assert result["host"] == "hostname"
571 assert result["port"] is None
572 assert result["user"] is None
573 assert result["password"] is None
574 assert result["fullpath"] == "/a/path/ending/with/slash/"
575 assert result["path"] == "/a/path/ending/with/slash/"
576 assert result["query"] is None
577 assert result["url"] == "https://hostname/a/path/ending/with/slash/"
578 assert result["qsd"] == {"key": "value"}
579 assert result["qsd-"] == {}
580 assert result["qsd+"] == {}
581 assert result["qsd:"] == {}
582
583 # Handle garbage
584 assert utils.parse.parse_url(None) is None
585
586 result = utils.parse.parse_url(
587 "mailto://user:password@otherHost/[email protected]"
588 + "[email protected]&name=Chris%20Caron&format=text"
589 )
590 assert result["schema"] == "mailto"
591 assert result["host"] == "otherHost"
592 assert result["port"] is None
593 assert result["user"] == "user"
594 assert result["password"] == "password"
595 assert unquote(result["fullpath"]) == "/[email protected]"
596 assert result["path"] == "/"
597 assert unquote(result["query"]) == "[email protected]"
598 assert (
599 unquote(result["url"])
600 == "mailto://user:password@otherHost/[email protected]"
601 )
602 assert len(result["qsd"]) == 3
603 assert "name" in result["qsd"]
604 assert unquote(result["qsd"]["name"]) == "Chris Caron"
605 assert "from" in result["qsd"]
606 assert unquote(result["qsd"]["from"]) == "[email protected]"
607 assert "format" in result["qsd"]
608 assert unquote(result["qsd"]["format"]) == "text"
609 assert result["qsd-"] == {}
610 assert result["qsd+"] == {}
611 assert result["qsd:"] == {}
612
613 # Test Passwords with question marks ?; not supported
614 result = utils.parse.parse_url("http://user:pass.with.?question@host")
615 assert result is None
616
617 # just hostnames
618 result = utils.parse.parse_url("nuxref.com")
619 assert result["schema"] == "http"
620 assert result["host"] == "nuxref.com"
621 assert result["port"] is None
622 assert result["user"] is None
623 assert result["password"] is None
624 assert result["fullpath"] is None
625 assert result["path"] is None
626 assert result["query"] is None
627 assert result["url"] == "http://nuxref.com"
628 assert result["qsd"] == {}
629 assert result["qsd-"] == {}
630 assert result["qsd+"] == {}
631 assert result["qsd:"] == {}
632
633 # just host and path
634 result = utils.parse.parse_url("invalid/host")
635 assert result["schema"] == "http"
636 assert result["host"] == "invalid"
637 assert result["port"] is None
638 assert result["user"] is None
639 assert result["password"] is None
640 assert result["fullpath"] == "/host"
641 assert result["path"] == "/"
642 assert result["query"] == "host"
643 assert result["url"] == "http://invalid/host"
644 assert result["qsd"] == {}
645 assert result["qsd-"] == {}
646 assert result["qsd+"] == {}
647 assert result["qsd:"] == {}
648
649 # just all out invalid
650 assert utils.parse.parse_url("?") is None
651 assert utils.parse.parse_url("/") is None
652
653 # Test some illegal strings
654 result = utils.parse.parse_url(object, verify_host=False)
655 assert result is None
656 result = utils.parse.parse_url(None, verify_host=False)
657 assert result is None
658
659 # Just a schema; invalid host
660 result = utils.parse.parse_url("test://")
661 assert result is None
662
663 # Do it again without host validation
664 result = utils.parse.parse_url("test://", verify_host=False)
665 assert result["schema"] == "test"
666 # It's worth noting that the hostname is an empty string and is NEVER set
667 # to None if it wasn't specified.
668 assert result["host"] == ""
669 assert result["port"] is None
670 assert result["user"] is None
671 assert result["password"] is None
672 assert result["fullpath"] is None
673 assert result["path"] is None
674 assert result["query"] is None
675 assert result["url"] == "test://"
676 assert result["qsd"] == {}
677 assert result["qsd-"] == {}
678 assert result["qsd+"] == {}
679 assert result["qsd:"] == {}
680
681 result = utils.parse.parse_url("testhostname")
682 assert result["schema"] == "http"
683 assert result["host"] == "testhostname"
684 assert result["port"] is None
685 assert result["user"] is None
686 assert result["password"] is None
687 assert result["fullpath"] is None
688 assert result["path"] is None
689 assert result["query"] is None
690 # The default_schema kicks in here
691 assert result["url"] == "http://testhostname"
692 assert result["qsd"] == {}
693 assert result["qsd-"] == {}
694 assert result["qsd+"] == {}
695 assert result["qsd:"] == {}
696
697 result = utils.parse.parse_url("example.com", default_schema="unknown")
698 assert result["schema"] == "unknown"
699 assert result["host"] == "example.com"
700 assert result["port"] is None
701 assert result["user"] is None
702 assert result["password"] is None
703 assert result["fullpath"] is None
704 assert result["path"] is None
705 assert result["query"] is None
706 # The default_schema kicks in here
707 assert result["url"] == "unknown://example.com"
708 assert result["qsd"] == {}
709 assert result["qsd-"] == {}
710 assert result["qsd+"] == {}
711 assert result["qsd:"] == {}
712
713 # An empty string without a hostame is still valid if verify_host is set
714 result = utils.parse.parse_url("", verify_host=False)
715 assert result["schema"] == "http"
716 assert result["host"] == ""
717 assert result["port"] is None
718 assert result["user"] is None
719 assert result["password"] is None
720 assert result["fullpath"] is None
721 assert result["path"] is None
722 assert result["query"] is None
723 # The default_schema kicks in here
724 assert result["url"] == "http://"
725 assert result["qsd"] == {}
726 assert result["qsd-"] == {}
727 assert result["qsd+"] == {}
728 assert result["qsd:"] == {}
729
730 # A messed up URL
731 result = utils.parse.parse_url("test://:@/", verify_host=False)
732 assert result["schema"] == "test"
733 assert result["host"] == ""
734 assert result["port"] is None
735 assert result["user"] == ""
736 assert result["password"] == ""
737 assert result["fullpath"] == "/"
738 assert result["path"] == "/"
739 assert result["query"] is None
740 assert result["url"] == "test://:@/"
741 assert result["qsd"] == {}
742 assert result["qsd-"] == {}
743 assert result["qsd+"] == {}
744 assert result["qsd:"] == {}
745
746 result = utils.parse.parse_url(
747 "crazy://:@//_/@^&/jack.json", verify_host=False
748 )
749 assert result["schema"] == "crazy"
750 assert result["host"] == ""
751 assert result["port"] is None
752 assert result["user"] == ""
753 assert result["password"] == ""
754 assert unquote(result["fullpath"]) == "/_/@^&/jack.json"
755 assert unquote(result["path"]) == "/_/@^&/"
756 assert result["query"] == "jack.json"
757 assert unquote(result["url"]) == "crazy://:@/_/@^&/jack.json"
758 assert result["qsd"] == {}
759 assert result["qsd-"] == {}
760 assert result["qsd+"] == {}
761 assert result["qsd:"] == {}
762
763 # Sanitizing
764 result = utils.parse.parse_url(
765 "hTTp://hostname/?+KeY=ValueA&-kEy=ValueB&KEY=Value%20+C&:cOlON=YeS",
766 sanitize=False,
767 )
768
769 assert len(result["qsd-"]) == 1
770 assert len(result["qsd+"]) == 1
771 assert len(result["qsd"]) == 4
772 assert len(result["qsd:"]) == 1
773
774 assert result["schema"] == "http"
775 assert result["host"] == "hostname"
776 assert result["port"] is None
777 assert result["user"] is None
778 assert result["password"] is None
779 assert result["fullpath"] == "/"
780 assert result["path"] == "/"
781 assert result["query"] is None
782 assert result["url"] == "http://hostname/"
783 assert "+KeY" in result["qsd"]
784 assert "-kEy" in result["qsd"]
785 assert ":cOlON" in result["qsd"]
786 assert result["qsd:"]["cOlON"] == "YeS"
787 assert "key" not in result["qsd"]
788 assert "KeY" in result["qsd+"]
789 assert result["qsd+"]["KeY"] == "ValueA"
790 assert "kEy" in result["qsd-"]
791 assert result["qsd-"]["kEy"] == "ValueB"
792 assert result["qsd"]["KEY"] == "Value +C"
793 assert result["qsd"]["+KeY"] == result["qsd+"]["KeY"]
794 assert result["qsd"]["-kEy"] == result["qsd-"]["kEy"]
795
796 # Testing Defect 1264 - whitespaces in url
797 result = utils.parse.parse_url(
798 "posts://example.com/my endpoint?-token=ab cdefg"
799 )
800
801 assert len(result["qsd-"]) == 1
802 assert len(result["qsd+"]) == 0
803 assert len(result["qsd"]) == 1
804 assert len(result["qsd:"]) == 0
805
806 assert result["schema"] == "posts"
807 assert result["host"] == "example.com"
808 assert result["port"] is None
809 assert result["user"] is None
810 assert result["password"] is None
811 assert result["fullpath"] == "/my%20endpoint"
812 assert result["path"] == "/"
813 assert result["query"] == "my%20endpoint"
814 assert result["url"] == "posts://example.com/my%20endpoint"
815 assert "-token" in result["qsd"]
816 assert result["qsd-"]["token"] == "ab cdefg"
817
818 # Testing Defect 1672 - reserved characters in URL paths
819 url = "https://cdn.jsdelivr.net/gh/Cleanuparr/Cleanuparr@main/Logo/256.png"
820 result = utils.parse.parse_url(url)
821 assert result["fullpath"] == "/gh/Cleanuparr/Cleanuparr@main/Logo/256.png"
822 assert result["url"] == url
823
824 # RFC 3986 path characters must survive a parse_url() round trip because
825 # some services distinguish literal characters from encoded ones.
826 url = "https://example.com/a:b@c!d$e&f'g(h)i*j+k=n/file.txt"
827 result = utils.parse.parse_url(url)
828 assert result["fullpath"] == "/a:b@c!d$e&f'g(h)i*j+k=n/file.txt"
829 assert result["url"] == url
830
831 # Keep commas and semicolons encoded because Apprise uses them as path/list
832 # delimiters. Otherwise path data such as a Home Assistant target list
833 # could become extra segments. Related regressions have dedicated plugin
834 # tests.
835 result = utils.parse.parse_url("https://example.com/a,b;c/file.txt")
836 assert result["fullpath"] == "/a%2Cb%3Bc/file.txt"
837
838 # Characters outside an RFC 3986 path segment must remain encoded when the
839 # safe list is expanded.
840 result = utils.parse.parse_url("https://example.com/a b/c[1]#/file.txt")
841 assert "%20" in result["fullpath"]
842 assert "[" not in result["fullpath"]
843 assert "]" not in result["fullpath"]
844
845
846 def test_parse_url_markdown_content():
847 """
848 utils: parse_url() with unmatched-bracket content (GH#1693)
849 """
850 # Content whose host portion carries an unmatched '[' (for example from
851 # Markdown link syntax) makes the underlying urlparse() raise
852 # "Invalid IPv6 URL". parse_url() documents that it returns None when
853 # content cannot be extracted, so that ValueError must not propagate.
854 assert (
855 utils.parse.parse_url("**bold** and [link](https://example.com)")
856 is None
857 )
858 assert utils.parse.parse_url("text with [unclosed bracket") is None
859
860
861 def test_parse_url_path_no_redos():
862 "utils: parse_url() does not regress into slow/backtracking behavior"
863
864 # Escaping uses linear-time table lookups. This guards against a future
865 # regex-based implementation backtracking on untrusted paths.
866 segment = "%40%3A%21%24%26%27%28%29%2A%2B%2C%3B%3D-a" * 5000
867 url = f"https://example.com/{segment}/file.txt?foo=bar"
868
869 start = time.time()
870 result = utils.parse.parse_url(url)
871 elapsed = time.time() - start
872
873 assert result is not None
874 # The generous limit allows slower CI while catching nonlinear behavior.
875 assert elapsed < 5.0
876
877
878 def test_parse_url_simple():
879 "utils: parse_url() testing"
880
881 result = utils.parse.parse_url("http://hostname", simple=True)
882 assert len(result) == 3
883 assert result["schema"] == "http"
884 assert result["host"] == "hostname"
885 assert result["url"] == "http://hostname"
886
887 result = utils.parse.parse_url("http://hostname/", simple=True)
888 assert len(result) == 5
889 assert result["schema"] == "http"
890 assert result["host"] == "hostname"
891 assert result["fullpath"] == "/"
892 assert result["path"] == "/"
893 assert result["url"] == "http://hostname/"
894
895 # colon after hostname without port number is no good
896 assert utils.parse.parse_url("http://hostname:", simple=True) is None
897
898 # An invalid port
899 result = utils.parse.parse_url(
900 "http://hostname:invalid",
901 verify_host=False,
902 strict_port=True,
903 simple=True,
904 )
905 assert len(result) == 4
906 assert result["schema"] == "http"
907 assert result["host"] == "hostname"
908 assert result["port"] == "invalid"
909 assert result["url"] == "http://hostname:invalid"
910
911 # However if we don't verify the host, it is okay
912 result = utils.parse.parse_url(
913 "http://hostname:", verify_host=False, simple=True
914 )
915 assert len(result) == 3
916 assert result["schema"] == "http"
917 assert result["host"] == "hostname:"
918 assert result["url"] == "http://hostname:"
919
920 # A port of Zero is not valid with strict port checking
921 assert (
922 utils.parse.parse_url(
923 "http://hostname:0", strict_port=True, simple=True
924 )
925 is None
926 )
927
928 # Without strict port checking however, it is okay
929 result = utils.parse.parse_url(
930 "http://hostname:0", strict_port=False, simple=True
931 )
932 assert len(result) == 4
933 assert result["schema"] == "http"
934 assert result["port"] == 0
935 assert result["host"] == "hostname"
936 assert result["url"] == "http://hostname:0"
937
938 # A negative port is not valid
939 assert (
940 utils.parse.parse_url(
941 "http://hostname:-92", strict_port=True, simple=True
942 )
943 is None
944 )
945 result = utils.parse.parse_url(
946 "http://hostname:-92", verify_host=False, strict_port=True, simple=True
947 )
948 assert len(result) == 4
949 assert result["schema"] == "http"
950 assert result["host"] == "hostname"
951 assert result["port"] == -92
952 assert result["url"] == "http://hostname:-92"
953
954 # A port that is too large is not valid
955 assert (
956 utils.parse.parse_url(
957 "http://hostname:65536", strict_port=True, simple=True
958 )
959 is None
960 )
961
962 # This is an accetable port (the maximum)
963 result = utils.parse.parse_url(
964 "http://hostname:65535", strict_port=True, simple=True
965 )
966 assert len(result) == 4
967 assert result["schema"] == "http"
968 assert result["host"] == "hostname"
969 assert result["port"] == 65535
970 assert result["url"] == "http://hostname:65535"
971
972 # This is an accetable port (the maximum)
973 result = utils.parse.parse_url(
974 "http://hostname:1", strict_port=True, simple=True
975 )
976 assert len(result) == 4
977 assert result["schema"] == "http"
978 assert result["host"] == "hostname"
979 assert result["port"] == 1
980 assert result["url"] == "http://hostname:1"
981
982 # A port that was identfied as a string is invalid
983 assert (
984 utils.parse.parse_url(
985 "http://hostname:invalid", strict_port=True, simple=True
986 )
987 is None
988 )
989 result = utils.parse.parse_url(
990 "http://hostname:invalid",
991 verify_host=False,
992 strict_port=True,
993 simple=True,
994 )
995 assert len(result) == 4
996 assert result["schema"] == "http"
997 assert result["host"] == "hostname"
998 assert result["port"] == "invalid"
999 assert result["url"] == "http://hostname:invalid"
1000
1001 result = utils.parse.parse_url(
1002 "http://hostname:invalid",
1003 verify_host=False,
1004 strict_port=False,
1005 simple=True,
1006 )
1007 assert len(result) == 3
1008 assert result["schema"] == "http"
1009 assert result["host"] == "hostname:invalid"
1010 assert result["url"] == "http://hostname:invalid"
1011
1012 result = utils.parse.parse_url(
1013 "http://hostname:invalid?key=value&-minuskey=mvalue",
1014 verify_host=False,
1015 strict_port=False,
1016 simple=True,
1017 )
1018 assert len(result) == 4
1019 assert result["schema"] == "http"
1020 assert result["host"] == "hostname:invalid"
1021 assert result["url"] == "http://hostname:invalid"
1022 assert isinstance(result["qsd"], dict)
1023 assert len(result["qsd"]) == 2
1024 assert unquote(result["qsd"]["-minuskey"]) == "mvalue"
1025 assert unquote(result["qsd"]["key"]) == "value"
1026
1027 # Handling of floats
1028 assert (
1029 utils.parse.parse_url(
1030 "http://hostname:4.2", strict_port=True, simple=True
1031 )
1032 is None
1033 )
1034 result = utils.parse.parse_url(
1035 "http://hostname:4.2", verify_host=False, strict_port=True, simple=True
1036 )
1037 assert len(result) == 4
1038 assert result["schema"] == "http"
1039 assert result["host"] == "hostname"
1040 assert result["port"] == "4.2"
1041 assert result["url"] == "http://hostname:4.2"
1042
1043 # A Port of zero is not acceptable for a regular hostname
1044 assert (
1045 utils.parse.parse_url(
1046 "http://hostname:0", strict_port=True, simple=True
1047 )
1048 is None
1049 )
1050
1051 # No host verification (zero is an acceptable port when this is the case
1052 result = utils.parse.parse_url(
1053 "http://hostname:0", verify_host=False, simple=True
1054 )
1055 assert len(result) == 4
1056 assert result["schema"] == "http"
1057 assert result["host"] == "hostname"
1058 assert result["port"] == 0
1059 assert result["url"] == "http://hostname:0"
1060
1061 result = utils.parse.parse_url(
1062 "http://[2001:db8:002a:3256:adfe:05c0:0003:0006]:8080",
1063 verify_host=False,
1064 simple=True,
1065 )
1066 assert len(result) == 4
1067 assert result["schema"] == "http"
1068 assert result["host"] == "[2001:db8:002a:3256:adfe:05c0:0003:0006]"
1069 assert result["port"] == 8080
1070 assert (
1071 result["url"] == "http://[2001:db8:002a:3256:adfe:05c0:0003:0006]:8080"
1072 )
1073
1074 result = utils.parse.parse_url(
1075 "http://hostname:0", verify_host=False, strict_port=True, simple=True
1076 )
1077 assert len(result) == 4
1078 assert result["schema"] == "http"
1079 assert result["host"] == "hostname"
1080 assert result["port"] == 0
1081 assert result["url"] == "http://hostname:0"
1082
1083 result = utils.parse.parse_url("http://hostname/?-KeY=Value", simple=True)
1084 assert len(result) == 6
1085 assert result["schema"] == "http"
1086 assert result["host"] == "hostname"
1087 assert result["fullpath"] == "/"
1088 assert result["path"] == "/"
1089 assert result["url"] == "http://hostname/"
1090 assert "-key" in result["qsd"]
1091 assert unquote(result["qsd"]["-key"]) == "Value"
1092
1093 result = utils.parse.parse_url("http://hostname/?+KeY=Value", simple=True)
1094 assert len(result) == 6
1095 assert result["schema"] == "http"
1096 assert result["host"] == "hostname"
1097 assert result["fullpath"] == "/"
1098 assert result["path"] == "/"
1099 assert result["url"] == "http://hostname/"
1100 assert "+key" in result["qsd"]
1101 assert result["qsd"]["+key"] == "Value"
1102
1103 result = utils.parse.parse_url("http://hostname/?:kEy=vALUE", simple=True)
1104 assert len(result) == 6
1105 assert result["schema"] == "http"
1106 assert result["host"] == "hostname"
1107 assert result["fullpath"] == "/"
1108 assert result["path"] == "/"
1109 assert result["url"] == "http://hostname/"
1110 assert ":key" in result["qsd"]
1111 assert result["qsd"][":key"] == "vALUE"
1112
1113 result = utils.parse.parse_url(
1114 "http://hostname/?+KeY=ValueA&-kEy=ValueB&KEY=Value%20+C&:colon=y",
1115 simple=True,
1116 )
1117 assert len(result) == 6
1118 assert result["schema"] == "http"
1119 assert result["host"] == "hostname"
1120 assert result["fullpath"] == "/"
1121 assert result["path"] == "/"
1122 assert result["url"] == "http://hostname/"
1123 assert "+key" in result["qsd"]
1124 assert "-key" in result["qsd"]
1125 assert ":colon" in result["qsd"]
1126 assert result["qsd"][":colon"] == "y"
1127 assert result["qsd"]["key"] == "Value +C"
1128 assert result["qsd"]["+key"] == "ValueA"
1129 assert result["qsd"]["-key"] == "ValueB"
1130
1131 result = utils.parse.parse_url("http://hostname////", simple=True)
1132 assert len(result) == 5
1133 assert result["schema"] == "http"
1134 assert result["host"] == "hostname"
1135 assert result["fullpath"] == "/"
1136 assert result["path"] == "/"
1137 assert result["url"] == "http://hostname/"
1138
1139 result = utils.parse.parse_url("http://hostname:40////", simple=True)
1140 assert len(result) == 6
1141 assert result["schema"] == "http"
1142 assert result["host"] == "hostname"
1143 assert result["port"] == 40
1144 assert result["fullpath"] == "/"
1145 assert result["path"] == "/"
1146 assert result["url"] == "http://hostname:40/"
1147
1148 result = utils.parse.parse_url("HTTP://HoStNaMe:40/test.php", simple=True)
1149 assert len(result) == 7
1150 assert result["schema"] == "http"
1151 assert result["host"] == "HoStNaMe"
1152 assert result["port"] == 40
1153 assert result["fullpath"] == "/test.php"
1154 assert result["path"] == "/"
1155 assert result["query"] == "test.php"
1156 assert result["url"] == "http://HoStNaMe:40/test.php"
1157
1158 result = utils.parse.parse_url(
1159 "HTTPS://user@hostname/test.py", simple=True
1160 )
1161 assert len(result) == 7
1162 assert result["schema"] == "https"
1163 assert result["host"] == "hostname"
1164 assert result["user"] == "user"
1165 assert result["fullpath"] == "/test.py"
1166 assert result["path"] == "/"
1167 assert result["query"] == "test.py"
1168 assert result["url"] == "https://user@hostname/test.py"
1169
1170 result = utils.parse.parse_url(
1171 " HTTPS://///user@@@hostname///test.py ", simple=True
1172 )
1173 assert len(result) == 7
1174 assert result["schema"] == "https"
1175 assert result["host"] == "hostname"
1176 assert result["user"] == "user"
1177 assert result["fullpath"] == "/test.py"
1178 assert result["path"] == "/"
1179 assert result["query"] == "test.py"
1180 assert result["url"] == "https://user@hostname/test.py"
1181
1182 result = utils.parse.parse_url(
1183 "HTTPS://user:password@otherHost/full///path/name/",
1184 simple=True,
1185 )
1186 assert len(result) == 7
1187 assert result["schema"] == "https"
1188 assert result["host"] == "otherHost"
1189 assert result["user"] == "user"
1190 assert result["password"] == "password"
1191 assert result["fullpath"] == "/full/path/name/"
1192 assert result["path"] == "/full/path/name/"
1193 assert result["url"] == "https://user:password@otherHost/full/path/name/"
1194
1195 # Handle garbage
1196 assert utils.parse.parse_url(None) is None
1197
1198 result = utils.parse.parse_url(
1199 "mailto://user:password@otherHost/[email protected]"
1200 + "[email protected]&name=Chris%20Caron&format=text",
1201 simple=True,
1202 )
1203 assert len(result) == 9
1204 assert result["schema"] == "mailto"
1205 assert result["host"] == "otherHost"
1206 assert result["user"] == "user"
1207 assert result["password"] == "password"
1208 assert unquote(result["fullpath"]) == "/[email protected]"
1209 assert result["path"] == "/"
1210 assert unquote(result["query"]) == "[email protected]"
1211 assert (
1212 unquote(result["url"])
1213 == "mailto://user:password@otherHost/[email protected]"
1214 )
1215 assert len(result["qsd"]) == 3
1216 assert "name" in result["qsd"]
1217 assert unquote(result["qsd"]["name"]) == "Chris Caron"
1218 assert "from" in result["qsd"]
1219 assert unquote(result["qsd"]["from"]) == "[email protected]"
1220 assert "format" in result["qsd"]
1221 assert unquote(result["qsd"]["format"]) == "text"
1222
1223 # Test Passwords with question marks ?; not supported
1224 result = utils.parse.parse_url(
1225 "http://user:pass.with.?question@host", simple=True
1226 )
1227 assert result is None
1228
1229 # just hostnames
1230 result = utils.parse.parse_url(
1231 "nuxref.com",
1232 simple=True,
1233 )
1234 assert len(result) == 3
1235 assert result["schema"] == "http"
1236 assert result["host"] == "nuxref.com"
1237 assert result["url"] == "http://nuxref.com"
1238
1239 # just host and path
1240 result = utils.parse.parse_url("invalid/host", simple=True)
1241 assert len(result) == 6
1242 assert result["schema"] == "http"
1243 assert result["host"] == "invalid"
1244 assert result["fullpath"] == "/host"
1245 assert result["path"] == "/"
1246 assert result["query"] == "host"
1247 assert result["url"] == "http://invalid/host"
1248
1249 # just all out invalid
1250 assert utils.parse.parse_url("?", simple=True) is None
1251 assert utils.parse.parse_url("/", simple=True) is None
1252
1253 # Test some illegal strings
1254 result = utils.parse.parse_url(object, verify_host=False, simple=True)
1255 assert result is None
1256 result = utils.parse.parse_url(None, verify_host=False, simple=True)
1257 assert result is None
1258
1259 # Just a schema; invalid host
1260 result = utils.parse.parse_url("test://", simple=True)
1261 assert result is None
1262
1263 # Do it again without host validation
1264 result = utils.parse.parse_url("test://", verify_host=False, simple=True)
1265 assert len(result) == 2
1266 assert result["schema"] == "test"
1267 assert result["url"] == "test://"
1268
1269 result = utils.parse.parse_url("testhostname", simple=True)
1270 assert len(result) == 3
1271 assert result["schema"] == "http"
1272 assert result["host"] == "testhostname"
1273 # The default_schema kicks in here
1274 assert result["url"] == "http://testhostname"
1275
1276 result = utils.parse.parse_url(
1277 "example.com", default_schema="unknown", simple=True
1278 )
1279 assert len(result) == 3
1280 assert result["schema"] == "unknown"
1281 assert result["host"] == "example.com"
1282 # The default_schema kicks in here
1283 assert result["url"] == "unknown://example.com"
1284
1285 # An empty string without a hostame is still valid if verify_host is set
1286 result = utils.parse.parse_url("", verify_host=False, simple=True)
1287 assert len(result) == 2
1288 assert result["schema"] == "http"
1289 # The default_schema kicks in here
1290 assert result["url"] == "http://"
1291
1292 # A messed up URL
1293 result = utils.parse.parse_url(
1294 "test://:@/", verify_host=False, simple=True
1295 )
1296 assert len(result) == 6
1297 assert result["schema"] == "test"
1298 assert result["user"] == ""
1299 assert result["password"] == ""
1300 assert result["fullpath"] == "/"
1301 assert result["path"] == "/"
1302 assert result["url"] == "test://:@/"
1303
1304 result = utils.parse.parse_url(
1305 "crazy://:@//_/@^&/jack.json", verify_host=False, simple=True
1306 )
1307 assert len(result) == 7
1308 assert result["schema"] == "crazy"
1309 assert result["user"] == ""
1310 assert result["password"] == ""
1311 assert unquote(result["fullpath"]) == "/_/@^&/jack.json"
1312 assert unquote(result["path"]) == "/_/@^&/"
1313 assert result["query"] == "jack.json"
1314 assert unquote(result["url"]) == "crazy://:@/_/@^&/jack.json"
1315
1316
1317 def test_url_assembly():
1318 """ "utils: url_assembly() testing."""
1319
1320 url = "schema://user:password@hostname:port/path/?key=value"
1321 assert (
1322 utils.parse.url_assembly(
1323 **utils.parse.parse_url(url, verify_host=False)
1324 )
1325 == url
1326 )
1327
1328 # Same URL without trailing slash after path
1329 url = "schema://user:password@hostname:port/path?key=value"
1330 assert (
1331 utils.parse.url_assembly(
1332 **utils.parse.parse_url(url, verify_host=False)
1333 )
1334 == url
1335 )
1336
1337 url = "schema://user@hostname:port/path?key=value"
1338 assert (
1339 utils.parse.url_assembly(
1340 **utils.parse.parse_url(url, verify_host=False)
1341 )
1342 == url
1343 )
1344
1345 url = "schema://hostname:10/a/file.php"
1346 assert (
1347 utils.parse.url_assembly(
1348 **utils.parse.parse_url(url, verify_host=False)
1349 )
1350 == url
1351 )
1352
1353 # When spaces and special characters are introduced, the URL
1354 # is hard to mimic what was entered. Instead it is normalized
1355 url = (
1356 "schema://hostname:10/a space/file.php?"
1357 "arg=a+space&arg2=a%20space&arg3=a space"
1358 )
1359 assert (
1360 utils.parse.url_assembly(
1361 **utils.parse.parse_url(url, verify_host=False)
1362 )
1363 == "schema://hostname:10/a%20space/file.php?"
1364 "arg=a%2Bspace&arg2=a%20space&arg3=a%20space"
1365 )
1366
1367 # encode=True should only be used if you're passing in un-assembled
1368 # content... hence the following is likely not what is expected:
1369 assert (
1370 utils.parse.url_assembly(
1371 **utils.parse.parse_url(url, verify_host=False), encode=True
1372 )
1373 == "schema://hostname:10/a%2520space/file.php?"
1374 "arg=a%2Bspace&arg2=a%20space&arg3=a%20space"
1375 )
1376
1377 # But the following utilizes the encode=True and produces the
1378 # desired effects:
1379 content = {
1380 "host": "hostname",
1381 # Note that fullpath requires escaping in this case
1382 "fullpath": "/a space/file.php",
1383 "path": "/a space/",
1384 "query": "file.php",
1385 "schema": "schema",
1386 # our query arguments also require escaping as well
1387 "qsd": {"arg": "a+space", "arg2": "a space", "arg3": "a space"},
1388 }
1389 assert (
1390 utils.parse.url_assembly(**content, encode=True)
1391 == "schema://hostname/a%20space/file.php?"
1392 "arg=a%2Bspace&arg2=a%20space&arg3=a%20space"
1393 )
1394
1395
1396 def test_parse_bool():
1397 "utils: parse_bool() testing"
1398
1399 assert utils.parse.parse_bool("Enabled", None) is True
1400 assert utils.parse.parse_bool("Disabled", None) is False
1401 assert utils.parse.parse_bool("Allow", None) is True
1402 assert utils.parse.parse_bool("Deny", None) is False
1403 assert utils.parse.parse_bool("Yes", None) is True
1404 assert utils.parse.parse_bool("YES", None) is True
1405 assert utils.parse.parse_bool("Always", None) is True
1406 assert utils.parse.parse_bool("No", None) is False
1407 assert utils.parse.parse_bool("NO", None) is False
1408 assert utils.parse.parse_bool("NEVER", None) is False
1409 assert utils.parse.parse_bool("TrUE", None) is True
1410 assert utils.parse.parse_bool("tRUe", None) is True
1411 assert utils.parse.parse_bool("FAlse", None) is False
1412 assert utils.parse.parse_bool("F", None) is False
1413 assert utils.parse.parse_bool("T", None) is True
1414 assert utils.parse.parse_bool("0", None) is False
1415 assert utils.parse.parse_bool("1", None) is True
1416 assert utils.parse.parse_bool("True", None) is True
1417 assert utils.parse.parse_bool("Yes", None) is True
1418 assert utils.parse.parse_bool(1, None) is True
1419 assert utils.parse.parse_bool(0, None) is False
1420 assert utils.parse.parse_bool(True, None) is True
1421 assert utils.parse.parse_bool(False, None) is False
1422
1423 # only the int of 0 will return False since the function
1424 # casts this to a boolean
1425 assert utils.parse.parse_bool(2, None) is True
1426 # An empty list is still false
1427 assert utils.parse.parse_bool([], None) is False
1428 # But a list that contains something is True
1429 assert (
1430 utils.parse.parse_bool(
1431 [
1432 "value",
1433 ],
1434 None,
1435 )
1436 is True
1437 )
1438
1439 # Use Default (which is False)
1440 assert utils.parse.parse_bool("OhYeah") is False
1441 # Adjust Default and get a different result
1442 assert utils.parse.parse_bool("OhYeah", True) is True
1443
1444
1445 def test_is_uuid():
1446 """
1447 API: is_uuid() function
1448 """
1449 # Invalid Entries
1450 assert utils.parse.is_uuid("invalid") is False
1451 assert utils.parse.is_uuid(None) is False
1452 assert utils.parse.is_uuid(5) is False
1453 assert utils.parse.is_uuid(object) is False
1454
1455 # A slightly invalid uuid4 entry
1456 assert utils.parse.is_uuid("591ed387-fa65-ac97-9712-b9d2a15e42a9") is False
1457 assert utils.parse.is_uuid("591ed387-fa65-Jc97-9712-b9d2a15e42a9") is False
1458
1459 # Valid UUID4 Entries
1460 assert utils.parse.is_uuid("591ed387-fa65-4c97-9712-b9d2a15e42a9") is True
1461 assert utils.parse.is_uuid("32b0b447-fe84-4df1-8368-81925e729265") is True
1462
1463
1464 def test_is_hostname():
1465 """
1466 API: is_hostname() function
1467
1468 """
1469 # Valid Hostnames
1470 assert utils.parse.is_hostname("yahoo.ca") == "yahoo.ca"
1471 assert utils.parse.is_hostname("yahoo.ca.") == "yahoo.ca"
1472 assert (
1473 utils.parse.is_hostname("valid-dashes-in-host.ca")
1474 == "valid-dashes-in-host.ca"
1475 )
1476 assert (
1477 utils.parse.is_hostname("valid-underscores_in_host.ca")
1478 == "valid-underscores_in_host.ca"
1479 )
1480
1481 # Underscores are supported by default
1482 assert (
1483 utils.parse.is_hostname("valid_dashes_in_host.ca")
1484 == "valid_dashes_in_host.ca"
1485 )
1486 # However they are not if specified otherwise:
1487 assert (
1488 utils.parse.is_hostname("valid_dashes_in_host.ca", underscore=False)
1489 is False
1490 )
1491
1492 # Invalid Hostnames
1493 assert (
1494 utils.parse.is_hostname("-hostname.that.starts.with.a.dash") is False
1495 )
1496 assert utils.parse.is_hostname("invalid-characters_#^.ca") is False
1497 assert utils.parse.is_hostname(" spaces ") is False
1498 assert utils.parse.is_hostname(" ") is False
1499 assert utils.parse.is_hostname("") is False
1500
1501 # Valid IPv4 Addresses
1502 assert utils.parse.is_hostname("127.0.0.1") == "127.0.0.1"
1503 assert utils.parse.is_hostname("0.0.0.0") == "0.0.0.0"
1504 assert utils.parse.is_hostname("255.255.255.255") == "255.255.255.255"
1505
1506 # But not if we're not checking for this:
1507 assert utils.parse.is_hostname("127.0.0.1", ipv4=False) is False
1508 assert utils.parse.is_hostname("0.0.0.0", ipv4=False) is False
1509 assert utils.parse.is_hostname("255.255.255.255", ipv4=False) is False
1510
1511 # Invalid IPv4 Addresses
1512 assert utils.parse.is_hostname("1.2.3") is False
1513 assert utils.parse.is_hostname("256.256.256.256") is False
1514 assert utils.parse.is_hostname("999.0.0.0") is False
1515 assert utils.parse.is_hostname("1.2.3.4.5") is False
1516 assert utils.parse.is_hostname(" 127.0.0.1 ") is False
1517 assert utils.parse.is_hostname(" ") is False
1518 assert utils.parse.is_hostname("") is False
1519
1520 # Valid IPv6 Addresses (square brakets supported for URL construction)
1521 assert (
1522 utils.parse.is_hostname("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]")
1523 == "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]"
1524 )
1525 assert (
1526 utils.parse.is_hostname("2001:0db8:85a3:0000:0000:8a2e:0370:7334")
1527 == "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]"
1528 )
1529 assert (
1530 utils.parse.is_hostname("[2001:db8:002a:3256:adfe:05c0:0003:0006]")
1531 == "[2001:db8:002a:3256:adfe:05c0:0003:0006]"
1532 )
1533
1534 # localhost
1535 assert utils.parse.is_hostname("::1") == "[::1]"
1536 assert utils.parse.is_hostname("0:0:0:0:0:0:0:1") == "[0:0:0:0:0:0:0:1]"
1537
1538 # But not if we're not checking for this:
1539 assert (
1540 utils.parse.is_hostname(
1541 "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]", ipv6=False
1542 )
1543 is False
1544 )
1545 assert (
1546 utils.parse.is_hostname(
1547 "2001:0db8:85a3:0000:0000:8a2e:0370:7334", ipv6=False
1548 )
1549 is False
1550 )
1551
1552 # Test hostnames with a single character hostname
1553 assert (
1554 utils.parse.is_hostname("cloud.a.example.com", ipv4=False, ipv6=False)
1555 == "cloud.a.example.com"
1556 )
1557
1558
1559 def test_is_ipaddr():
1560 """
1561 API: is_ipaddr() function
1562
1563 """
1564 # Valid IPv4 Addresses
1565 assert utils.parse.is_ipaddr("127.0.0.1") == "127.0.0.1"
1566 assert utils.parse.is_ipaddr("0.0.0.0") == "0.0.0.0"
1567 assert utils.parse.is_ipaddr("255.255.255.255") == "255.255.255.255"
1568
1569 # Invalid IPv4 Addresses
1570 assert utils.parse.is_ipaddr("1.2.3") is False
1571 assert utils.parse.is_ipaddr("256.256.256.256") is False
1572 assert utils.parse.is_ipaddr("999.0.0.0") is False
1573 assert utils.parse.is_ipaddr("1.2.3.4.5") is False
1574 assert utils.parse.is_ipaddr(" 127.0.0.1 ") is False
1575 assert utils.parse.is_ipaddr(" ") is False
1576 assert utils.parse.is_ipaddr("") is False
1577
1578 # Valid IPv6 Addresses (square brakets supported for URL construction)
1579 assert (
1580 utils.parse.is_ipaddr("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]")
1581 == "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]"
1582 )
1583 assert (
1584 utils.parse.is_ipaddr("2001:0db8:85a3:0000:0000:8a2e:0370:7334")
1585 == "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]"
1586 )
1587 assert (
1588 utils.parse.is_ipaddr("[2001:db8:002a:3256:adfe:05c0:0003:0006]")
1589 == "[2001:db8:002a:3256:adfe:05c0:0003:0006]"
1590 )
1591
1592 # localhost
1593 assert utils.parse.is_ipaddr("::1") == "[::1]"
1594 assert utils.parse.is_ipaddr("0:0:0:0:0:0:0:1") == "[0:0:0:0:0:0:0:1]"
1595
1596
1597 def test_is_email():
1598 """
1599 API: is_email() function
1600
1601 """
1602 # Valid Emails
1603 results = utils.parse.is_email("[email protected]")
1604 assert results["name"] == ""
1605 assert results["email"] == "[email protected]"
1606 assert results["full_email"] == "[email protected]"
1607 assert results["domain"] == "gmail.com"
1608 assert results["user"] == "test"
1609 assert results["label"] == ""
1610
1611 results = utils.parse.is_email("test@my-valid_host.com")
1612 assert results["name"] == ""
1613 assert results["email"] == "test@my-valid_host.com"
1614 assert results["full_email"] == "test@my-valid_host.com"
1615 assert results["domain"] == "my-valid_host.com"
1616 assert results["user"] == "test"
1617 assert results["label"] == ""
1618
1619 results = utils.parse.is_email("[email protected]")
1620 assert results["name"] == ""
1621 assert results["email"] == "[email protected]"
1622 assert results["full_email"] == "[email protected]"
1623 assert results["domain"] == "gmail.com"
1624 assert results["user"] == "test"
1625 assert results["label"] == "tag"
1626
1627 # Support Full Names as well
1628 results = utils.parse.is_email("Bill Gates: [email protected]")
1629 assert results["name"] == "Bill Gates"
1630 assert results["email"] == "[email protected]"
1631 assert results["full_email"] == "[email protected]"
1632 assert results["domain"] == "microsoft.com"
1633 assert results["user"] == "bgates"
1634 assert results["label"] == ""
1635
1636 results = utils.parse.is_email("Bill Gates <[email protected]>")
1637 assert results["name"] == "Bill Gates"
1638 assert results["email"] == "[email protected]"
1639 assert results["full_email"] == "[email protected]"
1640 assert results["domain"] == "microsoft.com"
1641 assert results["user"] == "bgates"
1642 assert results["label"] == ""
1643
1644 results = utils.parse.is_email("Bill Gates: <[email protected]>")
1645 assert results["name"] == "Bill Gates"
1646 assert results["email"] == "[email protected]"
1647 assert results["full_email"] == "[email protected]"
1648 assert results["domain"] == "microsoft.com"
1649 assert results["user"] == "bgates"
1650 assert results["label"] == ""
1651
1652 results = utils.parse.is_email("Sundar Pichai <[email protected]>")
1653 assert results["name"] == "Sundar Pichai"
1654 assert results["email"] == "[email protected]"
1655 assert results["full_email"] == "[email protected]"
1656 assert results["domain"] == "gmail.com"
1657 assert results["user"] == "spichai"
1658 assert results["label"] == "ceo"
1659
1660 # Support Quotes
1661 results = utils.parse.is_email('"Chris Hemsworth" <[email protected]>')
1662 assert results["name"] == "Chris Hemsworth"
1663 assert results["email"] == "[email protected]"
1664 assert results["full_email"] == "[email protected]"
1665 assert results["domain"] == "test.com"
1666 assert results["user"] == "ch"
1667 assert results["label"] == ""
1668
1669 # An email without name, but contains delimiters
1670 results = utils.parse.is_email(" <[email protected]>")
1671 assert results["name"] == ""
1672 assert results["email"] == "[email protected]"
1673 assert results["full_email"] == "[email protected]"
1674 assert results["domain"] == "gmail.com"
1675 assert results["user"] == "spichai"
1676 assert results["label"] == ""
1677
1678 # a valid email not properly delimited with a colon or angle bracket
1679 # We do a best guess and still parse it correctly
1680 results = utils.parse.is_email("Name [email protected]")
1681 assert results["name"] == "Name"
1682 assert results["email"] == "[email protected]"
1683 assert results["full_email"] == "[email protected]"
1684 assert results["domain"] == "example.com"
1685 assert results["user"] == "valid"
1686 assert results["label"] == ""
1687
1688 # a valid email not properly delimited with a colon or angle bracket
1689 # We do a best guess and still parse it correctly
1690 results = utils.parse.is_email("Руслан Эра russian+russia@example.ru")
1691 assert results["name"] == "Руслан Эра"
1692 assert results["email"] == "[email protected]"
1693 assert results["full_email"] == "[email protected]"
1694 assert results["domain"] == "example.ru"
1695 assert results["user"] == "russia"
1696 assert results["label"] == "russian"
1697
1698 # Invalid Emails
1699 assert utils.parse.is_email("invalid.com") is False
1700 assert utils.parse.is_email(object()) is False
1701 assert utils.parse.is_email(None) is False
1702 assert utils.parse.is_email("Just A Name") is False
1703 assert utils.parse.is_email("Name <bademail>") is False
1704
1705 # Extended valid emails
1706 #
1707 # The first + denotes our label, so this test really validates
1708 # that there is a correct split and parsing of our email
1709 results = utils.parse.is_email("a-z0-9_!#$%&*+/=?%`{|}~^[email protected]")
1710 assert results["name"] == ""
1711 assert results["label"] == "a-z0-9_!#$%&*"
1712 assert results["email"] == "/=?%`{|}~^[email protected]"
1713 assert results["full_email"] == "a-z0-9_!#$%&*+/=?%`{|}~^[email protected]"
1714 assert results["domain"] == "gmail.com"
1715 assert results["user"] == "/=?%`{|}~^.-"
1716
1717 # A similar test without '+' (use of a label)
1718
1719 # The first + denotes our label, so this test really validates
1720 # that there is a correct split and parsing of our email
1721 results = utils.parse.is_email("a-z0-9_!#$%&*/=?%`{|}~^[email protected]")
1722 assert results["name"] == ""
1723 assert results["label"] == ""
1724 assert results["email"] == "a-z0-9_!#$%&*/=?%`{|}~^[email protected]"
1725 assert results["full_email"] == "a-z0-9_!#$%&*/=?%`{|}~^[email protected]"
1726 assert results["domain"] == "gmail.com"
1727 assert results["user"] == "a-z0-9_!#$%&*/=?%`{|}~^.-"
1728
1729
1730 def test_is_domain_service_target():
1731 """
1732 API: is_domain_service_target() function
1733
1734 """
1735 # Invalid information
1736 assert utils.parse.is_domain_service_target(None) is False
1737 assert utils.parse.is_domain_service_target(42) is False
1738 assert utils.parse.is_domain_service_target(object) is False
1739 assert utils.parse.is_domain_service_target("") is False
1740 assert utils.parse.is_domain_service_target("+()") is False
1741 assert utils.parse.is_domain_service_target("+") is False
1742
1743 # Valid entries
1744 result = utils.parse.is_domain_service_target("service")
1745 assert isinstance(result, dict)
1746 assert result["service"] == "service"
1747 # Default domain
1748 assert result["domain"] == "notify"
1749 assert isinstance(result["targets"], list)
1750 assert len(result["targets"]) == 0
1751
1752 result = utils.parse.is_domain_service_target("domain.service")
1753 assert isinstance(result, dict)
1754 assert result["service"] == "service"
1755 assert result["domain"] == "domain"
1756 assert isinstance(result["targets"], list)
1757 assert len(result["targets"]) == 0
1758
1759 result = utils.parse.is_domain_service_target("domain.service:target")
1760 assert isinstance(result, dict)
1761 assert result["service"] == "service"
1762 assert result["domain"] == "domain"
1763 assert isinstance(result["targets"], list)
1764 assert len(result["targets"]) == 1
1765 assert result["targets"][0] == "target"
1766
1767 result = utils.parse.is_domain_service_target("domain.service:t1,t2,t3")
1768 assert isinstance(result, dict)
1769 assert result["service"] == "service"
1770 assert result["domain"] == "domain"
1771 assert isinstance(result["targets"], list)
1772 assert len(result["targets"]) == 3
1773 assert "t1" in result["targets"]
1774 assert "t2" in result["targets"]
1775 assert "t3" in result["targets"]
1776
1777 result = utils.parse.is_domain_service_target(
1778 "service:t1,t2,t3", domain="new_default"
1779 )
1780 assert isinstance(result, dict)
1781 assert result["service"] == "service"
1782 # Default domain
1783 assert result["domain"] == "new_default"
1784 assert isinstance(result["targets"], list)
1785 assert len(result["targets"]) == 3
1786 assert "t1" in result["targets"]
1787 assert "t2" in result["targets"]
1788 assert "t3" in result["targets"]
1789
1790
1791 def test_is_call_sign_no():
1792 """
1793 API: is_call_sign() function
1794
1795 """
1796 # Invalid numbers
1797 assert utils.parse.is_call_sign(None) is False
1798 assert utils.parse.is_call_sign(42) is False
1799 assert utils.parse.is_call_sign(object) is False
1800 assert utils.parse.is_call_sign("") is False
1801 assert utils.parse.is_call_sign("1") is False
1802 assert utils.parse.is_call_sign("12") is False
1803 assert utils.parse.is_call_sign("abc") is False
1804 assert utils.parse.is_call_sign("+()") is False
1805 assert utils.parse.is_call_sign("+") is False
1806 assert utils.parse.is_call_sign(None) is False
1807 assert utils.parse.is_call_sign(42) is False
1808
1809 # To short or 2 long
1810 assert utils.parse.is_call_sign("DF1ABCX") is False
1811 assert utils.parse.is_call_sign("DF1ABCEFG") is False
1812 assert utils.parse.is_call_sign("1ABCX") is False
1813 # 4th character is not an number
1814 assert utils.parse.is_call_sign("XXXXXX") is False
1815
1816 # Some valid checks
1817 # 1x2
1818 result = utils.parse.is_call_sign("A0AF")
1819 assert isinstance(result, dict)
1820 assert result["callsign"] == "A0AF"
1821 assert result["ssid"] == ""
1822
1823 # 2x1
1824 result = utils.parse.is_call_sign("AA0A")
1825 assert isinstance(result, dict)
1826 assert result["callsign"] == "AA0A"
1827 assert result["ssid"] == ""
1828
1829 # 2x2
1830 result = utils.parse.is_call_sign("AA0AF")
1831 assert isinstance(result, dict)
1832 assert result["callsign"] == "AA0AF"
1833 assert result["ssid"] == ""
1834
1835 result = utils.parse.is_call_sign("AA0AF-23")
1836 assert isinstance(result, dict)
1837 assert result["callsign"] == "AA0AF"
1838 assert result["ssid"] == "23"
1839
1840 # 1x3
1841 result = utils.parse.is_call_sign("K0ACL")
1842 assert isinstance(result, dict)
1843 assert result["callsign"] == "K0ACL"
1844 assert result["ssid"] == ""
1845
1846 # 2x3
1847 result = utils.parse.is_call_sign("DF1ABC")
1848 assert isinstance(result, dict)
1849 assert result["callsign"] == "DF1ABC"
1850 assert result["ssid"] == ""
1851
1852 # Get our SSID
1853 result = utils.parse.is_call_sign("DF1ABC-14")
1854 assert result["callsign"] == "DF1ABC"
1855 assert result["ssid"] == "14"
1856
1857
1858 def test_is_phone_no():
1859 """
1860 API: is_phone_no() function
1861
1862 """
1863 # Invalid numbers
1864 assert utils.parse.is_phone_no(None) is False
1865 assert utils.parse.is_phone_no(42) is False
1866 assert utils.parse.is_phone_no(object) is False
1867 assert utils.parse.is_phone_no("") is False
1868 assert utils.parse.is_phone_no("1") is False
1869 assert utils.parse.is_phone_no("12") is False
1870 assert utils.parse.is_phone_no("abc") is False
1871 assert utils.parse.is_phone_no("+()") is False
1872 assert utils.parse.is_phone_no("+") is False
1873 assert utils.parse.is_phone_no(None) is False
1874 assert utils.parse.is_phone_no(42) is False
1875 assert utils.parse.is_phone_no(object, min_len=0) is False
1876 assert utils.parse.is_phone_no("", min_len=1) is False
1877 assert utils.parse.is_phone_no("abc", min_len=0) is False
1878 assert utils.parse.is_phone_no("", min_len=0) is False
1879
1880 # Ambigious, but will document it here in this test as such
1881 results = utils.parse.is_phone_no("+((()))--+", min_len=0)
1882 assert results["country"] == ""
1883 assert results["area"] == ""
1884 assert results["line"] == ""
1885 assert results["pretty"] == ""
1886 assert results["full"] == ""
1887
1888 # Valid phone numbers
1889 assert utils.parse.is_phone_no("+(0)") is False
1890 results = utils.parse.is_phone_no("+(0)", min_len=1)
1891 assert results["country"] == ""
1892 assert results["area"] == ""
1893 assert results["line"] == "0"
1894 assert results["pretty"] == "0"
1895 assert results["full"] == "0"
1896
1897 assert utils.parse.is_phone_no("1") is False
1898 results = utils.parse.is_phone_no("1", min_len=1)
1899 assert results["country"] == ""
1900 assert results["area"] == ""
1901 assert results["line"] == "1"
1902 assert results["pretty"] == "1"
1903 assert results["full"] == "1"
1904
1905 assert utils.parse.is_phone_no("12") is False
1906 results = utils.parse.is_phone_no("12", min_len=2)
1907 assert results["country"] == ""
1908 assert results["area"] == ""
1909 assert results["line"] == "12"
1910 assert results["pretty"] == "12"
1911 assert results["full"] == "12"
1912
1913 assert utils.parse.is_phone_no("911") is False
1914 results = utils.parse.is_phone_no("911", min_len=3)
1915 assert isinstance(results, dict)
1916 assert results["country"] == ""
1917 assert results["area"] == ""
1918 assert results["line"] == "911"
1919 assert results["pretty"] == "911"
1920 assert results["full"] == "911"
1921
1922 assert utils.parse.is_phone_no("1234") is False
1923 results = utils.parse.is_phone_no("1234", min_len=4)
1924 assert isinstance(results, dict)
1925 assert results["country"] == ""
1926 assert results["area"] == ""
1927 assert results["line"] == "1234"
1928 assert results["pretty"] == "1234"
1929 assert results["full"] == "1234"
1930
1931 assert utils.parse.is_phone_no("12345") is False
1932 results = utils.parse.is_phone_no("12345", min_len=5)
1933 assert isinstance(results, dict)
1934 assert results["country"] == ""
1935 assert results["area"] == ""
1936 assert results["line"] == "12345"
1937 assert results["pretty"] == "12345"
1938 assert results["full"] == "12345"
1939
1940 assert utils.parse.is_phone_no("123456") is False
1941 results = utils.parse.is_phone_no("123456", min_len=6)
1942 assert isinstance(results, dict)
1943 assert results["country"] == ""
1944 assert results["area"] == ""
1945 assert results["line"] == "123456"
1946 assert results["pretty"] == "123456"
1947 assert results["full"] == "123456"
1948
1949 # at 7 digits, the format hyphenates in the `pretty` section
1950 assert utils.parse.is_phone_no("1234567") is False
1951 results = utils.parse.is_phone_no("1234567", min_len=7)
1952 assert isinstance(results, dict)
1953 assert results["country"] == ""
1954 assert results["area"] == ""
1955 assert results["line"] == "1234567"
1956 assert results["pretty"] == "123-4567"
1957 assert results["full"] == "1234567"
1958
1959 results = utils.parse.is_phone_no("1(800) 123-4567")
1960 assert isinstance(results, dict)
1961 assert results["country"] == "1"
1962 assert results["area"] == "800"
1963 assert results["line"] == "1234567"
1964 assert results["pretty"] == "+1 800-123-4567"
1965 assert results["full"] == "18001234567"
1966
1967
1968 def test_parse_call_sign():
1969 """utils: parse_call_sign() testing"""
1970 # A simple single array entry (As str)
1971 results = utils.parse.parse_call_sign("")
1972 assert isinstance(results, list)
1973 assert len(results) == 0
1974
1975 # just delimeters
1976 results = utils.parse.parse_call_sign(", ,, , ,,, ")
1977 assert isinstance(results, list)
1978 assert len(results) == 0
1979
1980 results = utils.parse.parse_call_sign(None)
1981 assert isinstance(results, list)
1982 assert len(results) == 0
1983
1984 results = utils.parse.parse_call_sign(42)
1985 assert isinstance(results, list)
1986 assert len(results) == 0
1987
1988 results = utils.parse.parse_call_sign(
1989 "this is not a parseable call sign at all"
1990 )
1991 assert isinstance(results, list)
1992 assert len(results) == 9
1993
1994 results = utils.parse.parse_call_sign(
1995 "this is not a parseable call sign at all", store_unparseable=False
1996 )
1997 assert isinstance(results, list)
1998 assert len(results) == 0
1999
2000 # Now test valid call signs
2001 results = utils.parse.parse_call_sign("0A1DEF")
2002 assert isinstance(results, list)
2003 assert len(results) == 1
2004 assert "0A1DEF" in results
2005
2006 results = utils.parse.parse_call_sign("0A1DEF, DF1ABC")
2007 assert isinstance(results, list)
2008 assert len(results) == 2
2009 assert "0A1DEF" in results
2010 assert "DF1ABC" in results
2011
2012 results = utils.parse.parse_call_sign("AA0A, A0AF-12, GARBAGE")
2013 assert isinstance(results, list)
2014 assert len(results) == 2
2015 assert "AA0A" in results
2016 assert "A0AF-12" in results
2017
2018
2019 def test_parse_domain_service_targets():
2020 """utils: parse_domain_service_targets() testing"""
2021
2022 results = utils.parse.parse_domain_service_targets("")
2023 assert isinstance(results, list)
2024 assert len(results) == 0
2025
2026 results = utils.parse.parse_domain_service_targets("service1 service2")
2027 assert isinstance(results, list)
2028 assert len(results) == 2
2029 assert "service1" in results
2030 assert "service2" in results
2031
2032 results = utils.parse.parse_domain_service_targets(
2033 "service1:target1,target2"
2034 )
2035 assert isinstance(results, list)
2036 assert len(results) == 1
2037 assert "service1:target1,target2" in results
2038
2039 results = utils.parse.parse_domain_service_targets(
2040 "service1:target1,target2 service2 domain.service3"
2041 )
2042 assert isinstance(results, list)
2043 assert len(results) == 3
2044 assert "service1:target1,target2" in results
2045 assert "service2" in results
2046 assert "domain.service3" in results
2047
2048 # Support a comma in the space between entries
2049 results = utils.parse.parse_domain_service_targets(
2050 "service1:target1,target2, service2 ,domain.service3, , , service4"
2051 )
2052 assert isinstance(results, list)
2053 assert len(results) == 4
2054 assert "service1:target1,target2" in results
2055 assert "service2" in results
2056 assert "domain.service3" in results
2057 assert "service4" in results
2058
2059 results = utils.parse.parse_domain_service_targets(
2060 "service:target1,target2"
2061 )
2062 assert isinstance(results, list)
2063 assert len(results) == 1
2064 assert "service:target1,target2" in results
2065
2066 # Handle unparseables
2067 results = utils.parse.parse_domain_service_targets(
2068 ": %invalid ^entries%", store_unparseable=False
2069 )
2070 assert isinstance(results, list)
2071 assert len(results) == 0
2072
2073 # Verify many separators complete in reasonable time.
2074 t0 = time.monotonic()
2075 utils.parse.parse_domain_service_targets("ha.smtp" + " , " * 30)
2076 assert time.monotonic() - t0 < 5.0
2077
2078
2079 def test_parse_phone_no():
2080 """utils: parse_phone_no() testing"""
2081 # A simple single array entry (As str)
2082 results = utils.parse.parse_phone_no("")
2083 assert isinstance(results, list)
2084 assert len(results) == 0
2085
2086 # just delimeters
2087 results = utils.parse.parse_phone_no(", ,, , ,,, ")
2088 assert isinstance(results, list)
2089 assert len(results) == 0
2090
2091 results = utils.parse.parse_phone_no(",")
2092 assert isinstance(results, list)
2093 assert len(results) == 0
2094
2095 results = utils.parse.parse_phone_no(None)
2096 assert isinstance(results, list)
2097 assert len(results) == 0
2098
2099 results = utils.parse.parse_phone_no(42)
2100 assert isinstance(results, list)
2101 assert len(results) == 0
2102
2103 results = utils.parse.parse_phone_no(
2104 "this is not a parseable phoneno at all"
2105 )
2106 assert isinstance(results, list)
2107 assert len(results) == 8
2108 # Now we do it again with the store_unparsable flag set to False
2109 results = utils.parse.parse_phone_no(
2110 "this is not a parseable email at all", store_unparseable=False
2111 )
2112 assert isinstance(results, list)
2113 assert len(results) == 0
2114
2115 results = utils.parse.parse_phone_no("+", store_unparseable=False)
2116 assert isinstance(results, list)
2117 assert len(results) == 0
2118
2119 results = utils.parse.parse_phone_no("(", store_unparseable=False)
2120 assert isinstance(results, list)
2121 assert len(results) == 0
2122
2123 # Number is too short
2124 results = utils.parse.parse_phone_no("0", store_unparseable=False)
2125 assert isinstance(results, list)
2126 assert len(results) == 0
2127
2128 results = utils.parse.parse_phone_no("12", store_unparseable=False)
2129 assert isinstance(results, list)
2130 assert len(results) == 0
2131
2132 # Now test valid phone numbers
2133 results = utils.parse.parse_phone_no("+1 (124) 245 2345")
2134 assert isinstance(results, list)
2135 assert len(results) == 1
2136 assert "+1 (124) 245 2345" in results
2137
2138 results = utils.parse.parse_phone_no("911", store_unparseable=False)
2139 assert isinstance(results, list)
2140 assert len(results) == 1
2141 assert "911" in results
2142
2143 results = utils.parse.parse_phone_no(
2144 "911, 123-123-1234", store_unparseable=False
2145 )
2146 assert isinstance(results, list)
2147 assert len(results) == 2
2148 assert "911" in results
2149 assert "123-123-1234" in results
2150
2151 # Space variations
2152 results = utils.parse.parse_phone_no(" 911 , +1 (123) 123-1234")
2153 assert isinstance(results, list)
2154 assert len(results) == 2
2155 assert "911" in results
2156 assert "+1 (123) 123-1234" in results
2157
2158 results = utils.parse.parse_phone_no(" 911 , + 1 ( 123 ) 123-1234")
2159 assert isinstance(results, list)
2160 assert len(results) == 2
2161 assert "911" in results
2162 assert "+ 1 ( 123 ) 123-1234" in results
2163
2164 # Verify trailing-whitespace runs complete in reasonable time.
2165 t0 = time.monotonic()
2166 results = utils.parse.parse_phone_no("+12345678901" + " " * 1000)
2167 assert time.monotonic() - t0 < 5.0
2168 assert results == ["+12345678901"]
2169
2170
2171 def test_parse_emails():
2172 """utils: parse_emails() testing"""
2173 # A simple single array entry (As str)
2174 results = utils.parse.parse_emails("")
2175 assert isinstance(results, list)
2176 assert len(results) == 0
2177
2178 # just delimeters
2179 results = utils.parse.parse_emails(", ,, , ,,, ")
2180 assert isinstance(results, list)
2181 assert len(results) == 0
2182
2183 results = utils.parse.parse_emails(",")
2184 assert isinstance(results, list)
2185 assert len(results) == 0
2186
2187 results = utils.parse.parse_emails(None)
2188 assert isinstance(results, list)
2189 assert len(results) == 0
2190
2191 results = utils.parse.parse_emails(42)
2192 assert isinstance(results, list)
2193 assert len(results) == 0
2194
2195 results = utils.parse.parse_emails("this is not a parseable email at all")
2196 assert isinstance(results, list)
2197 assert len(results) == 8
2198 # Now we do it again with the store_unparsable flag set to False
2199 results = utils.parse.parse_emails(
2200 "this is not a parseable email at all", store_unparseable=False
2201 )
2202 assert isinstance(results, list)
2203 assert len(results) == 0
2204
2205 # Now test valid emails
2206 results = utils.parse.parse_emails("[email protected]")
2207 assert isinstance(results, list)
2208 assert len(results) == 1
2209 assert "[email protected]" in results
2210
2211 results = utils.parse.parse_emails("a@")
2212 assert isinstance(results, list)
2213 assert len(results) == 1
2214 assert "a@" in results
2215
2216 results = utils.parse.parse_emails("[email protected] [email protected]")
2217 assert isinstance(results, list)
2218 assert len(results) == 2
2219 assert "[email protected]" in results
2220 assert "[email protected]" in results
2221
2222 # Commas and spaces found inside URLs are ignored
2223 emails = [
2224 "[email protected],",
2225 "[email protected],,, [email protected]",
2226 "Chuck Norris [email protected]",
2227 "David Spade [email protected], Yours Truly [email protected]",
2228 ]
2229
2230 results = utils.parse.parse_emails(", ".join(emails))
2231 assert isinstance(results, list)
2232 assert len(results) == 6
2233 assert "[email protected]" in results
2234 assert "[email protected]" in results
2235 assert "[email protected]" in results
2236 assert "Chuck Norris [email protected]" in results
2237 assert "David Spade [email protected]" in results
2238 assert "Yours Truly [email protected]" in results
2239
2240 # Test triangle bracket parsing
2241 # Commas and spaces found inside URLs are ignored
2242 emails = [
2243 "User1 [email protected]",
2244 "User 2 [email protected]",
2245 "User Three <[email protected]>",
2246 "The Forth User: <[email protected]>",
2247 "5th User: [email protected]",
2248 ]
2249
2250 results = utils.parse.parse_emails(", ".join(emails))
2251 assert isinstance(results, list)
2252 assert len(results) == len(emails)
2253 for email in emails:
2254 assert email in results
2255 is_email = utils.parse.is_email(email)
2256 assert is_email
2257 assert is_email.get("name")
2258
2259 # pass the entries in as a list
2260 results = utils.parse.parse_emails(emails)
2261 assert isinstance(results, list)
2262 assert len(results) == len(emails)
2263 for email in emails:
2264 assert email in results
2265
2266 # Pass in some unparseables
2267 results = utils.parse.parse_emails("garbage")
2268 assert isinstance(results, list)
2269 assert len(results) == 1
2270
2271 results = utils.parse.parse_emails("garbage", store_unparseable=False)
2272 assert isinstance(results, list)
2273 assert len(results) == 0
2274
2275 # Pass in garbage
2276 results = utils.parse.parse_emails(object)
2277 assert isinstance(results, list)
2278 assert len(results) == 0
2279
2280 results = utils.parse.parse_emails(42)
2281 assert isinstance(results, list)
2282 assert len(results) == 0
2283
2284 results = utils.parse.parse_emails([None, object, 42])
2285 assert isinstance(results, list)
2286 assert len(results) == 0
2287
2288 # Verify trailing-whitespace runs complete in reasonable time.
2289 t0 = time.monotonic()
2290 results = utils.parse.parse_emails("[email protected]" + " " * 400)
2291 assert time.monotonic() - t0 < 5.0
2292 assert results == ["[email protected]"]
2293
2294 # Quoted display names containing commas are kept as a single token.
2295 results = utils.parse.parse_emails(
2296 '"John, Jason & Mike" <[email protected]>'
2297 )
2298 assert results == ['"John, Jason & Mike" <[email protected]>']
2299
2300 results = utils.parse.parse_emails(
2301 '"Smith, Jane" <[email protected]>, Bob Jones <[email protected]>'
2302 )
2303 assert len(results) == 2
2304 assert '"Smith, Jane" <[email protected]>' in results
2305 assert "Bob Jones <[email protected]>" in results
2306
2307
2308 def test_parse_urls():
2309 """utils: parse_urls() testing"""
2310 # A simple single array entry (As str)
2311 results = utils.parse.parse_urls("")
2312 assert isinstance(results, list)
2313 assert len(results) == 0
2314
2315 # just delimeters
2316 results = utils.parse.parse_urls(", ,, , ,,, ")
2317 assert isinstance(results, list)
2318 assert len(results) == 0
2319
2320 results = utils.parse.parse_urls(",")
2321 assert isinstance(results, list)
2322 assert len(results) == 0
2323
2324 results = utils.parse.parse_urls(None)
2325 assert isinstance(results, list)
2326 assert len(results) == 0
2327
2328 results = utils.parse.parse_urls(42)
2329 assert isinstance(results, list)
2330 assert len(results) == 0
2331
2332 results = utils.parse.parse_urls("this is not a parseable url at all")
2333 assert isinstance(results, list)
2334 # we still end up returning this
2335 assert len(results) == 8
2336
2337 results = utils.parse.parse_urls(
2338 "this is not a parseable url at all", store_unparseable=False
2339 )
2340 assert isinstance(results, list)
2341 assert len(results) == 0
2342
2343 # Now test valid URLs
2344 results = utils.parse.parse_urls("windows://")
2345 assert isinstance(results, list)
2346 assert len(results) == 1
2347 assert "windows://" in results
2348
2349 results = utils.parse.parse_urls("windows:// gnome://")
2350 assert isinstance(results, list)
2351 assert len(results) == 2
2352 assert "windows://" in results
2353 assert "gnome://" in results
2354
2355 # We don't want to parse out URLs that are part of another URL's arguments
2356 results = utils.parse.parse_urls("discord://host?url=https://localhost")
2357 assert isinstance(results, list)
2358 assert len(results) == 1
2359 assert "discord://host?url=https://localhost" in results
2360
2361 # Commas and spaces found inside URLs are ignored
2362 urls = [
2363 (
2364 "mailgun://[email protected]/apikey/"
2365 "[email protected],[email protected],,"
2366 " [email protected]"
2367 ),
2368 (
2369 "mailgun://[email protected]/apikey/"
2370 "[email protected],,[email protected],, [email protected], ,"
2371 ),
2372 "windows://",
2373 ]
2374
2375 # Since comma's and whitespace are the delimiters; they won't be
2376 # present at the end of the URL; so we just need to write a special
2377 # rstrip() as a regular exression to handle whitespace (\s) and comma
2378 # delimiter
2379 rstrip_re = re.compile(r"[\s,]+$")
2380
2381 # Since a comma acts as a delimiter, we run a risk of a problem where the
2382 # comma exists as part of the URL and is therefore lost if it was found
2383 # at the end of it.
2384
2385 results = utils.parse.parse_urls(", ".join(urls))
2386 assert isinstance(results, list)
2387 assert len(results) == len(urls)
2388 for url in urls:
2389 assert rstrip_re.sub("", url) in results
2390
2391 # However if a comma is found at the end of a single url without a new
2392 # match to hit, it is saved and not lost
2393
2394 # The comma at the end of the password will not be lost if we're
2395 # dealing with a single entry:
2396 url = "http://hostname?password=,abcd,"
2397 results = utils.parse.parse_urls(url)
2398 assert isinstance(results, list)
2399 assert len(results) == 1
2400 assert url in results
2401
2402 # however if we have multiple entries, commas and spaces between
2403 # URLs will be lost, however the last URL will not lose the comma
2404 urls = [
2405 "schema1://hostname?password=,abcd,",
2406 "schema2://hostname?password=,abcd,",
2407 ]
2408 results = utils.parse.parse_urls(", ".join(urls))
2409 assert isinstance(results, list)
2410 assert len(results) == len(urls)
2411
2412 # No match because the comma is gone in the results entry
2413 # schema1://hostname?password=,abcd
2414 assert urls[0] not in results
2415 assert urls[0][:-1] in results
2416
2417 # However we wouldn't have lost the comma in the second one:
2418 # schema2://hostname?password=,abcd,
2419 assert urls[1] in results
2420
2421 # Pass the list in (as a list); results are the same
2422 results = utils.parse.parse_urls(urls)
2423 assert isinstance(results, list)
2424 assert len(results) == len(urls)
2425
2426 # Pass in garbage
2427 results = utils.parse.parse_urls(object)
2428 assert isinstance(results, list)
2429 assert len(results) == 0
2430
2431 results = utils.parse.parse_urls(42)
2432 assert isinstance(results, list)
2433 assert len(results) == 0
2434
2435 results = utils.parse.parse_urls([None, object, 42])
2436 assert isinstance(results, list)
2437 assert len(results) == 0
2438
2439 # Verify trailing-whitespace runs complete in reasonable time.
2440 t0 = time.monotonic()
2441 results = utils.parse.parse_urls("https://example.com" + " " * 50000)
2442 assert time.monotonic() - t0 < 5.0
2443 assert results == ["https://example.com"]
2444
2445
2446 def test_dict_full_update():
2447 """utils: dict_full_update() testing"""
2448 dict_1 = {
2449 "a": 1,
2450 "b": 2,
2451 "c": 3,
2452 "d": {
2453 "z": 27,
2454 "y": 26,
2455 "x": 25,
2456 },
2457 }
2458
2459 dict_2 = {
2460 "d": {
2461 "x": "updated",
2462 "w": 24,
2463 },
2464 "c": "updated",
2465 "e": 5,
2466 }
2467 utils.logic.dict_full_update(dict_1, dict_2)
2468 # Dictionary 2 is untouched
2469 assert len(dict_2) == 3
2470 assert dict_2["c"] == "updated"
2471 assert dict_2["d"]["w"] == 24
2472 assert dict_2["d"]["x"] == "updated"
2473 assert dict_2["e"] == 5
2474
2475 # Dictionary 3 however has entries from Dict 2 applied
2476 # without disrupting entries that were not matched.
2477 assert len(dict_1) == 5
2478 assert dict_1["a"] == 1
2479 assert dict_1["b"] == 2
2480 assert dict_1["c"] == "updated"
2481 assert dict_1["d"]["w"] == 24
2482 assert dict_1["d"]["x"] == "updated"
2483 assert dict_1["d"]["y"] == 26
2484 assert dict_1["d"]["z"] == 27
2485 assert dict_1["e"] == 5
2486
2487
2488 def test_parse_list():
2489 """utils: parse_list() testing"""
2490
2491 # A simple single array entry (As str)
2492 results = utils.parse.parse_list(
2493 ".mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso"
2494 )
2495
2496 assert results == sorted(
2497 [
2498 ".divx",
2499 ".iso",
2500 ".mkv",
2501 ".mov",
2502 ".mpg",
2503 ".avi",
2504 ".mpeg",
2505 ".vob",
2506 ".xvid",
2507 ".wmv",
2508 ".mp4",
2509 ]
2510 )
2511
2512 class StrangeObject:
2513 def __str__(self):
2514 return ".avi"
2515
2516 # Now 2 lists with lots of duplicates and other delimiters
2517 results = utils.parse.parse_list(
2518 ".mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg .mpeg,.vob,,; ;",
2519 (".mkv,.avi,.divx,.xvid,.mov ", " .wmv,.mp4;.mpg,.mpeg,"),
2520 ".vob,.iso",
2521 [
2522 ".vob",
2523 [
2524 ".vob",
2525 ".mkv",
2526 StrangeObject(),
2527 ],
2528 ],
2529 StrangeObject(),
2530 )
2531
2532 assert results == sorted(
2533 [
2534 ".divx",
2535 ".iso",
2536 ".mkv",
2537 ".mov",
2538 ".mpg",
2539 ".avi",
2540 ".mpeg",
2541 ".vob",
2542 ".xvid",
2543 ".wmv",
2544 ".mp4",
2545 ]
2546 )
2547
2548 # Garbage in is removed
2549 assert utils.parse.parse_list(object(), 42, None) == []
2550
2551 # Now a list with extras we want to add as strings
2552 # empty entries are removed
2553 results = utils.parse.parse_list(
2554 [
2555 ".divx",
2556 ".iso",
2557 ".mkv",
2558 ".mov",
2559 "",
2560 " ",
2561 ".avi",
2562 ".mpeg",
2563 ".vob",
2564 ".xvid",
2565 ".mp4",
2566 ],
2567 ".mov,.wmv,.mp4,.mpg",
2568 )
2569
2570 assert results == sorted(
2571 [
2572 ".divx",
2573 ".wmv",
2574 ".iso",
2575 ".mkv",
2576 ".mov",
2577 ".mpg",
2578 ".avi",
2579 ".vob",
2580 ".xvid",
2581 ".mpeg",
2582 ".mp4",
2583 ]
2584 )
2585
2586
2587 def test_import_module(tmpdir):
2588 """utils: import_module testing"""
2589 # Prepare ourselves a file to work with
2590 bad_file_base = tmpdir.mkdir("a")
2591 bad_file = bad_file_base.join("README.md")
2592 bad_file.write(
2593 cleandoc("""
2594 I'm a README file, not a Python one.
2595
2596 I can't be loaded
2597 """)
2598 )
2599 assert utils.module.import_module(str(bad_file), "invalidfile1") is None
2600 assert (
2601 utils.module.import_module(str(bad_file_base), "invalidfile2") is None
2602 )
2603
2604
2605 def test_module_detection(tmpdir):
2606 """utils: test_module_detection() testing"""
2607
2608 # Clear our working variables so they don't obstruct with the tests here
2609 N_MGR._paths_previously_scanned.clear()
2610 N_MGR._custom_module_map.clear()
2611
2612 # Test case where we load invalid data
2613 N_MGR.module_detection(None)
2614
2615 # Invalid data does not load anything
2616 assert len(N_MGR._paths_previously_scanned) == 0
2617 assert len(N_MGR._custom_module_map) == 0
2618
2619 # Prepare ourselves a file to work with
2620 notify_hook_a_base = tmpdir.mkdir("a")
2621 notify_hook_a = notify_hook_a_base.join("hook.py")
2622 notify_hook_a.write(
2623 cleandoc("""
2624 from apprise.decorators import notify
2625
2626 @notify(on="clihook")
2627 def mywrapper(body, title, notify_type, *args, **kwargs):
2628 pass
2629 """)
2630 )
2631
2632 notify_ignore = notify_hook_a_base.join("README.md")
2633 notify_ignore.write(
2634 cleandoc("""
2635 We're not a .py file, so this file gets gracefully skipped
2636 """)
2637 )
2638
2639 # Not previously loaded
2640 assert "clihook" not in N_MGR
2641
2642 # load entry by string
2643 N_MGR.module_detection(str(notify_hook_a))
2644 N_MGR.module_detection(str(notify_ignore))
2645 N_MGR.module_detection(str(notify_hook_a_base))
2646
2647 assert len(N_MGR._paths_previously_scanned) == 3
2648 assert len(N_MGR._custom_module_map) == 1
2649
2650 # Now loaded
2651 assert "clihook" in N_MGR
2652
2653 # load entry by array
2654 N_MGR.module_detection([str(notify_hook_a)])
2655
2656 # No changes to our path
2657 assert len(N_MGR._paths_previously_scanned) == 3
2658 assert len(N_MGR._custom_module_map) == 1
2659
2660 # Reset our variables for the next test
2661 N_MGR._paths_previously_scanned.clear()
2662 N_MGR._custom_module_map.clear()
2663
2664 # Hidden files are ignored
2665 notify_hook_b_base = tmpdir.mkdir("b")
2666 notify_hook_b = notify_hook_b_base.join(".hook.py")
2667 notify_hook_b.write(
2668 cleandoc("""
2669 from apprise.decorators import notify
2670
2671 # this is in a hidden file so it will not load
2672 @notify(on="hidden")
2673 def mywrapper(body, title, notify_type, *args, **kwargs):
2674 pass
2675 """)
2676 )
2677
2678 assert "hidden" not in N_MGR
2679
2680 N_MGR.module_detection([str(notify_hook_b)])
2681
2682 # Verify that it did not load
2683 assert "hidden" not in N_MGR
2684
2685 # Path was scanned; nothing loaded
2686 assert len(N_MGR._paths_previously_scanned) == 1
2687 assert len(N_MGR._custom_module_map) == 0
2688
2689 # Reset our variables for the next test
2690 N_MGR._paths_previously_scanned.clear()
2691 N_MGR._custom_module_map.clear()
2692
2693 # modules with no hooks found are ignored
2694 notify_hook_c_base = tmpdir.mkdir("c")
2695 notify_hook_c = notify_hook_c_base.join("empty.py")
2696 notify_hook_c.write("")
2697
2698 N_MGR.module_detection([str(notify_hook_c)])
2699
2700 # File was found, no custom modules
2701 assert len(N_MGR._paths_previously_scanned) == 1
2702 assert len(N_MGR._custom_module_map) == 0
2703
2704 # A new path scanned
2705 N_MGR.module_detection([str(notify_hook_c_base)])
2706 assert len(N_MGR._paths_previously_scanned) == 2
2707 assert len(N_MGR._custom_module_map) == 0
2708
2709 def create_hook(tdir, cache=True, on="valid1"):
2710 """Just a temporary hook creation tool for writing a working notify
2711 hook."""
2712 tdir.write(
2713 cleandoc(f"""
2714 from apprise.decorators import notify
2715
2716 # this is a good hook but burried in hidden directory which won't
2717 # be accessed unless the file is pointed to via absolute path
2718 @notify(on="{on}")
2719 def mywrapper(body, title, notify_type, *args, **kwargs):
2720 pass
2721 """)
2722 )
2723
2724 N_MGR.module_detection([str(tdir)], cache=cache)
2725
2726 create_hook(notify_hook_c, on="valid1")
2727 assert "valid1" not in N_MGR
2728
2729 # Even if we correct our empty file; the fact the directory has been
2730 # scanned and failed to load (same with file), it won't be loaded
2731 # a second time. This is intentional since module_detection() get's
2732 # called for every AppriseAsset() object creation. This prevents us
2733 # from reloading conent over and over again wasting resources
2734 assert "valid1" not in N_MGR
2735 N_MGR.module_detection([str(notify_hook_c)])
2736 assert len(N_MGR._paths_previously_scanned) == 2
2737 assert len(N_MGR._custom_module_map) == 0
2738
2739 # Even by absolute path...
2740 N_MGR.module_detection([str(notify_hook_c)])
2741 assert "valid1" not in N_MGR
2742 assert len(N_MGR._paths_previously_scanned) == 2
2743 assert len(N_MGR._custom_module_map) == 0
2744
2745 # However we can bypass the cache if we really want to
2746 N_MGR.module_detection([str(notify_hook_c_base)], cache=False)
2747 assert "valid1" in N_MGR
2748 assert len(N_MGR._paths_previously_scanned) == 2
2749 assert len(N_MGR._custom_module_map) == 1
2750
2751 # Bypassing it twice causes the module to load twice (not very efficient)
2752 # However we can bypass the cache if we really want to
2753 N_MGR.module_detection([str(notify_hook_c_base)], cache=False)
2754 assert "valid1" in N_MGR
2755 assert len(N_MGR._paths_previously_scanned) == 2
2756 assert len(N_MGR._custom_module_map) == 1
2757
2758 # If you update the module (corrupting it in the process and reload)
2759 notify_hook_c.write(
2760 cleandoc("""
2761 raise ValueError
2762 """)
2763 )
2764
2765 # Force no cache to cause the file to be replaced
2766 N_MGR.module_detection([str(notify_hook_c_base)], cache=False)
2767
2768 # Our valid entry is no longer loaded
2769 assert "valid1" not in N_MGR
2770
2771 # No change to scanned paths
2772 assert len(N_MGR._paths_previously_scanned) == 2
2773 # The previously loaded module is now gone
2774 assert len(N_MGR._custom_module_map) == 0
2775
2776 # Reload our valid1 entry
2777 create_hook(notify_hook_c, on="valid1", cache=False)
2778 assert "valid1" in N_MGR
2779 assert len(N_MGR._paths_previously_scanned) == 2
2780 assert len(N_MGR._custom_module_map) == 1
2781
2782 # Prepare an empty file
2783 notify_hook_c.write("")
2784 N_MGR.module_detection([str(notify_hook_c_base)], cache=False)
2785
2786 # Our valid entry is no longer loaded
2787 assert "valid1" not in N_MGR
2788 assert len(N_MGR._paths_previously_scanned) == 2
2789 assert len(N_MGR._custom_module_map) == 0
2790
2791 # Now reload our module again (this time rather then an exception, the
2792 # module is read back and swaps `valid1` for `valid2`
2793 create_hook(notify_hook_c, on="valid1", cache=False)
2794 assert "valid1" in N_MGR
2795 assert "valid2" not in N_MGR
2796 assert len(N_MGR._paths_previously_scanned) == 2
2797 assert len(N_MGR._custom_module_map) == 1
2798
2799 create_hook(notify_hook_c, on="valid2", cache=False)
2800 assert "valid1" not in N_MGR
2801 assert "valid2" in N_MGR
2802 assert len(N_MGR._paths_previously_scanned) == 2
2803 assert len(N_MGR._custom_module_map) == 1
2804
2805 # Reset our variables for the next test
2806 create_hook(notify_hook_c, on="valid1", cache=False)
2807 del N_MGR["valid1"]
2808 N_MGR._paths_previously_scanned.clear()
2809 N_MGR._custom_module_map.clear()
2810
2811 notify_hook_d = notify_hook_c_base.join(".ignore.py")
2812 notify_hook_d.write("")
2813 notify_hook_e_base = notify_hook_c_base.mkdir(".ignore")
2814 notify_hook_e = notify_hook_e_base.join("__init__.py")
2815 notify_hook_e.write(
2816 cleandoc("""
2817 from apprise.decorators import notify
2818
2819 # this is a good hook but burried in hidden directory which won't
2820 # be accessed unless the file is pointed to via absolute path
2821 @notify(on="valid2")
2822 def mywrapper(body, title, notify_type, *args, **kwargs):
2823 pass
2824 """)
2825 )
2826
2827 # Try to load our base directory again; this time we search by the
2828 # directory; the only edge case we're testing here is it will not
2829 # even look at the .ignore.py file found since it is invalid
2830 N_MGR.module_detection([str(notify_hook_c_base)])
2831 assert "valid1" in N_MGR
2832 assert len(N_MGR._paths_previously_scanned) == 2
2833 assert len(N_MGR._custom_module_map) == 1
2834
2835 # Reset our variables for the next test
2836 del N_MGR._schema_map["valid1"]
2837 N_MGR._paths_previously_scanned.clear()
2838 N_MGR._custom_module_map.clear()
2839
2840 # Try to load our base directory again
2841 N_MGR.module_detection([str(notify_hook_c)])
2842 assert "valid1" in N_MGR
2843
2844 # Hidden directories are not scanned
2845 assert "valid2" not in N_MGR
2846
2847 assert len(N_MGR._paths_previously_scanned) == 1
2848 assert str(notify_hook_c) in N_MGR._paths_previously_scanned
2849 assert len(N_MGR._custom_module_map) == 1
2850
2851 # However a direct reference to the hidden directory is okay
2852 N_MGR.module_detection([str(notify_hook_e_base)])
2853
2854 # We loaded our module
2855 assert "valid2" in N_MGR
2856 assert len(N_MGR._paths_previously_scanned) == 3
2857 assert str(notify_hook_c) in N_MGR._paths_previously_scanned
2858 assert str(notify_hook_e) in N_MGR._paths_previously_scanned
2859 assert str(notify_hook_e_base) in N_MGR._paths_previously_scanned
2860 assert len(N_MGR._custom_module_map) == 2
2861
2862 # Reset our variables for the next test
2863 del N_MGR._schema_map["valid1"]
2864 del N_MGR._schema_map["valid2"]
2865 N_MGR._paths_previously_scanned.clear()
2866 N_MGR._custom_module_map.clear()
2867
2868 # Load our file directly
2869 assert "valid2" not in N_MGR
2870 N_MGR.module_detection([str(notify_hook_e)])
2871
2872 # Now we have it loaded as expected
2873 assert "valid2" in N_MGR
2874 assert len(N_MGR._paths_previously_scanned) == 1
2875 assert str(notify_hook_e) in N_MGR._paths_previously_scanned
2876 assert len(N_MGR._custom_module_map) == 1
2877
2878 # however if we try to load the base directory where the __init__.py
2879 # was already loaded from, it will not change anything
2880 N_MGR.module_detection([str(notify_hook_e_base)])
2881 assert "valid2" in N_MGR
2882 assert len(N_MGR._paths_previously_scanned) == 2
2883 assert str(notify_hook_e) in N_MGR._paths_previously_scanned
2884 assert str(notify_hook_e_base) in N_MGR._paths_previously_scanned
2885 assert len(N_MGR._custom_module_map) == 1
2886
2887 # Tidy up for the next test
2888 del N_MGR._schema_map["valid2"]
2889 N_MGR._paths_previously_scanned.clear()
2890 N_MGR._custom_module_map.clear()
2891
2892 assert "valid1" not in N_MGR
2893 assert "valid2" not in N_MGR
2894 assert "valid3" not in N_MGR
2895 notify_hook_f_base = tmpdir.mkdir("f")
2896 notify_hook_f = notify_hook_f_base.join("invalid.py")
2897 notify_hook_f.write(
2898 cleandoc("""
2899 from apprise.decorators import notify
2900
2901 # A very invalid hook type... on should not be None
2902 @notify(on=None)
2903 def mywrapper(body, title, notify_type, *args, **kwargs):
2904 pass
2905
2906 # An invalid name
2907 @notify(on='valid1', name=None)
2908 def mywrapper(body, title, notify_type, *args, **kwargs):
2909 pass
2910
2911 # Another invalid name (so it's ignored)
2912 @notify(on='valid2', name=object)
2913 def mywrapper(body, title, notify_type, *args, **kwargs):
2914 pass
2915
2916 # Simply put... the name has to be a string to be referenced
2917 # however this will still be loaded
2918 @notify(on='valid3', name=4)
2919 def mywrapper(body, title, notify_type, *args, **kwargs):
2920 pass
2921
2922 """)
2923 )
2924
2925 N_MGR.module_detection([str(notify_hook_f)])
2926
2927 assert len(N_MGR._paths_previously_scanned) == 1
2928 assert len(N_MGR._custom_module_map) == 1
2929 assert "valid1" in N_MGR
2930 assert "valid2" in N_MGR
2931 assert "valid3" in N_MGR
2932
2933 # Reset our variables for the next test
2934 del N_MGR._schema_map["valid1"]
2935 del N_MGR._schema_map["valid2"]
2936 del N_MGR._schema_map["valid3"]
2937 N_MGR._paths_previously_scanned.clear()
2938 N_MGR._custom_module_map.clear()
2939
2940 # Now test the handling of just bad data entirely
2941 notify_hook_g_base = tmpdir.mkdir("g")
2942 notify_hook_g = notify_hook_g_base.join("binary.py")
2943 with open(str(notify_hook_g), "wb") as fout:
2944 fout.write(os.urandom(512))
2945
2946 N_MGR.module_detection([str(notify_hook_g)])
2947 assert len(N_MGR._paths_previously_scanned) == 1
2948 assert len(N_MGR._custom_module_map) == 0
2949
2950 # Reset our variables before we leave
2951 N_MGR._paths_previously_scanned.clear()
2952 N_MGR._custom_module_map.clear()
2953
2954
2955 def test_exclusive_match():
2956 """utils: is_exclusive_match() testing"""
2957
2958 # No Logic always returns True if there is also no data
2959 assert utils.logic.is_exclusive_match(data=None, logic=None) is True
2960 assert utils.logic.is_exclusive_match(data=None, logic=set()) is True
2961 assert utils.logic.is_exclusive_match(data="", logic=set()) is True
2962 assert utils.logic.is_exclusive_match(data="", logic=set()) is True
2963
2964 # however, once data is introduced, True is no longer returned
2965 # if no logic has been specified
2966 assert utils.logic.is_exclusive_match(data="check", logic=set()) is False
2967 assert (
2968 utils.logic.is_exclusive_match(data=["check", "checkb"], logic=set())
2969 is False
2970 )
2971
2972 # String delimters are stripped out so that a list can be formed
2973 # the below is just an empty token list
2974 assert utils.logic.is_exclusive_match(data=set(), logic=",; ,") is True
2975
2976 # garbage logic is never an exclusive match
2977 assert utils.logic.is_exclusive_match(data=set(), logic=object()) is False
2978 assert (
2979 utils.logic.is_exclusive_match(
2980 data=set(),
2981 logic=[
2982 object(),
2983 ],
2984 )
2985 is False
2986 )
2987
2988 #
2989 # Test with logic:
2990 #
2991 data = {"abc"}
2992
2993 # def in data
2994 assert utils.logic.is_exclusive_match(logic="def", data=data) is False
2995 # def in data
2996 assert (
2997 utils.logic.is_exclusive_match(
2998 logic=[
2999 "def",
3000 ],
3001 data=data,
3002 )
3003 is False
3004 )
3005 # def in data
3006 assert utils.logic.is_exclusive_match(logic=("def",), data=data) is False
3007 # def in data
3008 assert (
3009 utils.logic.is_exclusive_match(
3010 logic={
3011 "def",
3012 },
3013 data=data,
3014 )
3015 is False
3016 )
3017 # abc in data
3018 assert (
3019 utils.logic.is_exclusive_match(
3020 logic=[
3021 "abc",
3022 ],
3023 data=data,
3024 )
3025 is True
3026 )
3027 # abc in data
3028 assert utils.logic.is_exclusive_match(logic=("abc",), data=data) is True
3029 # abc in data
3030 assert (
3031 utils.logic.is_exclusive_match(
3032 logic={
3033 "abc",
3034 },
3035 data=data,
3036 )
3037 is True
3038 )
3039 # abc or def in data
3040 assert utils.logic.is_exclusive_match(logic="abc, def", data=data) is True
3041
3042 #
3043 # Update our data set so we can do more advance checks
3044 #
3045 data = {"abc", "def", "efg", "xyz"}
3046
3047 # match_all matches everything
3048 assert utils.logic.is_exclusive_match(logic="all", data=data) is True
3049 assert utils.logic.is_exclusive_match(logic=["all"], data=data) is True
3050
3051 # def and abc in data
3052 assert (
3053 utils.logic.is_exclusive_match(logic=[("abc", "def")], data=data)
3054 is True
3055 )
3056
3057 # cba and abc in data
3058 assert (
3059 utils.logic.is_exclusive_match(logic=[("cba", "abc")], data=data)
3060 is False
3061 )
3062
3063 # www or zzz or abc and xyz
3064 assert (
3065 utils.logic.is_exclusive_match(
3066 logic=["www", "zzz", ("abc", "xyz")], data=data
3067 )
3068 is True
3069 )
3070 # www or zzz or abc and xyz (strings are valid too)
3071 assert (
3072 utils.logic.is_exclusive_match(
3073 logic=["www", "zzz", "abc, xyz"], data=data
3074 )
3075 is True
3076 )
3077
3078 # www or zzz or abc and jjj
3079 assert (
3080 utils.logic.is_exclusive_match(
3081 logic=["www", "zzz", ("abc", "jjj")], data=data
3082 )
3083 is False
3084 )
3085
3086 #
3087 # Empty data set
3088 #
3089 data = set()
3090 assert utils.logic.is_exclusive_match(logic=["www"], data=data) is False
3091 assert utils.logic.is_exclusive_match(logic="all", data=data) is True
3092
3093 #
3094 # Update our data set so we can do more advance checks
3095 #
3096 data = {"always", "entry1"}
3097 # We'll always match on the with keyword always
3098 assert utils.logic.is_exclusive_match(logic="always", data=data) is True
3099 assert utils.logic.is_exclusive_match(logic="garbage", data=data) is True
3100 # However we will not match if we turn this feature off
3101 assert (
3102 utils.logic.is_exclusive_match(
3103 logic="garbage", data=data, match_always=False
3104 )
3105 is False
3106 )
3107
3108 # Change default value from 'all' to 'match_me'. Logic matches
3109 # so we pass
3110 assert (
3111 utils.logic.is_exclusive_match(
3112 logic="match_me", data=data, match_all="match_me"
3113 )
3114 is True
3115 )
3116
3117
3118 def test_exclusive_match_priority_tokens():
3119 """utils: is_exclusive_match() with priority-prefixed filter tokens"""
3120
3121 # AppriseTag.__hash__ is name-only, so a set holds at most one entry per
3122 # tag name -- matching real usage where each URL has one priority.
3123 tag_ep3 = AppriseTag("endpoint", priority=3, has_priority=True)
3124 tag_other = AppriseTag("other", priority=1, has_priority=True)
3125
3126 data = {tag_ep3, tag_other}
3127
3128 # Exact priority match
3129 assert (
3130 utils.logic.is_exclusive_match(logic="3:endpoint", data=data) is True
3131 )
3132
3133 # Priority mismatch -- "2:endpoint" does not match priority-3 entry
3134 assert (
3135 utils.logic.is_exclusive_match(logic="2:endpoint", data=data) is False
3136 )
3137
3138 # Name-only filter matches via O(1) hash path regardless of stored priority
3139 assert utils.logic.is_exclusive_match(logic="endpoint", data=data) is True
3140
3141 # Absent tag returns False
3142 assert utils.logic.is_exclusive_match(logic="absent", data=data) is False
3143
3144 # AND group: both tokens present with correct priorities
3145 assert (
3146 utils.logic.is_exclusive_match(
3147 logic=[("3:endpoint", "1:other")], data=data
3148 )
3149 is True
3150 )
3151
3152 # AND group: one priority mismatch fails the whole group
3153 assert (
3154 utils.logic.is_exclusive_match(
3155 logic=[("2:endpoint", "1:other")], data=data
3156 )
3157 is False
3158 )
3159
3160 # OR: failing AND group rescued by a matching single token
3161 assert (
3162 utils.logic.is_exclusive_match(
3163 logic=[("2:endpoint", "1:other"), "3:endpoint"], data=data
3164 )
3165 is True
3166 )
3167
3168 # OR: no term matches -- all fail
3169 assert (
3170 utils.logic.is_exclusive_match(
3171 logic=[("2:endpoint", "1:other"), "99:endpoint"], data=data
3172 )
3173 is False
3174 )
3175
3176 # Backward compat: plain strings in data matched by a priority-prefixed
3177 # filter token (the for-loop fallback in _token_matches_data)
3178 str_data = {"endpoint", "other"}
3179 assert (
3180 utils.logic.is_exclusive_match(logic="7:endpoint", data=str_data)
3181 is True
3182 )
3183 assert (
3184 utils.logic.is_exclusive_match(logic="7:absent", data=str_data)
3185 is False
3186 )
3187
3188 # match_all keyword short-circuits even with priority data
3189 assert utils.logic.is_exclusive_match(logic="all", data=data) is True
3190
3191
3192 def test_apprise_validate_regex():
3193 """
3194 API: Apprise() Validate Regex tests
3195
3196 """
3197 assert utils.parse.validate_regex(None) is None
3198 assert utils.parse.validate_regex(object) is None
3199 assert utils.parse.validate_regex(42) is None
3200 assert utils.parse.validate_regex("") is None
3201 assert utils.parse.validate_regex(" ") is None
3202 assert utils.parse.validate_regex("abc") == "abc"
3203
3204 # value is a keyword that is extracted (if found)
3205 assert (
3206 utils.parse.validate_regex(
3207 "- abcd -", r"-(?P<value>[^-]+)-", fmt="{value}"
3208 )
3209 == "abcd"
3210 )
3211 assert (
3212 utils.parse.validate_regex(
3213 "- abcd -", r"-(?P<value>[^-]+)-", strip=False, fmt="{value}"
3214 )
3215 == " abcd "
3216 )
3217
3218 # String flags supported in addition to numeric
3219 assert (
3220 utils.parse.validate_regex(
3221 "- abcd -", r"-(?P<value>[^-]+)-", "i", fmt="{value}"
3222 )
3223 == "abcd"
3224 )
3225 assert (
3226 utils.parse.validate_regex(
3227 "- abcd -", r"-(?P<value>[^-]+)-", re.I, fmt="{value}"
3228 )
3229 == "abcd"
3230 )
3231
3232 # Test multiple flag settings
3233 assert (
3234 utils.parse.validate_regex(
3235 "- abcd -", r"-(?P<value>[^-]+)-", "isax", fmt="{value}"
3236 )
3237 == "abcd"
3238 )
3239
3240 # Invalid flags are just ignored. The below fails to match
3241 # because the default value of 'i' is over-ridden by what is
3242 # identfied below, and no flag is set at the end of the day
3243 assert (
3244 utils.parse.validate_regex(
3245 "- abcd -", r"-(?P<value>[ABCD]+)-", "-%2gb", fmt="{value}"
3246 )
3247 is None
3248 )
3249 assert (
3250 utils.parse.validate_regex(
3251 "- abcd -", r"-(?P<value>[ABCD]+)-", "", fmt="{value}"
3252 )
3253 is None
3254 )
3255 assert (
3256 utils.parse.validate_regex(
3257 "- abcd -", r"-(?P<value>[ABCD]+)-", None, fmt="{value}"
3258 )
3259 is None
3260 )
3261
3262
3263 def test_apply_templating():
3264 """utils: apply_template() testing"""
3265
3266 template = "Hello {{fname}}, How are you {{whence}}?"
3267
3268 result = utils.templates.apply_template(
3269 template, **{"fname": "Chris", "whence": "this morning"}
3270 )
3271 assert isinstance(result, str)
3272 assert result == "Hello Chris, How are you this morning?"
3273
3274 # In this example 'whence' isn't provided, so it isn't swapped
3275 result = utils.templates.apply_template(template, **{"fname": "Chris"})
3276 assert isinstance(result, str)
3277 assert result == "Hello Chris, How are you {{whence}}?"
3278
3279 # white space won't cause any ill affects:
3280 template = "Hello {{ fname }}, How are you {{ whence}}?"
3281 result = utils.templates.apply_template(
3282 template, **{"fname": "Chris", "whence": "this morning"}
3283 )
3284 assert isinstance(result, str)
3285 assert result == "Hello Chris, How are you this morning?"
3286
3287 # No arguments won't cause any problems
3288 template = "Hello {{fname}}, How are you {{whence}}?"
3289 result = utils.templates.apply_template(template)
3290 assert isinstance(result, str)
3291 assert result == template
3292
3293 # Wrong elements are simply ignored
3294 result = utils.templates.apply_template(
3295 template, **{"fname": "l2g", "whence": "this evening", "ignore": "me"}
3296 )
3297 assert isinstance(result, str)
3298 assert result == "Hello l2g, How are you this evening?"
3299
3300 # Empty template makes things easy
3301 result = utils.templates.apply_template(
3302 "", **{"fname": "l2g", "whence": "this evening"}
3303 )
3304 assert isinstance(result, str)
3305 assert result == ""
3306
3307 # Regular expressions are safely escapped and act as normal
3308 # tokens:
3309 template = "Hello {{.*}}, How are you {{[A-Z0-9]+}}?"
3310 result = utils.templates.apply_template(
3311 template, **{".*": "l2g", "[A-Z0-9]+": "this afternoon"}
3312 )
3313 assert result == "Hello l2g, How are you this afternoon?"
3314
3315 # JSON is handled too such as escaping quotes
3316 template = '{value: "{{ value }}"}'
3317 result = utils.templates.apply_template(
3318 template,
3319 app_mode=utils.templates.TemplateType.JSON,
3320 **{"value": '"quotes are escaped"'},
3321 )
3322 assert result == '{value: "\\"quotes are escaped\\""}'
3323
3324
3325 def test_cwe312_word():
3326 """utils: cwe312_word() testing"""
3327 assert utils.cwe312.cwe312_word(None) is None
3328 assert utils.cwe312.cwe312_word(42) == 42
3329 assert utils.cwe312.cwe312_word("") == ""
3330 assert utils.cwe312.cwe312_word(" ") == " "
3331 assert utils.cwe312.cwe312_word("!") == "!"
3332
3333 assert utils.cwe312.cwe312_word("a") == "a"
3334 assert utils.cwe312.cwe312_word("ab") == "ab"
3335 assert utils.cwe312.cwe312_word("abc") == "abc"
3336 assert utils.cwe312.cwe312_word("abcd") == "abcd"
3337 assert utils.cwe312.cwe312_word("abcd", force=True) == "a...d"
3338
3339 assert utils.cwe312.cwe312_word("abc--d") == "abc--d"
3340 assert utils.cwe312.cwe312_word("a-domain.ca") == "a...a"
3341
3342 # Variances to still catch domain
3343 assert (
3344 utils.cwe312.cwe312_word("a-domain.ca", advanced=False)
3345 == "a-domain.ca"
3346 )
3347 assert (
3348 utils.cwe312.cwe312_word("a-domain.ca", threshold=6) == "a-domain.ca"
3349 )
3350
3351
3352 def test_cwe312_url():
3353 """utils: cwe312_url() testing"""
3354 assert utils.cwe312.cwe312_url(None) is None
3355 assert utils.cwe312.cwe312_url(42) == 42
3356 assert utils.cwe312.cwe312_url("http://") == "http://"
3357 assert utils.cwe312.cwe312_url("discord://") == "discord://"
3358 assert utils.cwe312.cwe312_url("path") == "http://path"
3359 assert utils.cwe312.cwe312_url("path/") == "http://path/"
3360
3361 # Now test http:// private data
3362 assert (
3363 utils.cwe312.cwe312_url("http://user:pass123@localhost")
3364 == "http://user:p...3@localhost"
3365 )
3366 assert (
3367 utils.cwe312.cwe312_url("http://user@localhost")
3368 == "http://user@localhost"
3369 )
3370 assert (
3371 utils.cwe312.cwe312_url("http://user@localhost?password=abc123")
3372 == "http://user@localhost?password=a...3"
3373 )
3374 assert (
3375 utils.cwe312.cwe312_url("http://user@localhost?secret=secret-.12345")
3376 == "http://user@localhost?secret=s...5"
3377 )
3378
3379 assert (
3380 utils.cwe312.cwe312_url(
3381 "slack://mybot@xoxb-43598234231-3248932482278"
3382 "-BZK5Wj15B9mPh1RkShJoCZ44"
3383 "/[email protected]"
3384 )
3385 == "slack://[email protected]/l...m"
3386 )
3387 assert (
3388 utils.cwe312.cwe312_url(
3389 "slack://test@B4QP3WWB4/J3QWT41JM/XIl2ffpqXkzkwMXrJdevi7W3/#random"
3390 )
3391 == "slack://[email protected]/J...M/X...3/"
3392 )
3393
3394
3395 def test_base64_encode_decode():
3396 """Utils:Base64:URLEncode & Decode."""
3397 assert utils.base64.base64_urlencode(None) is None
3398 assert utils.base64.base64_urlencode(42) is None
3399 assert utils.base64.base64_urlencode(object) is None
3400 assert utils.base64.base64_urlencode({}) is None
3401 assert utils.base64.base64_urlencode("") is None
3402 assert utils.base64.base64_urlencode("abc") is None
3403 assert utils.base64.base64_urlencode(b"") == ""
3404 assert utils.base64.base64_urlencode(b"abc") == "YWJj"
3405
3406 assert utils.base64.base64_urldecode(None) is None
3407 assert utils.base64.base64_urldecode(42) is None
3408 assert utils.base64.base64_urldecode(object) is None
3409 assert utils.base64.base64_urldecode({}) is None
3410
3411 assert utils.base64.base64_urldecode("abc") == b"i\xb7"
3412 assert utils.base64.base64_urldecode("") == b""
3413 assert utils.base64.base64_urldecode("YWJj") == b"abc"
3414
3415
3416 def test_dict_base64_codec(tmpdir):
3417 """Test encoding/decoding of base64 content."""
3418 original = {
3419 "int": 1,
3420 "float": 2.3,
3421 }
3422
3423 encoded, needs_decoding = utils.base64.encode_b64_dict(original)
3424 assert encoded == {"int": "b64:MQ==", "float": "b64:Mi4z"}
3425 assert needs_decoding is True
3426 decoded = utils.base64.decode_b64_dict(encoded)
3427 assert decoded == original
3428
3429 with mock.patch("json.dumps", side_effect=TypeError()):
3430 encoded, needs_decoding = utils.base64.encode_b64_dict(original)
3431 # we failed
3432 assert needs_decoding is False
3433 assert encoded == {
3434 "int": "1",
3435 "float": "2.3",
3436 }
3437
3438
3439 def test_dir_size(tmpdir):
3440 """Test dir size tool."""
3441
3442 # Nothing to find/see
3443 size, errors = utils.disk.dir_size(str(tmpdir))
3444 assert size == 0
3445 assert len(errors) == 0
3446
3447 # Write a file in our root directory
3448 tmpdir.join("root.psdata").write("0" * 1024 * 1024)
3449
3450 # Prepare some more directories
3451 namespace_1 = tmpdir.mkdir("abcdefg")
3452 namespace_2 = tmpdir.mkdir("defghij")
3453 namespace_2.join("cache.psdata").write("0" * 1024 * 1024)
3454 size, errors = utils.disk.dir_size(str(tmpdir))
3455 assert size == 1024 * 1024 * 2
3456 assert len(errors) == 0
3457
3458 # Write another file
3459 namespace_1.join("cache.psdata").write("0" * 1024 * 1024)
3460 size, errors = utils.disk.dir_size(str(tmpdir))
3461 assert size == 1024 * 1024 * 3
3462 assert len(errors) == 0
3463
3464 size, errors = utils.disk.dir_size(str(namespace_1))
3465 assert size == 1024 * 1024
3466 assert len(errors) == 0
3467
3468 # Create a directory insde one of our namespaces
3469 subspace_1 = namespace_1.mkdir("zyx")
3470 size, errors = utils.disk.dir_size(str(namespace_1))
3471 assert size == 1024 * 1024
3472
3473 subspace_1.join("cache.psdata").write("0" * 1024 * 1024)
3474 size, errors = utils.disk.dir_size(str(tmpdir))
3475 assert size == 1024 * 1024 * 4
3476 assert len(errors) == 0
3477
3478 # Recursion limit reduced... no change at 2 as we can go 2
3479 # diretories deep no problem
3480 size, errors = utils.disk.dir_size(str(tmpdir), max_depth=2)
3481 assert size == 1024 * 1024 * 4
3482 assert len(errors) == 0
3483
3484 size, errors = utils.disk.dir_size(str(tmpdir), max_depth=1)
3485 assert size == 1024 * 1024 * 3
3486 # we can't get into our subspace_1
3487 assert len(errors) == 1
3488 assert str(subspace_1) in errors
3489
3490 size, errors = utils.disk.dir_size(str(tmpdir), max_depth=0)
3491 assert size == 1024 * 1024
3492 # we can't get into our namespace directories
3493 assert len(errors) == 2
3494 assert str(namespace_1) in errors
3495 assert str(namespace_2) in errors
3496
3497 # Let's cause problems now and test the output
3498 size, errors = utils.disk.dir_size("invalid-directory", missing_okay=True)
3499 assert size == 0
3500 assert len(errors) == 0
3501
3502 size, errors = utils.disk.dir_size("invalid-directory", missing_okay=False)
3503 assert size == 0
3504 assert len(errors) == 1
3505 assert "invalid-directory" in errors
3506
3507 with mock.patch("os.scandir", side_effect=OSError()):
3508 size, errors = utils.disk.dir_size(str(tmpdir), missing_okay=True)
3509 assert size == 0
3510 assert len(errors) == 1
3511 assert str(tmpdir) in errors
3512
3513 with mock.patch("os.scandir") as mock_scandir:
3514 mock_entry = mock.MagicMock()
3515 mock_entry.is_file.side_effect = OSError()
3516 mock_entry.path = "/test/path"
3517 # Mock the scandir return value to yield the mock entry
3518 mock_scandir.return_value.__enter__.return_value = [mock_entry]
3519
3520 size, errors = utils.disk.dir_size(str(tmpdir))
3521 assert size == 0
3522 assert len(errors) == 1
3523 assert mock_entry.path in errors
3524
3525 with mock.patch("os.scandir") as mock_scandir:
3526 mock_entry = mock.MagicMock()
3527 mock_entry.is_file.return_value = False
3528 mock_entry.is_dir.side_effect = OSError()
3529 mock_entry.path = "/test/path"
3530 # Mock the scandir return value to yield the mock entry
3531 mock_scandir.return_value.__enter__.return_value = [mock_entry]
3532 size, errors = utils.disk.dir_size(str(tmpdir))
3533 assert len(errors) == 1
3534 assert mock_entry.path in errors
3535
3536 with mock.patch("os.scandir") as mock_scandir:
3537 mock_entry = mock.MagicMock()
3538 mock_entry.is_file.return_value = False
3539 mock_entry.is_dir.return_value = False
3540 # Mock the scandir return value to yield the mock entry
3541 mock_scandir.return_value.__enter__.return_value = [mock_entry]
3542 size, errors = utils.disk.dir_size(str(tmpdir))
3543 assert size == 0
3544 assert len(errors) == 0
3545
3546 with mock.patch("os.scandir") as mock_scandir:
3547 mock_entry = mock.MagicMock()
3548 mock_entry.is_file.side_effect = FileNotFoundError()
3549 mock_entry.path = "/test/path"
3550 # Mock the scandir return value to yield the mock entry
3551 mock_scandir.return_value.__enter__.return_value = [mock_entry]
3552
3553 size, errors = utils.disk.dir_size(str(tmpdir))
3554 assert size == 0
3555 # No file isn't a problem, we're calculating disksize anyway,
3556 # one less thing to calculate
3557 assert len(errors) == 0
3558
3559
3560 def test_bytes_to_str():
3561 """Test Bytes to String representation."""
3562 # Garbage Entry
3563 assert utils.disk.bytes_to_str(None) is None
3564 assert utils.disk.bytes_to_str("") is None
3565 assert utils.disk.bytes_to_str("GARBAGE") is None
3566
3567 # Good Entries
3568 assert utils.disk.bytes_to_str(0) == "0.00B"
3569 assert utils.disk.bytes_to_str(1) == "1.00B"
3570 assert utils.disk.bytes_to_str(1.1) == "1.10B"
3571 assert utils.disk.bytes_to_str(1024) == "1.00KB"
3572 assert utils.disk.bytes_to_str(1024 * 1024) == "1.00MB"
3573 assert utils.disk.bytes_to_str(1024 * 1024 * 1024) == "1.00GB"
3574 assert utils.disk.bytes_to_str(1024 * 1024 * 1024 * 1024) == "1.00TB"
3575
3576 # Support strings too
3577 assert utils.disk.bytes_to_str("0") == "0.00B"
3578 assert utils.disk.bytes_to_str("1024") == "1.00KB"
3579
3580
3581 def test_time_zoneinfo():
3582 """utils: zoneinfo() testing"""
3583
3584 # Some valid strings
3585 assert isinstance(utils.time.zoneinfo("UTC"), tzinfo)
3586 assert isinstance(utils.time.zoneinfo("z"), tzinfo)
3587 assert isinstance(utils.time.zoneinfo("gmt"), tzinfo)
3588 assert isinstance(utils.time.zoneinfo("utc"), tzinfo)
3589 assert isinstance(utils.time.zoneinfo("Toronto"), tzinfo)
3590 assert isinstance(utils.time.zoneinfo("America/Toronto"), tzinfo)
3591 assert isinstance(utils.time.zoneinfo("america/toronto"), tzinfo)
3592
3593 # Edge Case with time also supported:
3594 tz = utils.time.zoneinfo("America/Argentina/Cordoba")
3595 isinstance(tz, tzinfo)
3596 assert isinstance(utils.time.zoneinfo("Argentina/Cordoba"), tzinfo)
3597 assert utils.time.zoneinfo("Argentina/Cordoba").key == tz.key
3598 # "America/Cordoba" has been obsoleted by IANA in facor of
3599 # "America/Argentina/Cordoba", however the IANA database
3600 # instance used is system-dependent, so these tests have
3601 # different results depending on the system running them
3602 if utils.time.zoneinfo("Cordoba") is not None:
3603 # the system has the obsolete "America/Cordoba" entry
3604 assert isinstance(utils.time.zoneinfo("Cordoba"), tzinfo)
3605 assert utils.time.zoneinfo("Cordoba").key == "America/Cordoba"
3606 else:
3607 assert utils.time.zoneinfo("Cordoba") is None
3608 # the utils helper should still resolve this abbreviated (and
3609 # lowercase) form
3610 assert (
3611 utils.time.zoneinfo("argentina/cordoba").key
3612 == "America/Argentina/Cordoba"
3613 )
3614
3615 # Too ambiguous
3616 assert utils.time.zoneinfo("Argentina") is None
3617
3618 # bad data
3619 assert utils.time.zoneinfo(object) is None
3620 assert utils.time.zoneinfo(None) is None
3621 assert utils.time.zoneinfo(1) is None
3622 assert utils.time.zoneinfo("") is None
3623 assert utils.time.zoneinfo("invalid") is None