Debian Codegraph @

tests/TestWorker.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (c) 2008-2026 Andrew Ziem.
3 #
4 # This work is licensed under the terms of the GNU GPL, version 3 or
5 # later. See the COPYING file in the top-level directory.
6
7
8 """
9 Test case for module Worker
10 """
11
12 import errno
13 import os
14 import sqlite3
15 import tempfile
16 from unittest import mock
17
18 from tests import TestCleaner, common
19 from tests.TestFileUtilities import _open_blocking_handle
20 import bleachbit
21 from bleachbit import CLI, Command, FileUtilities
22 from bleachbit.Action import ActionProvider
23 from bleachbit.Cleaner import backends
24 from bleachbit.Worker import Worker
25
26 if bleachbit.IS_WINDOWS:
27 import win32con
28 import win32file
29
30
31 class AccessDeniedActionAction(ActionProvider):
32 action_key = 'access.denied'
33
34 def __init__(self, action_element):
35 ActionProvider.__init__(self, action_element)
36 self.pathname = action_element.getAttribute('path')
37
38 def get_commands(self):
39 # access denied, should fail and continue
40 def accessdenied():
41 raise OSError(
42 errno.EACCES, 'Permission denied: c:\\access\\denied', 'c:\\access\\denied')
43 yield Command.Function(None, accessdenied, 'Test access denied')
44
45 # real file, should succeed
46 yield Command.Delete(self.pathname)
47
48
49 class DoesNotExistAction(ActionProvider):
50 action_key = 'does.not.exist'
51
52 def __init__(self, action_element):
53 ActionProvider.__init__(self, action_element)
54 self.pathname = action_element.getAttribute('path')
55
56 def get_commands(self):
57 # non-existent file, should fail and continue
58 if bleachbit.IS_WINDOWS:
59 yield Command.Delete(r"c:\does\not\exist")
60 else:
61 yield Command.Delete("/does/not/exist")
62
63 # real file, should succeed
64 yield Command.Delete(self.pathname)
65
66
67 class ToctouAction(ActionProvider):
68 """Simulate a TOCTOU race: a file exists at listing time but vanishes before getsize()"""
69
70 action_key = 'toctou'
71 ghost_path = None # stored for test cleanup
72
73 def __init__(self, action_element):
74 ActionProvider.__init__(self, action_element)
75 self.pathname = action_element.getAttribute('path')
76
77 def get_commands(self):
78 # Create a file that physically exists at listing time.
79 # The test mocks getsize() to raise FileNotFoundError for it,
80 # simulating the file vanishing between listing and size check.
81 (fd, filename) = tempfile.mkstemp(
82 prefix='bleachbit-test-worker-toctou-')
83 os.close(fd)
84 ToctouAction.ghost_path = filename
85 yield Command.Delete(filename)
86
87 # Real file, should succeed even after the prior TOCTOU failure.
88 yield Command.Delete(self.pathname)
89
90
91 class FunctionGeneratorAction(ActionProvider):
92 action_key = 'function.generator'
93
94 def __init__(self, action_element):
95 ActionProvider.__init__(self, action_element)
96 self.pathname = action_element.getAttribute('path')
97
98 def get_commands(self):
99 # function generator without path, should succeed
100 def funcgenerator():
101 yield 10
102 yield Command.Function(None, funcgenerator, 'funcgenerator')
103
104 # real file, should succeed
105 yield Command.Delete(self.pathname)
106
107
108 class FunctionPathAction(ActionProvider):
109 action_key = 'function.path'
110
111 def __init__(self, action_element):
112 ActionProvider.__init__(self, action_element)
113 self.pathname = action_element.getAttribute('path')
114
115 def get_commands(self):
116 # function with path, should succeed
117 def pathfunc(_path):
118 pass
119 # self.pathname must exist because it checks the file size
120 yield Command.Function(self.pathname, pathfunc, 'pathfunc')
121
122 # real file, should succeed
123 yield Command.Delete(self.pathname)
124
125
126 class InvalidEncodingAction(ActionProvider):
127 action_key = 'invalid.encoding'
128
129 def __init__(self, action_element):
130 ActionProvider.__init__(self, action_element)
131 self.pathname = action_element.getAttribute('path')
132
133 def get_commands(self):
134 # file with invalid encoding
135 (fd, filename) = tempfile.mkstemp('invalid-encoding-\xe4\xf6\xfc~')
136 os.close(fd)
137 yield Command.Delete(filename)
138
139 # real file, should succeed
140 yield Command.Delete(self.pathname)
141
142
143 class FunctionPlainAction(ActionProvider):
144 action_key = 'function.plain'
145
146 def __init__(self, action_element):
147 ActionProvider.__init__(self, action_element)
148 self.pathname = action_element.getAttribute('path')
149
150 def get_commands(self):
151 # plain function without path, should succeed
152 def intfunc():
153 return int(5)
154 yield Command.Function(None, intfunc, 'intfunc')
155
156 # real file, should succeed
157 yield Command.Delete(self.pathname)
158
159
160 class LockedAction(ActionProvider):
161
162 action_key = 'locked'
163
164 def __init__(self, action_element):
165 ActionProvider.__init__(self, action_element)
166 self.pathname = action_element.getAttribute('path')
167
168 def get_commands(self):
169 # Open the file with a blocking handle that allows read/write but blocks delete.
170 # This causes delete() to truncate and mark for deletion. Windows only.
171 share_mode = win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE
172 handle = _open_blocking_handle(self.pathname, share_mode)
173 from bleachbit.FileUtilities import getsize
174 # Without admin privileges, this delete fails.
175 yield Command.Delete(self.pathname)
176 assert os.path.exists(self.pathname)
177 fsize = getsize(self.pathname)
178 if not fsize == 0: # File should be truncated to 0 bytes
179 raise RuntimeError('Locked file has size %dB (not 0B)' % fsize)
180 win32file.CloseHandle(handle)
181
182 # Now that the file is not locked, admin privileges
183 # are not required to delete it.
184 yield Command.Delete(self.pathname)
185
186
187 class RuntimeErrorAction(ActionProvider):
188
189 action_key = 'runtime'
190
191 def __init__(self, action_element):
192 ActionProvider.__init__(self, action_element)
193 self.pathname = action_element.getAttribute('path')
194
195 def get_commands(self):
196 # runtime exception, should fail and continue
197 def runtime():
198 raise RuntimeError('This is a test exception')
199
200 yield Command.Function(None, runtime, 'Test runtime exception')
201
202 # real file, should succeed
203 yield Command.Delete(self.pathname)
204
205
206 class TruncateTestAction(ActionProvider):
207 action_key = 'truncate.test'
208
209 def __init__(self, action_element):
210 ActionProvider.__init__(self, action_element)
211 self.pathname = action_element.getAttribute('path')
212
213 def get_commands(self):
214 # truncate real file
215 yield Command.Truncate(self.pathname)
216
217 # real file, should succeed
218 yield Command.Delete(self.pathname)
219
220
221 class WorkerTestCase(common.BleachbitTestCase):
222
223 """Test case for module Worker"""
224
225 def action_test_helper(self, command, special_expected, errors_expected,
226 bytes_expected_posix, count_deleted_posix,
227 bytes_expected_nt, count_deleted_nt):
228 ui = CLI.CliCallback()
229 (fd, filename) = tempfile.mkstemp(
230 prefix='bleachbit-test-worker', dir=self.tempdir)
231 os.write(fd, b'123')
232 os.close(fd)
233 self.assertExists(filename)
234 astr = '<action command="%s" path="%s"/>' % (command, filename)
235 cleaner = TestCleaner.action_to_cleaner(astr)
236 backends['test'] = cleaner
237 operations = {'test': ['option1']}
238 worker = Worker(ui, True, operations)
239 run = worker.run()
240 while next(run):
241 pass
242 del backends['test']
243 self.assertNotExists(filename, "Path still exists '%s'" % filename)
244 self.assertEqual(worker.total_special, special_expected,
245 'For command %s expecting %s special operations but observed %d'
246 % (command, special_expected, worker.total_special))
247 self.assertEqual(worker.total_errors, errors_expected,
248 'For command %s expecting %d errors but observed %d'
249 % (command, errors_expected, worker.total_errors))
250 if bleachbit.IS_POSIX:
251 self.assertEqual(worker.total_bytes, bytes_expected_posix)
252 self.assertEqual(worker.total_deleted, count_deleted_posix)
253 elif bleachbit.IS_WINDOWS:
254 self.assertEqual(worker.total_bytes, bytes_expected_nt)
255 self.assertEqual(worker.total_deleted, count_deleted_nt)
256
257 def test_AccessDenied(self):
258 """Test Worker using Action.AccessDeniedAction"""
259 with self.assertLogs(level='ERROR') as log_context:
260 self.action_test_helper('access.denied', 0, 1, 4096, 1, 3, 1)
261 if bleachbit.IS_WINDOWS:
262 self.assertIn('Access denied: c:\\access\\denied',
263 log_context.output[0])
264 self.assertNotIn('\\\\', log_context.output[0])
265
266 def test_DoesNotExist(self):
267 """Test Worker using Action.DoesNotExistAction"""
268 with self.assertLogs(level='ERROR') as log_context:
269 self.action_test_helper('does.not.exist', 0, 1, 4096, 1, 3, 1)
270 if bleachbit.IS_WINDOWS:
271 # Make sure there is a simple messages without double backslashes.
272 self.assertIn(
273 'File not found: c:\\does\\not\\exist', log_context.output[0])
274 self.assertNotIn('\\\\', log_context.output[0])
275
276 def test_TOCTOU_vanished_during_preview(self):
277 """Test Worker continues to the next file after a TOCTOU race
278
279 A file that exists at listing time but vanishes before getsize()
280 (simulated via mock) should log an error but not block the next file.
281 """
282 real_getsize = FileUtilities.getsize
283 call_count = [0]
284
285 def vanishing_getsize(path):
286 call_count[0] += 1
287 if call_count[0] == 1:
288 raise FileNotFoundError(
289 errno.ENOENT, 'No such file or directory', path)
290 return real_getsize(path)
291
292 try:
293 with mock.patch('bleachbit.FileUtilities.getsize',
294 side_effect=vanishing_getsize):
295 with self.assertLogs(level='ERROR') as log_context:
296 # assert 1 file processed and 1 error
297 self.action_test_helper(
298 'toctou', 0, 1, 4096, 1, 3, 1)
299 self.assertIn('File not found', '\n'.join(log_context.output))
300 finally:
301 # Clean up the ghost file that was not deleted by the worker
302 if ToctouAction.ghost_path and os.path.exists(ToctouAction.ghost_path):
303 os.unlink(ToctouAction.ghost_path)
304 ToctouAction.ghost_path = None
305
306 def test_FunctionGenerator(self):
307 """Test Worker using Action.FunctionGenerator"""
308 self.action_test_helper('function.generator', 1,
309 0, 4096 + 10, 1, 3 + 10, 1)
310
311 def test_FunctionPath(self):
312 """Test Worker using Action.FunctionPathAction"""
313 self.action_test_helper('function.path', 1, 0, 4096, 1, 3, 1)
314
315 def test_FunctionPlain(self):
316 """Test Worker using Action.FunctionPlainAction"""
317 self.action_test_helper('function.plain', 1, 0, 4096 + 5, 1, 3 + 5, 1)
318
319 def test_InvalidEncoding(self):
320 """Test Worker using Action.InvalidEncodingAction"""
321 self.action_test_helper('invalid.encoding', 0, 0, 4096, 2, 3, 2)
322
323 @common.skipUnlessWindows
324 def test_Locked(self):
325 """Test Worker using Action.LockedAction"""
326 from win32com.shell import shell
327 if shell.IsUserAnAdmin():
328 # If an admin, the first attempt, with locking, will mark for
329 # delete (3 bytes), and the second attempt will actually delete
330 # it (0 bytes, already truncated).
331 errors_expected = 0
332 bytes_expected = 3 + 0
333 total_deleted = 2
334 else:
335 # If not an admin, the first attempt (locked) truncates (to 0B) and fails,
336 # then the second attempt (unlocked) deletes the 0-byte file.
337 errors_expected = 1
338 bytes_expected = 0
339 total_deleted = 1
340 self.action_test_helper(
341 'locked', 0, errors_expected, None, None, bytes_expected, total_deleted)
342
343 def test_SqliteDatabaseLocked(self):
344 """Test Worker logs a locked SQLite database without a traceback"""
345 path = self.write_file('test_sqlite_database_locked', b'')
346
347 def sqlite_locked(_):
348 raise sqlite3.OperationalError('database is locked')
349
350 cmd = Command.Function(path, sqlite_locked,
351 'Test SQLite database locked')
352 worker = Worker(CLI.CliCallback(), True, {'test': ['option1']})
353 with self.assertLogs('bleachbit.Worker', level='ERROR') as log_context:
354 list(worker.execute(cmd, 'option1'))
355 output = '\n'.join(log_context.output)
356 self.assertIn(f'Database is locked: {path}', output)
357 self.assertNotIn('Traceback', output)
358 self.assertEqual(worker.total_errors, 1)
359
360 def test_RuntimeError(self):
361 """Test Worker using Action.RuntimeErrorAction. It is normal to see a traceback.
362
363 The Worker module handles these differently than
364 access denied exceptions
365 """
366 self.action_test_helper('runtime', 0, 1, 4096, 1, 3, 1)
367
368 def test_Truncate(self):
369 """Test Worker using Action.TruncateTestAction
370 """
371 self.action_test_helper('truncate.test', 0, 0, 4096, 2, 3, 2)
372
373 def test_deep_scan(self):
374 """Test for deep scan"""
375
376 # load cleaners from XML
377 import bleachbit.CleanerML
378 list(bleachbit.CleanerML.load_cleaners())
379
380 # DeepScan itself is tested elsewhere, so replace it here
381 import bleachbit.DeepScan
382 SaveDeepScan = bleachbit.DeepScan.DeepScan
383 self.scanned = 0
384 parent = self
385
386 class MyDeepScan:
387 def __init__(self, searches):
388 for (path, searches) in searches.items():
389 parent.assertEqual(path, os.path.expanduser('~'))
390 for s in searches:
391 parent.assertIn(
392 s.regex, ['^Thumbs\\.db$', '^Thumbs\\.db:encryptable$'])
393
394 def scan(self):
395 parent.scanned += 1
396 yield True
397
398 bleachbit.DeepScan.DeepScan = MyDeepScan
399
400 # test
401 operations = {'deepscan': ['thumbs_db']}
402 ui = CLI.CliCallback()
403 worker = Worker(ui, False, operations).run()
404 while next(worker):
405 pass
406 self.assertEqual(1, self.scanned)
407
408 # clean up
409 bleachbit.DeepScan.DeepScan = SaveDeepScan
410
411 def test_multiple_options(self):
412 """Test one cleaner with two options"""
413 ui = CLI.CliCallback()
414 filename1 = self.mkstemp(prefix='bleachbit-test-worker')
415 filename2 = self.mkstemp(prefix='bleachbit-test-worker')
416
417 astr1 = '<action command="delete" search="file" path="%s"/>' % filename1
418 astr2 = '<action command="delete" search="file" path="%s"/>' % filename2
419 cleaner = TestCleaner.actions_to_cleaner([astr1, astr2])
420 backends['test'] = cleaner
421 operations = {'test': ['option1', 'option2']}
422 worker = Worker(ui, True, operations)
423 run = worker.run()
424 while next(run):
425 pass
426 del backends['test']
427 self.assertNotExists(filename1)
428 self.assertNotExists(filename2)
429 self.assertEqual(worker.total_special, 0)
430 self.assertEqual(worker.total_errors, 0)
431 self.assertEqual(worker.total_deleted, 2)