Debian Codegraph @

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