Debian Codegraph @

tests/test_multiplatform.py

raw
1 # Copyright 2016-2026 Facundo Batista, Nicolás Demarchi
2 #
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General
5 # Public License version 3, as published by the Free Software Foundation.
6 #
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranties of
9 # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.
10 # See the GNU General Public License for more details.
11 #
12 # You should have received a copy of the GNU General Public License
13 # along with this program.
14 # If not, see <http://www.gnu.org/licenses/>.
15 #
16 # For further info, check https://github.com/PyAr/fades
17
18 """Tests for the helpers in multiplatform."""
19
20 import threading
21 import time
22 import unittest
23 from pathlib import Path
24
25 from fades.multiplatform import filelock
26
27
28 class LockChecker(threading.Thread):
29 """Helper to check the lock in other thread.
30
31 The time.sleep() in the middle of the process is for time.time()
32 granularity in different platforms to not mess our tests.
33 """
34
35 def __init__(self, filepath):
36 self.filepath = filepath
37 self.in_lock = self.post_work = None
38 self.middle_work = threading.Event()
39 super().__init__()
40
41 def run(self):
42 with filelock(self.filepath):
43 time.sleep(.01)
44 self.in_lock = time.time()
45 self.middle_work.wait()
46 self.post_work = time.time()
47
48
49 class LockCacheTestCase(unittest.TestCase):
50 """Tests for the locking utility."""
51
52 def setUp(self):
53 self.test_path = Path("test_filelock")
54
55 def tearDown(self):
56 if self.test_path.exists():
57 self.test_path.unlink()
58
59 def wait(self, lock_checker, attr_name):
60 """Wait at most a second for the LockChecker to end."""
61 for i in range(10):
62 attr = getattr(lock_checker, attr_name)
63 if attr is not None:
64 # ended!
65 return
66 time.sleep(.3)
67 self.fail("LC didnt end: %s" % (lock_checker,))
68
69 def test_lock_alone(self):
70 lc = LockChecker(self.test_path)
71 lc.start()
72 lc.middle_work.set()
73 self.wait(lc, 'post_work')
74
75 def test_lock_intermixed(self):
76 lc1 = LockChecker(self.test_path)
77 lc1.start()
78 self.wait(lc1, 'in_lock')
79
80 lc2 = LockChecker(self.test_path)
81 lc2.start()
82
83 lc1.middle_work.set()
84 self.wait(lc1, 'post_work')
85
86 lc2.middle_work.set()
87 self.wait(lc2, 'post_work')
88
89 # check LC 2 waited to enter
90 self.assertGreater(lc2.in_lock, lc1.post_work)
91
92 def test_lock_exploding(self):
93 # get the lock and explode in the middle (then ignore the blast)
94 try:
95 with filelock(self.test_path):
96 raise ValueError("pumba")
97 except ValueError:
98 pass
99
100 # get the lock again
101 with filelock(self.test_path):
102 pass