Debian Codegraph @

tests/test_persistent_store.py

raw
1 # BSD 2-Clause License
2 #
3 # Apprise - Push Notification Library.
4 # Copyright (c) 2026, Chris Caron <[email protected]>
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright notice,
10 # this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright notice,
13 # this list of conditions and the following disclaimer in the documentation
14 # and/or other materials provided with the distribution.
15 #
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 # POSSIBILITY OF SUCH DAMAGE.
27
28 from datetime import datetime, timedelta, timezone
29 import gzip
30 import json
31
32 # Disable logging for a cleaner testing output
33 import logging
34 import os
35 import shutil
36 import sys
37 import tempfile
38 import time
39 from unittest import mock
40 import zlib
41
42 import pytest
43
44 from apprise import Apprise, exception
45 from apprise.asset import AppriseAsset
46 from apprise.persistent_store import (
47 CacheJSONEncoder,
48 CacheObject,
49 PersistentStore,
50 PersistentStoreMode,
51 )
52 from apprise.plugins.base import NotifyBase
53
54 logging.disable(logging.CRITICAL)
55
56 # Attachment Directory
57 TEST_VAR_DIR = os.path.join(os.path.dirname(__file__), "var")
58
59
60 # Keep the real close method so simulated failures do not leak file handles.
61 _real_ntf_close = tempfile._TemporaryFileWrapper.close
62
63
64 def _flaky_close(always=False):
65 """Mock close errors while still releasing the real file handle.
66
67 Raise on every call when ``always`` is true; otherwise, raise only once.
68 """
69 state = {"calls": 0}
70
71 def _close(self, *args, **kwargs):
72 # Perform the real close regardless of the simulated outcome
73 _real_ntf_close(self)
74 state["calls"] += 1
75 if always or state["calls"] == 1:
76 raise OSError()
77
78 return _close
79
80
81 def test_persistent_storage_asset(tmpdir):
82 """Tests the Apprise Asset Object when setting the Persistent Store."""
83
84 asset = AppriseAsset(storage_path=str(tmpdir))
85 assert asset.storage_path == str(tmpdir)
86 assert asset.storage_mode is PersistentStoreMode.AUTO
87
88 # If there is no storage path, we're always set to memory
89 asset = AppriseAsset(
90 storage_path=None, storage_mode=PersistentStoreMode.MEMORY
91 )
92 assert asset.storage_path is None
93 assert asset.storage_mode is PersistentStoreMode.MEMORY
94
95
96 def test_persistent_storage_bad_mode(tmpdir):
97 """Persistent Storage Bad Mode Testing."""
98 # Create ourselves an attachment object set in Memory Mode only
99 with pytest.raises(exception.AppriseImproperlyConfigured):
100 PersistentStore(namespace="abc", path=str(tmpdir), mode="invalid")
101
102 with pytest.raises(exception.AppriseImproperlyConfigured):
103 AppriseAsset(storage_mode="invalid")
104
105
106 def test_disabled_persistent_storage(tmpdir):
107 """Persistent Storage General Testing."""
108 # Create ourselves an attachment object set in Memory Mode only
109 pc = PersistentStore(
110 namespace="abc", path=str(tmpdir), mode=PersistentStoreMode.MEMORY
111 )
112 assert pc.read() is None
113 assert pc.read("mykey") is None
114 with pytest.raises(exception.AppriseImproperlyConfigured):
115 # Invalid key specified
116 pc.read("!invalid")
117 assert pc.write("data") is False
118 assert pc.get("key") is None
119 assert pc.set("key", "value")
120 assert pc.get("key") == "value"
121
122 assert pc.set("key2", "value")
123 pc.clear("key", "key-not-previously-set")
124 assert pc.get("key2") == "value"
125 assert pc.get("key") is None
126
127 # Set it again
128 assert pc.set("key", "another-value")
129 # Clears all
130 pc.clear()
131 assert pc.get("key2") is None
132 assert pc.get("key") is None
133 # A second call to clear on an already empty cache set
134 pc.clear()
135
136 # No dirty flag is set as ther is nothing to write to disk
137 pc.set("not-persistent", "value", persistent=False)
138 del pc["not-persistent"]
139 with pytest.raises(KeyError):
140 # Can't delete it twice
141 del pc["not-persistent"]
142
143 # A Persistent key
144 pc.set("persistent", "value")
145 # Removes it and sets/clears the dirty flag
146 del pc["persistent"]
147
148 # After all of the above, nothing was done to the directory
149 assert len(os.listdir(str(tmpdir))) == 0
150
151 with pytest.raises(exception.AppriseImproperlyConfigured):
152 # invalid persistent store specified
153 PersistentStore(namespace="abc", path=str(tmpdir), mode="garbage")
154
155
156 def test_persistent_storage_init(tmpdir):
157 """Test storage initialization."""
158 with pytest.raises(exception.AppriseImproperlyConfigured):
159 PersistentStore(namespace="", path=str(tmpdir))
160 with pytest.raises(exception.AppriseImproperlyConfigured):
161 PersistentStore(namespace=None, path=str(tmpdir))
162
163 with pytest.raises(exception.AppriseImproperlyConfigured):
164 PersistentStore(namespace="_", path=str(tmpdir))
165 with pytest.raises(exception.AppriseImproperlyConfigured):
166 PersistentStore(namespace=".", path=str(tmpdir))
167 with pytest.raises(exception.AppriseImproperlyConfigured):
168 PersistentStore(namespace="-", path=str(tmpdir))
169
170 with pytest.raises(exception.AppriseImproperlyConfigured):
171 PersistentStore(namespace="_abc", path=str(tmpdir))
172 with pytest.raises(exception.AppriseImproperlyConfigured):
173 PersistentStore(namespace=".abc", path=str(tmpdir))
174 with pytest.raises(exception.AppriseImproperlyConfigured):
175 PersistentStore(namespace="-abc", path=str(tmpdir))
176
177 with pytest.raises(exception.AppriseImproperlyConfigured):
178 PersistentStore(namespace="%", path=str(tmpdir))
179
180
181 def test_persistent_storage_general(tmpdir):
182 """Persistent Storage General Testing."""
183 namespace = "abc"
184 # Create ourselves an attachment object
185 pc = PersistentStore()
186
187 # Default mode when a path is not provided
188 assert pc.mode == PersistentStoreMode.MEMORY
189
190 assert pc.size() == 0
191 assert pc.files() == []
192 assert pc.files(exclude=True, lazy=False) == []
193 assert pc.files(exclude=False, lazy=False) == []
194 pc.set("key", "value")
195 # There is no disk size utilized
196 assert pc.size() == 0
197 assert pc.files(exclude=True, lazy=False) == []
198 assert pc.files(exclude=False, lazy=False) == []
199
200 # Create ourselves an attachment object
201 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
202
203 # Default mode when a path is provided
204 assert pc.mode == PersistentStoreMode.AUTO
205
206 # Get our path associated with our Persistent Store
207 assert pc.path == os.path.join(str(tmpdir), "abc")
208
209 # Expiry testing
210 assert pc.set("key", "value", datetime.now() + timedelta(hours=1))
211 # i min in the future
212 assert pc.set("key", "value", 60)
213
214 with pytest.raises(exception.AppriseImproperlyConfigured):
215 assert pc.set("key", "value", "invalid")
216
217 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
218
219 # Our key is still valid and we load it from disk
220 assert pc.get("key") == "value"
221 assert pc["key"] == "value"
222
223 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
224 assert pc.keys()
225 # Second call after already initialized skips over initialization
226 assert pc.keys()
227
228 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
229
230 with pytest.raises(KeyError):
231 # The below
232 pc["unassigned_key"]
233
234
235 def test_persistent_storage_auto_mode(tmpdir):
236 """Persistent Storage Auto Write Testing."""
237 namespace = "abc"
238 # Create ourselves an attachment object
239 pc = PersistentStore(
240 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.AUTO
241 )
242
243 pc.write(b"test")
244 with mock.patch("os.unlink", side_effect=FileNotFoundError()):
245 assert pc.delete(all=True) is True
246
247 # Create a temporary file we can delete
248 with open(os.path.join(pc.path, pc.temp_dir, "test.file"), "wb") as fd:
249 fd.write(b"data")
250
251 # Delete just the temporary files
252 assert pc.delete(temp=True) is True
253
254 # Delete just the temporary files
255 # Create a cache entry and delete it
256 assert pc.set("key", "value") is True
257 pc.write(b"test")
258 assert pc.delete(cache=True) is True
259 # Verify our data entry wasn't removed
260 assert pc.read() == b"test"
261 # But our cache was
262 assert pc.get("key") is None
263
264 # A reverse of the above... create a cache an data variable and
265 # Clear the data; make sure our cache is still there
266 assert pc.set("key", "value") is True
267 assert pc.write(b"test", key="iokey") is True
268 assert pc.delete("iokey") is True
269 assert pc.get("key") == "value"
270 assert pc.read("iokey") is None
271
272
273 def test_persistent_storage_flush_mode(tmpdir):
274 """Persistent Storage Forced Write Testing."""
275 namespace = "abc"
276 # Create ourselves an attachment object
277 pc = PersistentStore(
278 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
279 )
280
281 # Reference path
282 path = os.path.join(str(tmpdir), namespace)
283
284 assert pc.size() == 0
285 assert list(pc.files()) == []
286
287 # Key is not set yet
288 assert pc.get("key") is None
289 assert len(pc.keys()) == 0
290 assert "key" not in pc
291
292 # Verify our data is set
293 assert pc.set("key", "value")
294 assert len(pc.keys()) == 1
295 assert "key" in list(pc.keys())
296
297 assert pc.size() > 0
298 assert len(pc.files()) == 1
299
300 # Second call uses Lazy cache
301 # Just our cache file
302 assert len(pc.files()) == 1
303
304 # Setting the same value again uses a lazy mode and
305 # bypasses all of the write overhead
306 assert pc.set("key", "value")
307
308 path_content = os.listdir(path)
309 # var, cache.psdata, and tmp
310 assert len(path_content) == 3
311
312 # Assignments (causes another disk write)
313 pc["key"] = "value2"
314
315 # Setting the same value and explictly marking the field as not being
316 # perisistent
317 pc.set("key-xx", "abc123", persistent=False)
318 # Changing its value does not alter the persistent flag.
319 pc["key-xx"] = "def678"
320 # Setting it twice
321 pc["key-xx"] = "def678"
322
323 # Our retrievals
324 assert pc["key-xx"] == "def678"
325 assert pc.get("key-xx") == "def678"
326
327 # But on the destruction of our object, it is not available again
328 del pc
329 # Create ourselves an attachment object
330 pc = PersistentStore(
331 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
332 )
333
334 assert pc.get("key-xx") is None
335 with pytest.raises(KeyError):
336 pc["key-xx"]
337
338 # Now our key is set
339 assert "key" in pc
340 assert pc.get("key") == "value2"
341
342 # A directory was created identified by the namespace
343 assert len(os.listdir(str(tmpdir))) == 1
344 assert namespace in os.listdir(str(tmpdir))
345
346 path_content = os.listdir(path)
347 assert len(path_content) == 4
348
349 # Another write doesn't change the file count
350 pc["key"] = "value3"
351 path_content = os.listdir(path)
352 assert len(path_content) == 4
353
354 # Our temporary directory used for all file handling in this namespace
355 assert pc.temp_dir in path_content
356 # Our cache file
357 assert os.path.basename(pc.cache_file) in path_content
358
359 path = os.path.join(pc.path, pc.temp_dir)
360 path_content = os.listdir(path)
361
362 # We always do our best to clean any temporary files up
363 assert len(path_content) == 0
364
365 # Destroy our object
366 del pc
367
368 # Re-initialize it
369 pc = PersistentStore(
370 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
371 )
372
373 # Our key is persistent and available right away
374 assert pc.get("key") == "value3"
375 assert "key" in pc
376
377 # Remove our item
378 del pc["key"]
379 assert pc.size() == 0
380 assert "key" not in pc
381
382 assert pc.write("data") is True
383 assert pc.read() == b"data"
384 assert pc.write(b"data") is True
385 assert pc.read() == b"data"
386
387 assert pc.read("default") == b"data"
388 assert pc.write("data2", key="mykey") is True
389 assert pc.read("mykey") == b"data2"
390
391 # We can selectively delete our key
392 assert pc.delete("mykey")
393 assert pc.read("mykey") is None
394 # Other keys are not touched
395 assert pc.read("default") == b"data"
396 assert pc.read() == b"data"
397 # Full purge
398 assert pc.delete()
399 assert pc.read("mykey") is None
400 assert pc.read() is None
401
402 # Practice with files
403 with open(os.path.join(TEST_VAR_DIR, "apprise-test.gif"), "rb") as fd:
404 assert pc.write(fd, key="mykey", compress=False) is True
405
406 # Read our content back
407 fd.seek(0)
408 assert pc.read("mykey", compress=False) == fd.read()
409
410 with open(os.path.join(TEST_VAR_DIR, "apprise-test.gif"), "rb") as fd:
411 assert pc.write(fd, key="mykey", compress=True) is True
412
413 # Read our content back; content will be compressed
414 fd.seek(0)
415 assert pc.read("mykey", compress=True) == fd.read()
416
417 class Foobar:
418 def read(*args, **kwargs):
419 return 42
420
421 foobar = Foobar()
422 # read() returns a non string/bin
423 with pytest.raises(exception.AppriseDiskIOError):
424 pc.write(foobar, key="foobar", compress=True)
425 assert pc.read("foobar") is None
426
427 class Foobar:
428 def read(*args, **kwargs):
429 return "good"
430
431 foobar = Foobar()
432 # read() returns a string so the below write works
433 assert pc.write(foobar, key="foobar", compress=True)
434 assert pc.read("foobar") == b"good"
435 pc.delete()
436
437 class Foobar:
438 def read(*args, **kwargs):
439 # Throw an exception
440 raise TypeError()
441
442 foobar = Foobar()
443 # read() returns a non string/bin
444 with pytest.raises(exception.AppriseDiskIOError):
445 pc.write(foobar, key="foobar", compress=True)
446 assert pc.read("foobar") is None
447
448 # Set our max_file_size
449 prev_max_file_size = pc.max_file_size
450 pc.max_file_size = 1
451 assert pc.delete()
452
453 assert pc.write("data") is False
454 assert pc.read() is None
455
456 # Restore setting
457 pc.max_file_size = prev_max_file_size
458
459 # Reset
460 pc.delete()
461
462 assert pc.write("data")
463 # Corrupt our data
464 data = pc.read(compress=False)[:20] + pc.read(compress=False)[:10]
465 pc.write(data, compress=False)
466
467 # Now we'll get an exception reading back the corrupted data
468 assert pc.read() is None
469
470 # Keep in mind though the data is still there; operator should write
471 # and read the way they expect to and things will work out fine
472 # This test just proves that Apprise Peresistent storage still
473 # gracefully handles bad data
474 assert pc.read(compress=False) == data
475
476 # No key exists also returns None
477 assert pc.read("no-key-exists") is None
478
479 pc.write(b"test")
480 pc["key"] = "value"
481 with mock.patch("os.unlink", side_effect=FileNotFoundError()):
482 assert pc.delete(all=True) is True
483 with mock.patch("os.unlink", side_effect=OSError()):
484 assert pc.delete(all=True) is False
485
486 # Create a temporary file we can delete
487 tmp_file = os.path.join(pc.path, pc.temp_dir, "test.file")
488 with open(tmp_file, "wb") as fd:
489 fd.write(b"data")
490
491 assert pc.set("key", "value") is True
492 assert pc.write(b"test", key="iokey") is True
493 # Delete just the temporary files
494 assert pc.delete(temp=True) is True
495 assert os.path.exists(tmp_file) is False
496 # our other entries are untouched
497 assert pc.get("key") == "value"
498 assert pc.read("iokey") == b"test"
499
500 # Delete just the temporary files
501 # Create a cache entry and delete it
502 assert pc.set("key", "value") is True
503 assert pc.write(b"test") is True
504 assert pc.delete(cache=True) is True
505 # Verify our data entry wasn't removed
506 assert pc.read() == b"test"
507 # But our cache was
508 assert pc.get("key") is None
509
510 # A reverse of the above... create a cache an data variable and
511 # Clear the data; make sure our cache is still there
512 assert pc.set("key", "value") is True
513 assert pc.write(b"test", key="iokey") is True
514 assert pc.delete("iokey") is True
515 assert pc.get("key") == "value"
516 assert pc.read("iokey") is None
517
518 # Create some custom files
519 cust1_file = os.path.join(pc.path, "test.file")
520 cust2_file = os.path.join(pc.path, pc.data_dir, "test.file")
521 with open(cust1_file, "wb") as fd:
522 fd.write(b"data")
523 with open(cust2_file, "wb") as fd:
524 fd.write(b"data")
525
526 # Even after a full flush our files will exist
527 assert pc.delete()
528 assert os.path.exists(cust1_file) is True
529 assert os.path.exists(cust2_file) is True
530
531 # However, if we turn off validate, we do a full sweep because these
532 # unknown files are lingering in our directory space
533 assert pc.delete(validate=False)
534 assert os.path.exists(cust1_file) is False
535 assert os.path.exists(cust2_file) is False
536
537 pc["key"] = "value"
538 pc["key2"] = "value2"
539 assert "key" in pc
540 assert "key2" in pc
541 pc.clear("key")
542 assert "key" not in pc
543 assert "key2" in pc
544
545 # Set expired content
546 pc.set(
547 "expired",
548 "expired-content",
549 expires=datetime.now() - timedelta(days=1),
550 )
551
552 # The expired persistent entry still exists on disk.
553 # storage is behaving as it should
554 assert "expired" not in pc
555 assert pc.get("expired") is None
556 # Prune our content
557 pc.prune()
558
559
560 def test_persistent_storage_corruption_handling(tmpdir):
561 """Test corrupting handling of storage."""
562
563 # Namespace
564 namespace = "def456"
565
566 # Initialize it
567 pc = PersistentStore(
568 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
569 )
570
571 cache_file = pc.cache_file
572 assert not os.path.isfile(cache_file)
573
574 # Store our key
575 pc["mykey"] = 42
576 assert os.path.isfile(cache_file)
577
578 with gzip.open(cache_file, "rb") as f:
579 # Read our content from disk
580 json.loads(f.read().decode("utf-8"))
581
582 # Remove object
583 del pc
584
585 # Corrupt the file
586 with open(cache_file, "wb") as f:
587 f.write(b"{")
588
589 pc = PersistentStore(
590 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
591 )
592
593 # File is corrupted
594 assert "mykey" not in pc
595 pc["mykey"] = 42
596 del pc
597
598 # File is corrected now
599 pc = PersistentStore(
600 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
601 )
602
603 assert "mykey" in pc
604
605 # Corrupt the file again
606 with gzip.open(cache_file, "wb") as f:
607 # Bad JSON File
608 f.write(b"{")
609
610 pc = PersistentStore(
611 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
612 )
613
614 # File is corrupted
615 assert "mykey" not in pc
616 pc["mykey"] = 42
617 del pc
618
619 pc = PersistentStore(
620 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
621 )
622
623 # Test our force flush
624 assert pc.flush(force=True) is True
625 # double call
626 assert pc.flush(force=True) is True
627
628 # Zlib error handling as well during open
629 with (
630 mock.patch("gzip.open", side_effect=OSError()),
631 pytest.raises(KeyError),
632 ):
633 pc["mykey"] = 43
634
635 pc = PersistentStore(
636 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
637 )
638
639 # Zlib error handling as well during open
640 with mock.patch("gzip.open", side_effect=OSError()):
641 # No keys can be returned
642 assert not pc.keys()
643
644 pc = PersistentStore(
645 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
646 )
647
648 with (
649 mock.patch("json.loads", side_effect=TypeError()),
650 mock.patch("os.unlink", side_effect=FileNotFoundError()),
651 pytest.raises(KeyError),
652 ):
653 pc["mykey"] = 44
654
655 pc = PersistentStore(
656 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
657 )
658
659 with (
660 mock.patch("json.loads", side_effect=TypeError()),
661 mock.patch("os.unlink", side_effect=OSError()),
662 pytest.raises(KeyError),
663 ):
664 pc["mykey"] = 45
665
666 pc["my-new-key"] = 43
667 with mock.patch("gzip.open", side_effect=OSError()):
668 # We will fail to flush our content to disk
669 assert pc.flush(force=True) is False
670
671 with mock.patch("json.dumps", side_effect=TypeError()):
672 # We will fail to flush our content to disk
673 assert pc.flush(force=True) is False
674
675 with mock.patch("os.makedirs", side_effect=OSError()):
676 pc = PersistentStore(
677 namespace=namespace,
678 path=str(tmpdir),
679 mode=PersistentStoreMode.FLUSH,
680 )
681
682 # Directory initialization failed so we fall back to memory mode
683 assert pc.mode == PersistentStoreMode.MEMORY
684
685 # Handle file updates
686 pc = PersistentStore(
687 namespace="file-time-refresh",
688 path=str(tmpdir),
689 mode=PersistentStoreMode.AUTO,
690 )
691
692 pc["test"] = "abcd"
693 assert pc.write(b"data", key="abcd") is True
694 assert pc.read("abcd", expires=True) == b"data"
695 assert pc.write(b"data2", key="defg") is True
696 assert pc.read("defg", expires=False) == b"data2"
697 assert pc.write(b"data3", key="hijk") is True
698 assert pc.read("hijk", expires=False) == b"data3"
699 assert pc["test"] == "abcd"
700
701 with mock.patch("os.utime", side_effect=(OSError(), FileNotFoundError())):
702 pc.flush()
703
704 # directory initialization okay
705 pc = PersistentStore(
706 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
707 )
708
709 assert "mykey" not in pc
710 pc["mykey"] = 42
711 del pc
712
713 pc = PersistentStore(
714 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
715 )
716 assert "mykey" in pc
717
718 # Remove the last entry
719 del pc["mykey"]
720 with (
721 mock.patch("os.rename", side_effect=OSError()),
722 mock.patch("os.unlink", side_effect=OSError()),
723 ):
724 assert not pc.flush(force=True)
725
726 # Create another entry
727 pc["mykey"] = 42
728 with mock.patch("tempfile.NamedTemporaryFile", side_effect=OSError()):
729 assert not pc.flush(force=True)
730
731 # Temporary file cleanup failure
732 with mock.patch(
733 "tempfile._TemporaryFileWrapper.close", side_effect=OSError()
734 ):
735 assert not pc.flush(force=True)
736
737 # Create another entry
738 pc["mykey"] = 43
739 mock_ntf = mock.MagicMock()
740 mock_ntf.name = os.path.join(tmpdir, "file")
741
742 #
743 # Recursion loop checking
744 #
745 with mock.patch(
746 "tempfile.NamedTemporaryFile",
747 side_effect=[FileNotFoundError(), FileNotFoundError(), mock_ntf],
748 ):
749 # No way to have recursion loop
750 assert not pc.flush(force=True, _recovery=True)
751
752 with mock.patch(
753 "tempfile.NamedTemporaryFile",
754 side_effect=[FileNotFoundError(), FileNotFoundError(), mock_ntf],
755 ):
756 # No way to have recursion loop
757 assert not pc.flush(force=False, _recovery=True)
758
759 with mock.patch(
760 "tempfile.NamedTemporaryFile",
761 side_effect=[FileNotFoundError(), FileNotFoundError(), mock_ntf],
762 ):
763 # No way to have recursion loop
764 assert not pc.flush(force=False, _recovery=False)
765
766 with mock.patch(
767 "tempfile.NamedTemporaryFile",
768 side_effect=[FileNotFoundError(), FileNotFoundError(), mock_ntf],
769 ):
770 # No way to have recursion loop
771 assert not pc.flush(force=True, _recovery=False)
772
773 with (
774 mock.patch(
775 "tempfile._TemporaryFileWrapper.close",
776 autospec=True,
777 side_effect=_flaky_close(),
778 ),
779 mock.patch("os.unlink", side_effect=(OSError())),
780 ):
781 assert not pc.flush(force=True)
782
783 with mock.patch(
784 "tempfile._TemporaryFileWrapper.close",
785 autospec=True,
786 side_effect=_flaky_close(always=True),
787 ):
788 assert not pc.flush(force=True)
789
790 with (
791 mock.patch(
792 "tempfile._TemporaryFileWrapper.close",
793 autospec=True,
794 side_effect=_flaky_close(),
795 ),
796 mock.patch("os.unlink", side_effect=OSError()),
797 ):
798 assert not pc.flush(force=True)
799
800 with (
801 mock.patch(
802 "tempfile._TemporaryFileWrapper.close",
803 autospec=True,
804 side_effect=_flaky_close(),
805 ),
806 mock.patch("os.unlink", side_effect=FileNotFoundError()),
807 ):
808 assert not pc.flush(force=True)
809
810 del pc
811
812 # directory initialization okay
813 pc = PersistentStore(
814 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
815 )
816
817 # Allows us to play with encoding errors
818 pc.encoding = "ascii"
819
820 # Handle write() calls
821 with mock.patch("os.stat", side_effect=OSError()):
822 # We fail to fetch the filesize of our old file causing us to fail
823 assert pc.write("abcd") is False
824
825 # ボールト translates to vault (no bad word here) :)
826 data = "ボールト"
827
828 # We'll have encoding issues
829 assert pc.write(data) is False
830
831 with mock.patch("gzip.open", side_effect=FileNotFoundError()):
832 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
833
834 # recovery mode will kick in and even it will fail
835 assert pc.write(b"key") is False
836
837 with mock.patch("gzip.open", side_effect=OSError()):
838 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
839
840 # Falls to default
841 assert pc.get("key") is None
842
843 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
844 with pytest.raises(KeyError):
845 pc["key"] = "value"
846
847 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
848 with pytest.raises(KeyError):
849 pc["key"]
850
851 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
852 with pytest.raises(KeyError):
853 del pc["key"]
854
855 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
856 # Fails to set key
857 assert pc.set("key", "value") is False
858
859 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
860 # Fails to clear
861 assert pc.clear() is False
862
863 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
864 # Fails to prune
865 assert pc.prune() is False
866
867 # Set some expired content
868 pc.set(
869 "key",
870 "value",
871 persistent=False,
872 expires=datetime.now() - timedelta(days=1),
873 )
874 pc.set(
875 "key2",
876 "value2",
877 persistent=True,
878 expires=datetime.now() - timedelta(days=1),
879 )
880
881 # Set some un-expired content
882 pc.set("key3", "value3", persistent=True)
883 pc.set("key4", "value4", persistent=False)
884 assert pc.prune() is True
885
886 # Second call has no change made
887 assert pc.prune() is False
888
889 # Reset
890 pc.delete()
891
892 # directory initialization okay
893 pc = PersistentStore(
894 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
895 )
896
897 # Write some content that expires almost immediately
898 pc.set(
899 "key1",
900 "value",
901 persistent=True,
902 expires=datetime.now() + timedelta(seconds=1),
903 )
904 pc.set(
905 "key2",
906 "value",
907 persistent=True,
908 expires=datetime.now() + timedelta(seconds=1),
909 )
910 pc.set(
911 "key3",
912 "value",
913 persistent=True,
914 expires=datetime.now() + timedelta(seconds=1),
915 )
916 pc.flush()
917
918 # Wait out our expiry
919 time.sleep(1.3)
920
921 # now initialize our storage again
922 pc = PersistentStore(
923 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
924 )
925
926 # This triggers our __load_cache() which reads in a value
927 # determined to have already been expired
928 assert "key1" not in pc
929 assert "key2" not in pc
930 assert "key3" not in pc
931
932 # Sweep
933 pc.delete()
934 pc.set("key", "value")
935 pc.set("key2", "value2")
936 pc.write("more-content")
937 # Flush our content to disk
938 pc.flush()
939
940 # Ideally we'd use os.stat below, but it is called inside a list
941 # comprehension block and mock doesn't appear to throw the exception
942 # there. So this is a bit of a cheat, but it works
943 with mock.patch("builtins.sum", side_effect=OSError()):
944 assert pc.size(exclude=True, lazy=False) == 0
945 assert pc.size(exclude=False, lazy=False) == 0
946
947 pc = PersistentStore(namespace=namespace, path=str(tmpdir))
948 with mock.patch("glob.glob", side_effect=OSError()):
949 assert pc.files(exclude=True, lazy=False) == []
950 assert pc.files(exclude=False, lazy=False) == []
951
952 pc = PersistentStore(
953 namespace=namespace, path=str(tmpdir), mode=PersistentStoreMode.FLUSH
954 )
955
956 # Causes an initialization
957 pc["abc"] = 1
958 with mock.patch("os.unlink", side_effect=OSError()):
959 # Now we can't set data
960 with pytest.raises(KeyError):
961 pc["new-key"] = "value"
962 # However keys that alrady exist don't get caught in check
963 # and therefore won't throw
964 pc["abc"] = "value"
965
966 #
967 # Handles flush() when the queue is empty
968 #
969 pc.clear()
970 with mock.patch("os.unlink", side_effect=OSError()):
971 # We can't remove backup cache file
972 assert pc.flush(force=True) is False
973
974 with mock.patch("os.unlink", side_effect=FileNotFoundError()):
975 # FileNotFound is not an issue
976 assert pc.flush(force=True) is True
977
978 with mock.patch("os.rename", side_effect=OSError()):
979 # We can't create a backup
980 assert pc.flush(force=True) is False
981
982 with mock.patch("os.rename", side_effect=FileNotFoundError()):
983 # FileNotFound is not an issue
984 assert pc.flush(force=True) is True
985
986 # Flush any previous cache and data
987 pc.delete()
988
989 #
990 # Handles flush() cases where is data to write
991 #
992
993 # Create a key
994 pc.set("abc", "a-test-value")
995 with mock.patch("os.unlink", side_effect=(OSError(), None)):
996 # We failed to move our content in place
997 assert pc.flush(force=True) is False
998
999 with mock.patch("os.unlink", side_effect=(OSError(), FileNotFoundError())):
1000 # We failed to move our content in place
1001 assert pc.flush(force=True) is False
1002
1003 with mock.patch("os.unlink", side_effect=(OSError(), OSError())):
1004 # We failed to move our content in place
1005 assert pc.flush(force=True) is False
1006
1007
1008 def test_persistent_custom_io(tmpdir):
1009 """Test reading and writing custom files."""
1010
1011 # Initialize it for memory only
1012 pc = PersistentStore(path=str(tmpdir))
1013
1014 with pytest.raises(exception.AppriseImproperlyConfigured):
1015 pc.open("!invalid#-Key")
1016
1017 # We can't open the file as it does not exist
1018 with pytest.raises(FileNotFoundError):
1019 pc.open("valid-key")
1020
1021 with pytest.raises(exception.AppriseImproperlyConfigured):
1022 # Bad data
1023 pc.open(1234)
1024
1025 with pytest.raises(FileNotFoundError), pc.open("key") as fd:
1026 pass
1027
1028 # Also can be caught using Apprise Exception Handling
1029 with pytest.raises(exception.AppriseFileNotFound), pc.open("key") as fd:
1030 pass
1031
1032 # Write some valid data
1033 with pc.open("new-key", "wb") as fd:
1034 fd.write(b"data")
1035
1036 with mock.patch(
1037 "builtins.open",
1038 new_callable=mock.mock_open,
1039 read_data="mocked file content",
1040 ) as mock_file:
1041 mock_file.side_effect = OSError
1042 with (
1043 pytest.raises(exception.AppriseDiskIOError),
1044 pc.open("new-key", compress=True) as fd,
1045 ):
1046 pass
1047
1048 # Again but with compression this time
1049 with mock.patch(
1050 "gzip.open",
1051 new_callable=mock.mock_open,
1052 read_data="mocked file content",
1053 ) as mock_file:
1054 mock_file.side_effect = OSError
1055 with (
1056 pytest.raises(exception.AppriseDiskIOError),
1057 pc.open("new-key", compress=True) as fd,
1058 ):
1059 pass
1060
1061 # Zlib error handling as well during open
1062 with mock.patch(
1063 "gzip.open",
1064 new_callable=mock.mock_open,
1065 read_data="mocked file content",
1066 ) as mock_file:
1067 mock_file.side_effect = zlib.error
1068 with (
1069 pytest.raises(exception.AppriseDiskIOError),
1070 pc.open("new-key", compress=True) as fd,
1071 ):
1072 pass
1073
1074 # Writing
1075 with pytest.raises(exception.AppriseImproperlyConfigured):
1076 pc.write(1234)
1077
1078 with pytest.raises(exception.AppriseImproperlyConfigured):
1079 pc.write(None)
1080
1081 with pytest.raises(exception.AppriseImproperlyConfigured):
1082 pc.write(True)
1083
1084 pc = PersistentStore(str(tmpdir))
1085 with pc.open("key", "wb") as fd:
1086 fd.write(b"test")
1087 fd.close()
1088
1089 # Handle error capuring when failing to write to disk
1090 with mock.patch(
1091 "gzip.open",
1092 new_callable=mock.mock_open,
1093 read_data="mocked file content",
1094 ) as mock_file:
1095 mock_file.side_effect = zlib.error
1096
1097 # We fail to write to disk
1098 assert pc.write(b"test") is False
1099
1100 # We support other errors too
1101 mock_file.side_effect = OSError
1102 assert pc.write(b"test") is False
1103
1104 with pytest.raises(exception.AppriseImproperlyConfigured):
1105 pc.write(b"data", key="!invalid#-Key")
1106
1107 pc.delete()
1108 with mock.patch("os.unlink", side_effect=OSError()):
1109 # Write our data and the __move() will fail under the hood
1110 assert pc.write(b"test") is False
1111
1112 pc.delete()
1113 with mock.patch("os.rename", side_effect=OSError()):
1114 # Write our data and the __move() will fail under the hood
1115 assert pc.write(b"test") is False
1116
1117 pc.delete()
1118 with mock.patch("os.unlink", side_effect=(OSError(), FileNotFoundError())):
1119 # Write our data and the __move() will fail under the hood
1120 assert pc.write(b"test") is False
1121
1122 pc.delete()
1123 with mock.patch("os.unlink", side_effect=(OSError(), None)):
1124 # Write our data and the __move() will fail under the hood
1125 assert pc.write(b"test") is False
1126
1127 pc.delete()
1128 with mock.patch("os.unlink", side_effect=(OSError(), OSError())):
1129 # Write our data and the __move() will fail under the hood
1130 assert pc.write(b"test") is False
1131
1132 pc.delete()
1133 with mock.patch("os.rename", side_effect=(None, OSError(), None)):
1134 assert pc.write(b"test") is False
1135
1136 with mock.patch("os.rename", side_effect=(None, OSError(), OSError())):
1137 assert pc.write(b"test") is False
1138
1139 with mock.patch(
1140 "os.rename", side_effect=(None, OSError(), FileNotFoundError())
1141 ):
1142 assert pc.write(b"test") is False
1143
1144 pc.delete()
1145 with mock.patch("os.rename", side_effect=(None, None, None, OSError())):
1146 # not enough reason to fail
1147 assert pc.write(b"test") is True
1148
1149 with (
1150 mock.patch("os.stat", side_effect=OSError()),
1151 mock.patch("os.close", side_effect=(None, OSError())),
1152 ):
1153 assert pc.write(b"test") is False
1154
1155 pc.delete()
1156 with mock.patch(
1157 "tempfile._TemporaryFileWrapper.close",
1158 autospec=True,
1159 side_effect=_flaky_close(always=True),
1160 ):
1161 assert pc.write(b"test") is False
1162
1163 pc.delete()
1164 with (
1165 mock.patch(
1166 "tempfile._TemporaryFileWrapper.close",
1167 autospec=True,
1168 side_effect=_flaky_close(),
1169 ),
1170 mock.patch("os.unlink", side_effect=OSError()),
1171 ):
1172 assert pc.write(b"test") is False
1173
1174 pc.delete()
1175 with (
1176 mock.patch(
1177 "tempfile._TemporaryFileWrapper.close",
1178 autospec=True,
1179 side_effect=_flaky_close(),
1180 ),
1181 mock.patch("os.unlink", side_effect=FileNotFoundError()),
1182 ):
1183 assert pc.write(b"test") is False
1184
1185
1186 def test_persistent_memory_open_uses_apprise_exception(tmpdir):
1187 """Opening memory-only storage raises the compatible Apprise error."""
1188 store = PersistentStore(
1189 path=str(tmpdir),
1190 mode=PersistentStoreMode.MEMORY,
1191 )
1192
1193 with pytest.raises(exception.AppriseFileNotFound) as error:
1194 store.open("key")
1195
1196 assert isinstance(error.value, FileNotFoundError)
1197
1198
1199 def test_persistent_storage_cache_object(tmpdir):
1200 """General testing of a CacheObject."""
1201 # A cache object
1202 c = CacheObject(123)
1203
1204 ref = datetime.now(tz=timezone.utc)
1205 expires = ref + timedelta(days=1)
1206 # Create a cache object that expires tomorrow
1207 c = CacheObject("abcd", expires=expires)
1208 assert c.expires == expires
1209 assert c.expires_sec > 86390.0 and c.expires_sec <= 86400.0
1210 assert bool(c) is True
1211 assert "never" not in str(c)
1212 assert "str:+:abcd" in str(c)
1213
1214 #
1215 # Testing CacheObject.set()
1216 #
1217 c.set(123)
1218 assert "never" not in str(c)
1219 assert "int:+:123" in str(c)
1220 hash_value = c.hash()
1221 assert isinstance(hash_value, str)
1222
1223 c.set(124)
1224 assert "never" not in str(c)
1225 assert "int:+:124" in str(c)
1226 assert c.hash() != hash_value
1227
1228 c.set(123)
1229 # sha is the same again if we set the value back
1230 assert c.hash() == hash_value
1231
1232 c.set(124)
1233 assert isinstance(c.hash(), str)
1234 assert c.value == 124
1235 assert bool(c) is True
1236 c.set(124, expires=False, persistent=False)
1237 assert bool(c) is True
1238 assert c.expires is None
1239 assert c.expires_sec is None
1240 c.set(124, expires=True)
1241 # we're expired now
1242 assert bool(c) is False
1243
1244 #
1245 # Testing CacheObject equality (==)
1246 #
1247 a = CacheObject("abc")
1248 b = CacheObject("abc")
1249
1250 assert a == b
1251 assert a == "abc"
1252 assert b == "abc"
1253
1254 # Equality is no longer a thing
1255 b = CacheObject("abc", 30)
1256 assert a != b
1257 # however we can look at the value inside
1258 assert a == b.value
1259
1260 b = CacheObject("abc", persistent=False)
1261 a = CacheObject("abc", persistent=True)
1262 # Persistent flag matters
1263 assert a != b
1264 # however we can look at the value inside
1265 assert a == b.value
1266 b = CacheObject("abc", persistent=True)
1267 assert a == b
1268
1269 # Epoch
1270 EPOCH = datetime(1970, 1, 1)
1271
1272 # test all of our supported types (also test time naive and aware times)
1273 for entry in (
1274 "string",
1275 123,
1276 1.2222,
1277 datetime.now(),
1278 datetime.now(tz=timezone.utc),
1279 None,
1280 False,
1281 True,
1282 b"\0",
1283 ):
1284 # Create a cache object that expires tomorrow
1285 c = CacheObject(entry, datetime.now() + timedelta(days=1))
1286
1287 # Verify our content hasn't expired
1288 assert c
1289
1290 # Verify we can dump our object
1291 result = json.loads(
1292 json.dumps(c, separators=(",", ":"), cls=CacheJSONEncoder)
1293 )
1294
1295 # Instantiate our object
1296 cc = CacheObject.instantiate(result)
1297 assert cc.json() == c.json()
1298
1299 # Test our JSON Encoder against items we don't support
1300 with pytest.raises(TypeError):
1301 json.loads(
1302 json.dumps(object(), separators=(",", ":"), cls=CacheJSONEncoder)
1303 )
1304
1305 assert CacheObject.instantiate(None) is None
1306 assert CacheObject.instantiate({}) is None
1307
1308 # Bad data
1309 assert (
1310 CacheObject.instantiate({"v": 123, "x": datetime.now(), "c": "int"})
1311 is None
1312 )
1313
1314 # object type is not supported
1315 assert (
1316 CacheObject.instantiate(
1317 {
1318 "v": 123,
1319 "x": (datetime.now() - EPOCH).total_seconds(),
1320 "c": object,
1321 }
1322 )
1323 is None
1324 )
1325
1326 obj = CacheObject.instantiate(
1327 {"v": 123, "x": (datetime.now() - EPOCH).total_seconds(), "c": "int"},
1328 verify=False,
1329 )
1330 assert isinstance(obj, CacheObject)
1331 assert obj.value == 123
1332
1333 # no HASH and verify is set to true; our checksum will fail
1334 assert (
1335 CacheObject.instantiate(
1336 {
1337 "v": 123,
1338 "x": (datetime.now() - EPOCH).total_seconds(),
1339 "c": "int",
1340 },
1341 verify=True,
1342 )
1343 is None
1344 )
1345
1346 # We can't instantiate our object if the expiry value is bad
1347 assert (
1348 CacheObject.instantiate(
1349 {"v": 123, "x": "garbage", "c": "int"}, verify=False
1350 )
1351 is None
1352 )
1353
1354 # We need a valid hash sum too
1355 assert (
1356 CacheObject.instantiate(
1357 {
1358 "v": 123,
1359 "x": (datetime.now() - EPOCH).total_seconds(),
1360 "c": "int",
1361 # Expecting a valid sha string
1362 "!": 1.0,
1363 },
1364 verify=False,
1365 )
1366 is None
1367 )
1368
1369 # Our Bytes Object with corruption
1370 assert (
1371 CacheObject.instantiate(
1372 {
1373 "v": "garbage",
1374 "x": (datetime.now() - EPOCH).total_seconds(),
1375 "c": "bytes",
1376 },
1377 verify=False,
1378 )
1379 is None
1380 )
1381
1382 obj = CacheObject.instantiate(
1383 {
1384 "v": "AA==",
1385 "x": (datetime.now() - EPOCH).total_seconds(),
1386 "c": "bytes",
1387 },
1388 verify=False,
1389 )
1390 assert isinstance(obj, CacheObject)
1391 assert obj.value == b"\0"
1392
1393 # Test our datetime objects
1394 obj = CacheObject.instantiate(
1395 {
1396 "v": "2024-06-08T01:50:01.587267",
1397 "x": (datetime.now() - EPOCH).total_seconds(),
1398 "c": "datetime",
1399 },
1400 verify=False,
1401 )
1402 assert isinstance(obj, CacheObject)
1403 assert obj.value == datetime(2024, 6, 8, 1, 50, 1, 587267)
1404
1405 # A corrupt datetime object
1406 assert (
1407 CacheObject.instantiate(
1408 {
1409 "v": "garbage",
1410 "x": (datetime.now() - EPOCH).total_seconds(),
1411 "c": "datetime",
1412 },
1413 verify=False,
1414 )
1415 is None
1416 )
1417
1418
1419 @pytest.mark.skipif(
1420 sys.platform == "win32", reason="Unreliable results to be determined"
1421 )
1422 def test_persistent_storage_disk_prune(tmpdir):
1423 """General testing of a Persistent Store prune calls."""
1424
1425 # Persistent Storage Initialization
1426 pc = PersistentStore(
1427 path=str(tmpdir), namespace="t01", mode=PersistentStoreMode.FLUSH
1428 )
1429 # Store some data
1430 assert pc.write(b"data-t01") is True
1431 assert pc.set("key-t01", "value")
1432
1433 pc = PersistentStore(
1434 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1435 )
1436 # Store some data
1437 assert pc.write(b"data-t02") is True
1438 assert pc.set("key-t02", "value")
1439
1440 # purne anything older then 30s
1441 results = PersistentStore.disk_prune(path=str(tmpdir), expires=30)
1442 # Nothing is older then 30s right now
1443 assert isinstance(results, dict)
1444 assert "t01" in results
1445 assert "t02" in results
1446 assert len(results["t01"]) == 0
1447 assert len(results["t02"]) == 0
1448
1449 pc = PersistentStore(
1450 path=str(tmpdir), namespace="t01", mode=PersistentStoreMode.FLUSH
1451 )
1452
1453 # Nothing is pruned
1454 assert pc.get("key-t01") == "value"
1455 assert pc.read() == b"data-t01"
1456
1457 # An expiry of zero gets everything
1458 # Note: This test randomly fails in Microsoft Windows for unknown reasons
1459 # When this is determined, this test can be opened back up
1460 results = PersistentStore.disk_prune(path=str(tmpdir), expires=0)
1461 # We match everything now
1462 assert isinstance(results, dict)
1463 assert "t01" in results
1464 assert "t02" in results
1465 assert len(results["t01"]) == 2
1466 assert len(results["t02"]) == 2
1467
1468 # Content is still not removed however because no action was put in place
1469 pc = PersistentStore(
1470 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1471 )
1472 # Nothing is pruned
1473 assert pc.get("key-t02") == "value"
1474 assert pc.read() == b"data-t02"
1475 pc = PersistentStore(
1476 path=str(tmpdir), namespace="t01", mode=PersistentStoreMode.FLUSH
1477 )
1478 # Nothing is pruned
1479 assert pc.get("key-t01") == "value"
1480 assert pc.read() == b"data-t01"
1481
1482 with mock.patch("os.listdir", side_effect=OSError()):
1483 results = PersistentStore.disk_scan(
1484 namespace="t01", path=str(tmpdir), closest=True
1485 )
1486 assert isinstance(results, list)
1487 assert len(results) == 0
1488
1489 with mock.patch("os.listdir", side_effect=FileNotFoundError()):
1490 results = PersistentStore.disk_scan(
1491 namespace="t01", path=str(tmpdir), closest=True
1492 )
1493 assert isinstance(results, list)
1494 assert len(results) == 0
1495
1496 # Without closest flag
1497 results = PersistentStore.disk_scan(
1498 namespace="t01", path=str(tmpdir), closest=False
1499 )
1500 assert isinstance(results, list)
1501 assert len(results) == 0
1502
1503 # Now we'll filter on specific namespaces
1504 results = PersistentStore.disk_prune(
1505 namespace="notfound", path=str(tmpdir), expires=0, action=True
1506 )
1507
1508 # nothing matched, nothing found
1509 assert isinstance(results, dict)
1510 assert len(results) == 0
1511
1512 results = PersistentStore.disk_prune(
1513 namespace=("t01", "invalid", "-garbag!"),
1514 path=str(tmpdir),
1515 expires=0,
1516 action=True,
1517 )
1518
1519 # only t01 would be cleaned now
1520 assert isinstance(results, dict)
1521 assert len(results) == 1
1522 assert len(results["t01"]) == 2
1523
1524 # A second call will yield no results because the content has
1525 # already been cleaned up
1526 results = PersistentStore.disk_prune(
1527 namespace="t01", path=str(tmpdir), expires=0, action=True
1528 )
1529 assert isinstance(results, dict)
1530 assert len(results) == 0
1531
1532 # t02 is still untouched
1533 pc = PersistentStore(
1534 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1535 )
1536 # Nothing is pruned
1537 assert pc.get("key-t02") == "value"
1538 assert pc.read() == b"data-t02"
1539
1540 # t01 of course... it's gone
1541 pc = PersistentStore(
1542 path=str(tmpdir), namespace="t01", mode=PersistentStoreMode.FLUSH
1543 )
1544 # Nothing is pruned
1545 assert pc.get("key-t01") is None
1546 assert pc.read() is None
1547
1548 with pytest.raises(exception.AppriseImproperlyConfigured):
1549 # provide garbage in namespace field and we're going to have a problem
1550 PersistentStore.disk_prune(
1551 namespace=object, path=str(tmpdir), expires=0, action=True
1552 )
1553
1554 # Error Handling
1555 with mock.patch("os.path.getmtime", side_effect=FileNotFoundError()):
1556 results = PersistentStore.disk_prune(
1557 namespace="t02", path=str(tmpdir), expires=0, action=True
1558 )
1559 assert isinstance(results, dict)
1560 assert len(results) == 1
1561 assert len(results["t02"]) == 0
1562
1563 # no files were removed, so our data is still accessible
1564 pc = PersistentStore(
1565 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1566 )
1567 # Nothing is pruned
1568 assert pc.get("key-t02") == "value"
1569 assert pc.read() == b"data-t02"
1570
1571 with mock.patch("os.path.getmtime", side_effect=OSError()):
1572 results = PersistentStore.disk_prune(
1573 namespace="t02", path=str(tmpdir), expires=0, action=True
1574 )
1575 assert isinstance(results, dict)
1576 assert len(results) == 1
1577 assert len(results["t02"]) == 0
1578
1579 # no files were removed, so our data is still accessible
1580 pc = PersistentStore(
1581 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1582 )
1583 # Nothing is pruned
1584 assert pc.get("key-t02") == "value"
1585 assert pc.read() == b"data-t02"
1586
1587 with mock.patch("os.unlink", side_effect=FileNotFoundError()):
1588 results = PersistentStore.disk_prune(
1589 namespace="t02", path=str(tmpdir), expires=0, action=True
1590 )
1591 assert isinstance(results, dict)
1592 assert len(results) == 1
1593 assert len(results["t02"]) == 2
1594
1595 # no files were removed, so our data is still accessible
1596 pc = PersistentStore(
1597 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1598 )
1599 # Nothing is pruned
1600 assert pc.get("key-t02") == "value"
1601 assert pc.read() == b"data-t02"
1602
1603 with mock.patch("os.unlink", side_effect=OSError()):
1604 results = PersistentStore.disk_prune(
1605 namespace="t02", path=str(tmpdir), expires=0, action=True
1606 )
1607 assert isinstance(results, dict)
1608 assert len(results) == 1
1609 assert len(results["t02"]) == 2
1610
1611 # no files were removed, so our data is still accessible
1612 pc = PersistentStore(
1613 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1614 )
1615 # Nothing is pruned
1616 assert pc.get("key-t02") == "value"
1617 assert pc.read() == b"data-t02"
1618
1619 with mock.patch("os.rmdir", side_effect=OSError()):
1620 results = PersistentStore.disk_prune(
1621 namespace="t02", path=str(tmpdir), expires=0, action=True
1622 )
1623 assert isinstance(results, dict)
1624 assert len(results) == 1
1625 assert len(results["t02"]) == 2
1626
1627 # no files were removed, so our data is still accessible
1628 pc = PersistentStore(
1629 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1630 )
1631 # Nothing is pruned
1632 assert pc.get("key-t02") is None
1633 assert pc.read() is None
1634
1635
1636 def test_persistent_storage_disk_changes(tmpdir):
1637 """General testing of a Persistent Store with underlining disk changes."""
1638
1639 # Create a garbage file in place of where the namespace should be
1640 tmpdir.join("t01").write("0" * 1024)
1641
1642 # Persistent Storage Initialization where namespace directory now is
1643 # already occupied by a filename
1644 pc = PersistentStore(
1645 path=str(tmpdir), namespace="t01", mode=PersistentStoreMode.FLUSH
1646 )
1647
1648 # Store some data and note that it isn't possible
1649 assert pc.write(b"data-t01") is False
1650 # We actually fell back to memory mode:
1651 assert pc.mode == PersistentStoreMode.MEMORY
1652
1653 # Set's work
1654 assert pc.set("key-t01", "value")
1655
1656 # But upon reinitializtion (enforcing memory mode check) we will not have
1657 # the data available to us
1658 pc = PersistentStore(
1659 path=str(tmpdir), namespace="t01", mode=PersistentStoreMode.FLUSH
1660 )
1661
1662 assert pc.get("key-t01") is None
1663
1664 #
1665 # Test situation where the file structure changed after initialization
1666 #
1667 pc = PersistentStore(
1668 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1669 )
1670 # Our mode stuck as t02 initialized correctly
1671 assert pc.mode == PersistentStoreMode.FLUSH
1672 assert os.path.isdir(pc.path)
1673
1674 shutil.rmtree(pc.path)
1675 assert not os.path.isdir(pc.path)
1676 assert pc.set("key-t02", "value")
1677 # The directory got re-created
1678 assert os.path.isdir(pc.path)
1679
1680 # Same test but flag set to AUTO
1681 pc = PersistentStore(
1682 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.AUTO
1683 )
1684 # Our mode stuck as t02 initialized correctly
1685 assert pc.mode == PersistentStoreMode.AUTO
1686 assert os.path.isdir(pc.path)
1687
1688 shutil.rmtree(pc.path)
1689 assert not os.path.isdir(pc.path)
1690 assert pc.set("key-t02", "value")
1691 # The directory is not recreated because of auto; it will occur on save
1692 assert not os.path.isdir(pc.path)
1693 path = pc.path
1694 del pc
1695 # It exists now
1696 assert os.path.isdir(path)
1697
1698 pc = PersistentStore(
1699 path=str(tmpdir), namespace="t02", mode=PersistentStoreMode.FLUSH
1700 )
1701 # Content was not lost
1702 assert pc.get("key-t02") == "value"
1703
1704 # We'll remove a sub directory of it this time
1705 shutil.rmtree(os.path.join(pc.path, pc.temp_dir))
1706
1707 # We will still successfully write our data
1708 assert pc.write(b"data-t02") is True
1709 assert os.path.isdir(pc.path)
1710
1711 shutil.rmtree(pc.path)
1712 assert not os.path.isdir(pc.path)
1713 assert pc.set("key-t01", "value")
1714
1715
1716 @pytest.mark.parametrize(
1717 "url",
1718 [
1719 "json://localhost/",
1720 "xml://localhost/",
1721 "form://localhost/",
1722 "mailtos://user:[email protected]/[email protected]",
1723 ],
1724 )
1725 def test_persistent_storage_disabled_per_url(url, tmpdir):
1726 """``store=no`` keeps the identifier but writes nothing to disk.
1727
1728 Services with read-only identifiers must switch storage mode without
1729 trying to replace that identifier.
1730 """
1731 asset = AppriseAsset(
1732 storage_path=str(tmpdir), storage_mode=PersistentStoreMode.FLUSH
1733 )
1734
1735 service = Apprise.instantiate(f"{url}?store=no", asset=asset)
1736 assert isinstance(service, NotifyBase)
1737
1738 # The identifier is still worked out as usual
1739 assert service.url_id()
1740
1741 # ...but everything it remembers is kept in memory
1742 assert service.store.mode is PersistentStoreMode.MEMORY
1743
1744 service.store.set("key", "value")
1745 service.flush_store()
1746 assert os.listdir(str(tmpdir)) == []
1747
1748 # ...and the setting is written back out so it survives a round trip
1749 assert "store=no" in service.url()
1750
1751
1752 def test_persistent_storage_writes_to_disk_when_left_on(tmpdir):
1753 """The same service with storage left on does use the disk."""
1754 asset = AppriseAsset(
1755 storage_path=str(tmpdir), storage_mode=PersistentStoreMode.FLUSH
1756 )
1757
1758 service = Apprise.instantiate("json://localhost/", asset=asset)
1759 service.store.set("key", "value")
1760 service.flush_store()
1761
1762 assert os.listdir(str(tmpdir)) == [service.url_id()]