Debian Codegraph @

tests/TestCleaner.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 Cleaner
10 """
11
12 import glob
13 import logging
14 import os
15 import shutil
16 from unittest import mock
17 from xml.dom.minidom import parseString
18
19 import bleachbit
20 from bleachbit import IS_WINDOWS, IS_POSIX
21 from bleachbit.Action import ActionProvider, Command
22 from bleachbit.Cleaner import Cleaner, System, backends, create_simple_cleaner, simpler_cleaner_process_path, register_cleaners
23 from bleachbit.FileUtilities import extended_path_undo
24 from bleachbit.PathUtils import path_startswith
25
26 from tests import common
27
28 logger = logging.getLogger('bleachbit')
29
30
31 def action_to_cleaner(action_str):
32 """Given an action XML fragment, return a cleaner"""
33 return actions_to_cleaner([action_str])
34
35
36 def actions_to_cleaner(action_strs):
37 """Given multiple action XML fragments, return one cleaner"""
38
39 cleaner = Cleaner()
40 for count, action_str in enumerate(action_strs, start=1):
41 dom = parseString(action_str)
42 action_node = dom.childNodes[0]
43 command = action_node.getAttribute('command')
44 provider = None
45 for actionplugin in ActionProvider.plugins:
46 if actionplugin.action_key == command:
47 provider = actionplugin(action_node)
48 cleaner.add_action(f'option{count}', provider)
49 cleaner.add_option(
50 f'option{count}', f'name{count}', f'description{count}')
51 return cleaner
52
53
54 def register_all_cleaners():
55 """Register all cleaners for testing; leaves winapp2.ini in the shared personal_cleaners_dir"""
56 if IS_WINDOWS:
57 from tests.TestWinapp import get_winapp2 # pylint: disable=import-outside-toplevel
58
59 os.makedirs(bleachbit.personal_cleaners_dir, exist_ok=True)
60 print(f"personal_cleaners_dir: {bleachbit.personal_cleaners_dir}")
61 shutil.copyfile(
62 get_winapp2(),
63 os.path.join(bleachbit.personal_cleaners_dir, 'winapp2.ini'),
64 )
65 # Previously, we guarded registration with `if not backends`, but
66 # this was unreliable under pytest-xdist, like if a test created
67 # a single test cleaner.
68 list(register_cleaners())
69 assert len(backends) > 1
70
71
72 class CleanerTestCase(common.BleachbitTestCase):
73
74 @classmethod
75 def setUpClass(cls):
76 """Set up CleanerTestCase class"""
77 super().setUpClass()
78 # Register all cleaners once for the whole class so that tests can
79 # rely on `backends` being populated even when run in isolation.
80 # register_all_cleaners() is idempotent.
81 register_all_cleaners()
82
83 def test_add_action(self):
84 """Unit test for Cleaner.add_action()"""
85 self.actions = []
86 if IS_WINDOWS:
87 self.actions += [
88 '<action command="delete" search="file" path="$WINDIR\\explorer.exe"/>',
89 '<action command="delete" search="glob" path="$WINDIR\\system32\\*.dll"/>',
90 '<action command="delete" search="walk.files" path="$WINDIR\\system32\\"/>',
91 '<action command="delete" search="walk.all" path="$WINDIR\\system32\\"/>']
92 elif IS_POSIX:
93 print(__file__)
94 self.actions += [
95 f'<action command="delete" search="file" path="{__file__}"/>',
96 '<action command="delete" search="glob" path="/bin/*sh"/>',
97 '<action command="delete" search="walk.files" path="/bin/"/>',
98 '<action command="delete" search="walk.all" path="/var/log/"/>']
99 else:
100 raise AssertionError('Unknown OS.')
101 self.assertGreater(len(self.actions), 0)
102
103 for action_str in self.actions:
104 cleaner = action_to_cleaner(action_str)
105 count = 0
106 for cmd in cleaner.get_commands('option1'):
107 for result in cmd.execute(False):
108 self.assertEqual(result['n_deleted'], 1)
109 pathname = result['path']
110 self.assertLExists(
111 pathname, f"Does not exist: '{pathname}'")
112 count += 1
113 common.validate_result(self, result)
114 self.assertGreater(count, 0, f"No files found for {action_str}")
115 # should yield nothing
116 cleaner.add_option('option2', 'name2', 'description2')
117 for cmd in cleaner.get_commands('option2'):
118 print(cmd)
119 raise AssertionError('option2 should yield nothing')
120 # should fail
121 self.assertRaises(
122 RuntimeError, cleaner.get_commands('option3').__next__)
123
124 def test_multiple_actions_per_option(self):
125 """Multiple actions under one option run in registration order, and
126 actions added after get_commands()/get_deep_scan() are reflected."""
127
128 class _StubAction:
129 """Minimal action provider yielding sentinel values."""
130
131 def __init__(self, token):
132 self.token = token
133
134 def get_commands(self):
135 yield self.token
136
137 def get_deep_scan(self):
138 yield ('deep', self.token)
139
140 cleaner = Cleaner()
141 cleaner.add_option('opt', 'name', 'description')
142 cleaner.add_action('opt', _StubAction('a'))
143 cleaner.add_action('opt', _StubAction('b'))
144
145 # Both actions run, in registration order
146 self.assertEqual(list(cleaner.get_commands('opt')), ['a', 'b'])
147 self.assertEqual(list(cleaner.get_deep_scan('opt')),
148 [('deep', 'a'), ('deep', 'b')])
149
150 # Adding an action after the index is built must be reflected
151 cleaner.add_action('opt', _StubAction('c'))
152 self.assertEqual(list(cleaner.get_commands('opt')), ['a', 'b', 'c'])
153 self.assertEqual(list(cleaner.get_deep_scan('opt')),
154 [('deep', 'a'), ('deep', 'b'), ('deep', 'c')])
155
156 # A registered option with no actions yields nothing without raising
157 cleaner.add_option('empty', 'name2', 'description2')
158 self.assertEqual(list(cleaner.get_commands('empty')), [])
159
160 def test_deep_scan_after_action_without_deep_scan(self):
161 """An action without a deep scan must not hide later deep scans"""
162
163 class _DeepStubAction:
164 """Minimal action provider yielding one deep scan entry."""
165
166 def get_deep_scan(self):
167 yield ('deep', 'entry')
168
169 cleaner = Cleaner()
170 cleaner.add_option('opt', 'name', 'description')
171 # The base class stands in for any action without a deep scan,
172 # such as winreg or process.
173 cleaner.add_action('opt', ActionProvider(None))
174 cleaner.add_action('opt', _DeepStubAction())
175
176 self.assertEqual(list(cleaner.get_deep_scan('opt')),
177 [('deep', 'entry')])
178
179 # should fail, like get_commands()
180 self.assertRaises(
181 RuntimeError, cleaner.get_deep_scan('unknown').__next__)
182
183 def test_has_action_key(self):
184 """Unit test for Cleaner.has_action_key()"""
185
186 class _StubAction:
187 """Minimal action provider carrying only an action_key."""
188
189 def __init__(self, action_key):
190 self.action_key = action_key
191
192 cleaner = Cleaner()
193 cleaner.add_option('opt', 'name', 'description')
194 cleaner.add_action('opt', _StubAction('delete'))
195 self.assertFalse(cleaner.has_action_key('opt', 'cookie'))
196 # an option id that was never registered is not an error
197 self.assertFalse(cleaner.has_action_key('missing', 'cookie'))
198
199 # an action added after the index was built must be reflected
200 cleaner.add_action('opt', _StubAction('cookie'))
201 self.assertTrue(cleaner.has_action_key('opt', 'cookie'))
202
203 # the action must belong to the option that is asked about
204 cleaner.add_action('other', _StubAction('shred'))
205 self.assertTrue(cleaner.has_action_key('other', 'shred'))
206 self.assertFalse(cleaner.has_action_key('opt', 'shred'))
207
208 def test_auto_hide(self):
209 count = 0
210 for key in sorted(backends):
211 self.assertIsInstance(backends[key].auto_hide(), bool)
212 count += 1
213 self.assertGreater(count, 0)
214
215 def test_create_simple_cleaner(self):
216 """Unit test for method create_simple_cleaner"""
217 dirname = self.mkdtemp(prefix='bleachbit-test-create-simple-cleaner')
218 filename1 = os.path.join(dirname, '1')
219 common.touch_file(filename1)
220 # test Cyrillic for https://bugs.launchpad.net/bleachbit/+bug/1541808
221 filename2 = os.path.join(dirname, 'чистый')
222 common.touch_file(filename2)
223 targets = [filename1, filename2, dirname]
224 cleaner = create_simple_cleaner(targets)
225 for cmd in cleaner.get_commands('files'):
226 # preview
227 for result in cmd.execute(False):
228 common.validate_result(self, result)
229 # delete
230 list(cmd.execute(True))
231
232 for target in targets:
233 self.assertNotExists(target)
234
235 def test_create_simple_cleaner_recursive(self):
236 """Verify create_simple_cleaner deletes recursive directory trees"""
237 # Build: root/
238 # file.txt
239 # sub1/
240 # file.txt
241 # sub2/
242 # file.txt
243 root = self.mkdir('csc-recursive') # relative to self.tempdir
244 sub1 = self.mkdir(os.path.join(root, 'sub1'))
245 sub2 = self.mkdir(os.path.join(sub1, 'sub2'))
246 dirnames = [root, sub1, sub2]
247 for dirname in dirnames:
248 common.touch_file(os.path.join(dirname, 'file.txt'))
249
250 cleaner = create_simple_cleaner([root])
251 for cmd in cleaner.get_commands('files'):
252 list(cmd.execute(True))
253
254 for dirname in dirnames:
255 self.assertNotExists(dirname)
256
257 def test_create_simple_cleaner_refuses_cwd(self):
258 """create_simple_cleaner must refuse to shred CWD or its parent."""
259 cwd = os.getcwd()
260 cwd_parent = os.path.dirname(cwd)
261 # Every spelling of "the working directory" or its parent.
262 bad_inputs = ('', ' ', '.', '..', './', './.', 'foo/..',
263 cwd, cwd_parent,
264 cwd + os.sep, os.path.join(cwd, '.'),
265 cwd_parent + os.sep, os.path.join(cwd_parent, '.'))
266 for bad in bad_inputs:
267 cleaner = create_simple_cleaner([bad])
268 cmds = list(cleaner.get_commands('files'))
269 self.assertEqual(cmds, [], f'expected no commands for {bad!r}')
270
271 def test_simpler_cleaner_process_path(self):
272 """Unit test for simpler_cleaner_process_path()."""
273 cwd = os.getcwd()
274 cwd_parent = os.path.dirname(cwd)
275
276 # Refused inputs return None.
277 for bad in ('', ' ', '.', '..', './', './.', 'foo/..', cwd, cwd_parent):
278 self.assertIsNone(simpler_cleaner_process_path(bad),
279 f'expected None for {bad!r}')
280
281 # Non-string raises.
282 for bad in (123, None, [], {}, set()):
283 with self.assertRaises(RuntimeError):
284 simpler_cleaner_process_path(bad)
285
286 # An absolute path is returned unchanged.
287 # It does not need to exist.
288 if IS_WINDOWS:
289 missing_abs_path = r'c:\nonexistent\path'
290 else:
291 missing_abs_path = '/nonexistent/path'
292 self.assertEqual(simpler_cleaner_process_path(
293 missing_abs_path), missing_abs_path)
294
295 # A relative path is returned as an absolute path.
296 # It does not need to exist.
297 # A genuinely relative path (a bare filename relative to CWD)
298 # is normalized to an absolute one and must not collapse to CWD.
299 # chdir into the tempdir so a bare filename resolves there; the
300 # context manager restores CWD even on assertion failure.
301 # macOS needs realpath because path uses symlink.
302 rel_target = os.path.join(os.path.realpath(self.tempdir), 'rel-target')
303 # After dropping support for Python 3.9, this can be simplified to:
304 # `with contextlib.chdir(self.tempdir):`
305 orig_cwd = os.getcwd()
306 try:
307 os.chdir(self.tempdir)
308 processed = simpler_cleaner_process_path('rel-target')
309 finally:
310 os.chdir(orig_cwd)
311 # On Windows, `processed` may be a 8.3 short name, so expand to
312 # long path before comparison.
313 self.assertEqual(os.path.realpath(processed), rel_target)
314 self.assertNotEqual(processed, self.tempdir)
315
316 def test_get_name(self):
317 count = 0
318 for key in sorted(backends):
319 self.assertIsString(backends[key].get_name())
320 count += 1
321 self.assertGreater(count, 10)
322
323 def test_get_description(self):
324 count = 0
325 for key in sorted(backends):
326 self.assertIsString(key)
327 self.assertIsInstance(backends[key], Cleaner)
328 desc = backends[key].get_description()
329 if desc is not None:
330 self.assertIsString(
331 desc, msg="description for '%s' is '%s'" % (key, desc))
332 count += 1
333 self.assertGreater(count, 10)
334
335 def test_get_options(self):
336 count = 0
337 for key in sorted(backends):
338 for (test_id, name) in backends[key].get_options():
339 self.assertIsString(
340 test_id, msg='%s.%s is not a string' % (key, test_id))
341 self.assertIsString(name)
342 count += 1
343 self.assertGreater(count, 10)
344
345 def test_get_commands(self):
346 validate_count = 0
347 # Directories shared across parallel pytest-xdist workers where
348 # files may appear/vanish between discovery and validation
349 # (TOCTOU).
350 # The system temporary directory covers Winapp2.ini
351 # `[Windows Temporary Files *]`, whose name and ID may change, so
352 # we check for it here by directory name.
353 volatile_dir = common.get_volatile_dir()
354
355 def is_volatile(path):
356 if not path:
357 return False
358 if IS_WINDOWS:
359 path = extended_path_undo(path)
360 return path_startswith(path, volatile_dir, case_sensitive=False)
361
362 for key in sorted(backends):
363 logger.debug("test_get_commands: key='%s'", key)
364 for (option_id, __name) in backends[key].get_options():
365 is_system_tmp = (key, option_id) == ('system', 'tmp')
366 for cmd in backends[key].get_commands(option_id):
367 try:
368 for result in cmd.execute(really_delete=False):
369 allow_vanishing = is_system_tmp \
370 or is_volatile(result.get('path'))
371 common.validate_result(
372 self, result, allow_vanishing=allow_vanishing)
373 validate_count += 1
374 except FileNotFoundError as e:
375 if not (is_system_tmp or is_volatile(e.filename)):
376 raise
377 logger.debug('TOCTOU: file vanished: %s', e.filename)
378 self.assertGreater(validate_count, 10,
379 "expected >10 file/results to validate")
380 # make sure trash and tmp don't return the same results
381 if IS_WINDOWS:
382 return
383
384 def get_files(option_id):
385 ret = []
386 for cmd in backends['system'].get_commands(option_id):
387 try:
388 result = next(cmd.execute(False))
389 except FileNotFoundError as e:
390 logger.debug('TOCTOU: file vanished: %s', e.filename)
391 continue
392 ret.append(result['path'])
393 return ret
394 trash_paths = get_files('trash')
395 tmp_paths = get_files('tmp')
396 for tmp_path in tmp_paths:
397 self.assertNotIn(tmp_path, trash_paths)
398
399 def test_no_files_exist(self):
400 """Verify only existing files are returned
401
402 It monkeypatches file system functions to return no files.
403 Then, it tries every cleaning option.
404 """
405 _exists = os.path.exists
406 _iglob = glob.iglob
407 _isdir = os.path.isdir
408 _lexists = os.path.lexists
409 _listdir = os.listdir
410 _oswalk = os.walk
411 _scandir = os.scandir
412
413 class _EmptyScandir:
414 """Mimic os.scandir returning no entries (and a no-op context)."""
415
416 def __iter__(self):
417 return iter(())
418
419 def __enter__(self):
420 return self
421
422 def __exit__(self, *exc):
423 return False
424
425 try:
426 glob.iglob = lambda path, *args, **kwargs: []
427 os.path.exists = lambda path: False
428 os.path.isdir = lambda path: False
429 os.path.lexists = lambda path: False
430 os.listdir = lambda path: []
431 os.walk = lambda top, topdown=True, onerror=None, followlinks=False: []
432 os.scandir = lambda path='.', *args, **kwargs: _EmptyScandir()
433 for key in sorted(backends):
434 for (option_id, __name) in backends[key].get_options():
435 for cmd in backends[key].get_commands(option_id):
436 # Some cleaners can still return a command, so next run
437 # a preview.
438 for result in cmd.execute(really_delete=False):
439 if not result:
440 break
441 msg = f"Expected no files to be deleted but got '{result}'"
442 self.assertNotIsInstance(cmd, Command.Delete, msg)
443 finally:
444 glob.iglob = _iglob
445 os.path.exists = _exists
446 os.path.isdir = _isdir
447 os.path.lexists = _lexists
448 os.listdir = _listdir
449 os.walk = _oswalk
450 os.scandir = _scandir
451
452 def test_register_cleaners(self):
453 """Unit test for register_cleaners"""
454 # setUpClass already registered cleaners; clear to test cold start.
455 backends.clear()
456 register_all_cleaners()
457 register_all_cleaners()
458 backends.clear()
459 register_all_cleaners()
460
461 @common.skipIfWindows # FIXME later: reevaluate
462 @common.skipUnlessDestructive
463 def test_system_recent_documents(self):
464 """Clean recent documents in GTK"""
465 from bleachbit.GtkShim import (
466 Gtk, Gio, GLib, suppress_pygobject_asyncio_warnings)
467 mgr = Gtk.RecentManager().get_default()
468 fn = self.mkstemp(suffix='.txt')
469 self.assertExists(fn)
470 uri = Gio.File.new_for_path(fn).get_uri()
471 self.assertTrue(mgr.add_item(uri))
472 GLib.idle_add(Gtk.main_quit)
473 # PyGObject 3.56.2 calls deprecated asyncio APIs in Gtk.main(),
474 # which breaks tests run with warnings as errors.
475 with suppress_pygobject_asyncio_warnings():
476 Gtk.main() # process the addition
477 GLib.idle_add(Gtk.main_quit)
478 self.assertGreater(len(mgr.get_items()), 0)
479 self.assertTrue(mgr.has_item(uri))
480
481 for cmd in backends['system'].get_commands('recent_documents'):
482 for result in cmd.execute(really_delete=True):
483 common.validate_result(self, result, True)
484
485 self.assertEqual(len(mgr.get_items()), 0)
486
487 @common.skipIfWindows
488 def test_whitelist_home_with_regex_metacharacters(self):
489 """A home directory with regex metacharacters must still be kept"""
490 for home in ('/home/a*b', '/home/a+b', '/home/x)y(z'):
491 cleaner = System()
492 with mock.patch('os.path.expanduser',
493 lambda path, home=home: path.replace('~', home, 1)):
494 cleaner.init_whitelist()
495 self.assertTrue(cleaner.whitelisted(home + '/.cache/mozilla/x'), home)
496 self.assertTrue(cleaner.whitelisted(home + '/.cache/kwin/y'), home)
497 self.assertFalse(cleaner.whitelisted(home + '/.cache/other/z'), home)
498 self.assertFalse(cleaner.whitelisted('/tmp/nope'), home)
499
500 @common.skipIfWindows
501 def test_whitelist(self):
502 """Unit test for method Cleaner.whitelisted"""
503 tests = [
504 ('/tmp/.truecrypt_aux_mnt1/control', True),
505 ('/tmp/.truecrypt_aux_mnt1/volume', True),
506 ('/tmp/.vbox-foo-ipc/lock', True),
507 ('/tmp/.wine-500/server-806-102400f/lock', True),
508 ('/tmp/gconfd-foo/lock/ior', True),
509 ('/tmp/ksocket-foo/Arts_SoundServerV2', True),
510 ('/tmp/ksocket-foo/secret-cookie', True),
511 ('/tmp/orbit-foo/bonobo-activation-register-a9cd6cc4973af098918b154c4957a93f.lock', True),
512 ('/tmp/orbit-foo/bonobo-activation-register.lock', True),
513 ('/tmp/orbit-foo/bonobo-activation-server-a9cd6cc4973af098918b154c4957a93f-ior', True),
514 ('/tmp/orbit-foo/bonobo-activation-server-ior', True),
515 ('/tmp/pulse-foo/pid', True),
516 ('/tmp/tmpsDOBFd', False),
517 ('~/.cache/obexd', True),
518 ('~/.cache/obexd/', True),
519 ('~/.cache/obexd/foo', True),
520 ('~/.cache/obex', False),
521 ('~/.cache/obexd-foo', False),
522 ('~/.cache/kwin', True),
523 ('~/.cache/kwi', False),
524 ('~/.cache/kwi/foo.txt', False),
525 ('~/.cache/kwin/test_file', True),
526 ('~/.cache/mesa_shader_cache', True),
527 ('~/.cache/mesa_shader_cache/test_file', True),
528 ('~/.cache/plasmashell', True),
529 ('~/.cache/plasmashell/test_file', True),
530 ('~/.cache/icon-cache.kcache', True),
531 ('~/.cache/plasma_theme_breeze-light_v5.103.0.kcache', True),
532 ('~/.cache/drkonqi', True),
533 ('~/.cache/drkonqi/test_file', True),
534 ('~/.cache/mesa_shader_cache_db', True),
535 ('~/.cache/mesa_shader_cache_db/test_file', True),
536 ('~/.cache/qtshadercache-x86_64-little_endian-lp64', True),
537 ('~/.cache/qtshadercache-x86_64-little_endian-lp64/test_file', True),
538 ('~/.cache/plasma_theme_default.kcache', True)
539 ]
540 for pathname, expected in tests:
541 path = os.path.expanduser(
542 pathname) if pathname.startswith('~') else pathname
543 self.assertEqual(
544 backends['system'].whitelisted(path), expected, pathname)
545 # Make sure directory ~/.cache/obexd is ignored
546 # https://github.com/bleachbit/bleachbit/issues/572
547 obexd_dir = os.path.expanduser('~/.cache/obexd')
548 if not os.path.exists(obexd_dir):
549 os.makedirs(obexd_dir)
550 obexd_fn = os.path.join(obexd_dir, 'bleachbit-test')
551 common.touch_file(obexd_fn)
552 for cmd in backends['system'].get_commands('cache'):
553 for _ in cmd.execute(really_delete=False):
554 self.assertNotEqual(cmd.path, obexd_fn)
555 self.assertNotIn('/.cache/obexd/', cmd.path)
556 from bleachbit.FileUtilities import delete
557 delete(obexd_fn, ignore_missing=True)
558
559 def test_custom(self):
560 """Test system.custom"""
561 from bleachbit.Options import options
562 original_custom_paths = options.get_custom_paths()
563
564 test_pathname = os.path.join(self.tempdir, 'foo')
565
566 # Check that custom cleaner doesn't iterate non-existent object
567 for obj_type in ('folder', 'file'):
568 options.set_custom_paths([(obj_type, test_pathname)])
569 for cmd in backends['system'].get_commands('custom'):
570 results = list(cmd.execute(really_delete=False))
571 self.assertEqual(len(results), 0)
572
573 # Create the file
574 common.touch_file(test_pathname)
575 self.assertExists(test_pathname)
576
577 # Check it returns the file now
578 for cmd in backends['system'].get_commands('custom'):
579 results = list(cmd.execute(really_delete=False))
580 self.assertEqual(len(results), 1)
581 self.assertEqual(results[0]['path'], test_pathname)
582
583 # Prepare an empty folder.
584 test_dirname = os.path.join(self.tempdir, 'subdir')
585 os.makedirs(test_dirname)
586 self.assertExists(test_dirname)
587 options.set_custom_paths([('folder', test_dirname)])
588
589 # Check it returns the folder now.
590 for cmd in backends['system'].get_commands('custom'):
591 results = list(cmd.execute(really_delete=False))
592 self.assertEqual(len(results), 1)
593 self.assertEqual(results[0]['path'], test_dirname)
594
595 # Restore the original settings.
596 options.set_custom_paths(original_custom_paths)