Debian Codegraph @

tests/TestProtectedPath.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 Test case for module ProtectedPath
9 """
10
11 import os
12 import tempfile
13 import unittest
14 from unittest import mock
15
16 from functools import wraps
17
18 from tests import common
19 from bleachbit.ProtectedPath import (
20 _check_exempt,
21 _get_protected_path_xml,
22 calculate_impact,
23 check_protected_path,
24 clear_cache,
25 get_warning_message,
26 load_protected_paths)
27 from bleachbit import ProtectedPath as protected_path_module
28 from bleachbit import get_share_path
29 from bleachbit import IS_MAC, IS_WINDOWS, IS_POSIX
30 from bleachbit.PathUtils import (
31 expand_path,
32 normalize_path,
33 path_has_relative_suffix,
34 )
35 from bleachbit.Cleaner import backends
36 from tests.TestCleaner import register_all_cleaners
37
38
39 CASE_METHODS = (
40 str.lower,
41 str.upper,
42 str.title,
43 str.swapcase,
44 lambda x: x)
45
46
47 def requirePPXML(test_func):
48 """Decorator to skip test if protected path XML is not found"""
49 @wraps(test_func)
50 def wrapper(self):
51 if not _get_protected_path_xml():
52 self.skipTest('Protected path XML not found')
53 return test_func(self)
54 return wrapper
55
56
57 class ProtectedPathTestCase(common.BleachbitTestCase):
58 """Test case for ProtectedPath module"""
59
60 def setUp(self):
61 """Call before each test method"""
62 super().setUp()
63 clear_cache()
64
65 def tearDown(self):
66 """Call after each test method"""
67 super().tearDown()
68 clear_cache()
69
70 def test_expand_path(self):
71 """Test expand_path function"""
72 # Test user home expansion
73 home = os.path.expanduser('~')
74 result = expand_path('~')
75 self.assertEqual(result, home)
76
77 # Test with subpath
78 result = expand_path('~/Documents')
79 expected = os.path.normpath(os.path.join(home, 'Documents'))
80 self.assertEqual(result, expected)
81
82 # Test environment variable expansion
83 with common.set_temporary_env('TEST_PROTECTED_PATH_VAR', '/test/path'):
84 if IS_WINDOWS:
85 result = expand_path('%TEST_PROTECTED_PATH_VAR%')
86 else:
87 result = expand_path('$TEST_PROTECTED_PATH_VAR')
88 self.assertEqual(result, os.path.normpath('/test/path'))
89
90 def test_normalize_path(self):
91 """Test normalize_path function"""
92 # Case sensitive
93 result = normalize_path('/Home/User', True)
94 self.assertIn('Home', result)
95
96 # Case insensitive
97 result = normalize_path('/Home/User', False)
98 self.assertEqual(result, result.lower())
99
100 def test_path_has_relative_suffix(self):
101 """Test path-component matching for relative protected paths"""
102 self.assertTrue(path_has_relative_suffix('/home/user/.git', '.git'))
103 self.assertTrue(path_has_relative_suffix('.git', '.git'))
104 self.assertFalse(path_has_relative_suffix(
105 '/home/user/not-git', '.git'))
106 self.assertFalse(path_has_relative_suffix(
107 '/home/user/.gitignore', '.git'))
108 self.assertTrue(path_has_relative_suffix(
109 '/home/user/.GIT', '.git', case_sensitive=False))
110
111 def test_get_protected_path_xml(self):
112 """Test that protected path XML file can be found"""
113 xml_path = get_share_path('protected_path.xml')
114 self.assertIsNotNone(
115 xml_path, 'protected_path.xml not found via get_share_path')
116 self.assertExists(xml_path)
117 xml_path2 = _get_protected_path_xml()
118 self.assertIsNotNone(xml_path2, 'Protected path XML not found')
119 self.assertExists(xml_path2)
120 self.assertTrue(xml_path2.endswith('protected_path.xml'))
121
122 @requirePPXML
123 def test_load_protected_paths(self):
124 """Test loading protected paths from XML"""
125 paths = load_protected_paths()
126 self.assertIsInstance(paths, list)
127 # Should have loaded some paths for current OS
128 self.assertGreater(len(paths), 0)
129
130 # Each path should have required keys
131 for ppath in paths:
132 self.assertIn('path', ppath)
133 self.assertIn('depth', ppath)
134 self.assertIn('case_sensitive', ppath)
135 self.assertIsInstance(ppath['path'], str)
136 self.assertTrue(isinstance(
137 ppath['depth'], int) or ppath['depth'] is None)
138 self.assertIsInstance(ppath['case_sensitive'], bool)
139
140 @requirePPXML
141 @common.skipIfWindows
142 def test_expand_path_entries_split_os_pathsep(self):
143 """Environment variables with os.pathsep values expand into multiple entries"""
144
145 share1 = f"/nonexistent_xdg_share1_{self._testMethodName}"
146 share2 = f"/nonexistent_xdg_share2_{self._testMethodName}"
147 expected_paths = [os.path.normpath(share1), os.path.normpath(share2)]
148 with common.set_temporary_env('XDG_DATA_DIRS', os.pathsep.join(expected_paths)):
149 clear_cache()
150 paths = load_protected_paths(force_reload=True)
151 matches = [pp['path']
152 for pp in paths if pp['path'] in expected_paths]
153 self.assertCountEqual(matches, expected_paths)
154
155 for candidate in expected_paths:
156 result = check_protected_path(candidate)
157 self.assertIsNotNone(result)
158 clear_cache()
159
160 def test_load_protected_paths_rejects_dtd(self):
161 """A protected_path.xml with a DTD is rejected (entity-expansion defense)"""
162 xml_str = (
163 '<?xml version="1.0"?>\n'
164 '<!DOCTYPE paths [ <!ENTITY x "y"> ]>\n'
165 '<paths/>\n')
166 fn = os.path.join(self.mkdtemp(prefix='bleachbit-protected-path-dtd'),
167 'protected_path.xml')
168 self.write_file(fn, text=xml_str)
169 with mock.patch.object(
170 protected_path_module, '_get_protected_path_xml',
171 return_value=fn):
172 paths = load_protected_paths(force_reload=True)
173 self.assertEqual(paths, [])
174
175 @requirePPXML
176 def test_load_protected_paths_caching(self):
177 """Test that protected paths are cached"""
178 paths1 = load_protected_paths()
179 paths2 = load_protected_paths()
180 # Should be the same object (cached)
181 self.assertIs(paths1, paths2)
182
183 # Force reload should return new list
184 paths3 = load_protected_paths(force_reload=True)
185 self.assertIsNot(paths1, paths3)
186
187 @common.skipUnlessWindows
188 def test_check_exempt_windows(self):
189 """Test check_exempt() on Windows"""
190 temp_dir = expand_path('%temp%')
191 self.assertIsInstance(temp_dir, str)
192 self.assertGreater(len(temp_dir), 0)
193 for case_method in CASE_METHODS:
194 cased_temp_dir = case_method(temp_dir)
195 self.assertTrue(_check_exempt(cased_temp_dir),
196 f"Failed for {cased_temp_dir}")
197 cased_temp_dir += os.sep
198 self.assertTrue(_check_exempt(cased_temp_dir),
199 f"Failed for {cased_temp_dir}")
200 git_dir = os.path.join(temp_dir, '.git')
201 self.assertTrue(_check_exempt(git_dir),
202 f"Failed for {git_dir}")
203 git_dir += os.sep
204 self.assertTrue(_check_exempt(git_dir),
205 f"Failed for {git_dir}")
206
207 @common.skipIfWindows
208 def test_check_exempt_unix(self):
209 """Test check_exempt() on Unix"""
210 expect_exempt = (
211 '~/.cache',
212 '~/.cache/',
213 '~/.cache/.git',
214 '/tmp',
215 '/tmp/',
216 '/tmp/.git')
217 for path in expect_exempt:
218 expanded_path = expand_path(path)
219 self.assertTrue(_check_exempt(expanded_path), expanded_path)
220 # macOS is case-insensitive by default (FS_CASE_SENSITIVE is False
221 # on macOS), so an upper-cased exempt path is still exempt there.
222 # Linux is case-sensitive, so an upper-cased path is not exempt.
223 upper = expanded_path.upper()
224 if IS_MAC:
225 self.assertTrue(_check_exempt(upper), upper)
226 else:
227 self.assertFalse(_check_exempt(upper), expanded_path)
228 expect_not_exempt = (
229 '/',
230 '/home',
231 '/home/',
232 '~/.caches',
233 '~/.caches/',
234 '~/.caches/.git',
235 '~/Documents/',
236 '/tmps',
237 '/tmps/',
238 '/tmps/.git')
239 for path in expect_not_exempt:
240 self.assertFalse(_check_exempt(expand_path(path)), path)
241
242 def test_check_protected_path_no_match(self):
243 """Test check_protected_path with non-protected path"""
244 # A random temp path should not be protected
245 with tempfile.TemporaryDirectory() as tmpdir:
246 result = check_protected_path(tmpdir)
247 self.assertIsNone(result)
248 # Check .git (which is protected) under an exempt directory
249 exempt_dir_raw = None
250 if IS_POSIX:
251 exempt_dir_raw = '~/.cache'
252 elif IS_WINDOWS:
253 exempt_dir_raw = '%temp%'
254 else:
255 self.skipTest("Unsupported OS")
256 exempt_dir = expand_path(exempt_dir_raw)
257 self.assertIsInstance(exempt_dir, str)
258 self.assertTrue(_check_exempt(exempt_dir))
259 self.assertNotEqual(exempt_dir, exempt_dir_raw)
260 self.assertGreater(len(exempt_dir), 0)
261 result = check_protected_path(exempt_dir)
262 self.assertIsNone(result)
263 subpath = os.path.join(exempt_dir, '.git')
264 result = check_protected_path(subpath)
265 self.assertIsNone(result)
266 # ~/Documents/Zoom/recording.mp4 is not protected
267 zoom_path_raw = '~/Documents/Zoom/recording.mp4'
268 zoom_path = expand_path(zoom_path_raw)
269 self.assertNotEqual(zoom_path, zoom_path_raw)
270 result = check_protected_path(zoom_path)
271 self.assertIsNone(result)
272
273 @requirePPXML
274 def test_check_protected_path_exact_match(self):
275 """Test check_protected_path with exact match"""
276 home = os.path.expanduser('~')
277 home_result = check_protected_path(home)
278 documents_path = os.path.expanduser('~/Documents')
279 documents_result = check_protected_path(documents_path)
280 for result in (home_result, documents_result):
281 self.assertIsNotNone(result)
282 self.assertIn('path', result)
283 self.assertIn('depth', result)
284
285 @requirePPXML
286 def test_check_protected_path_child_match(self):
287 """Test check_protected_path with child of protected path
288
289 If /home/foo/.mozilla is protected with depth 1, adding /home/foo/.mozilla/firefox
290 should also warn because it is a child of the protected directory.
291 """
292 # If home is protected with depth > 0, children should match
293 paths = load_protected_paths()
294
295 # Find a protected path with depth > 0
296 for ppath in paths:
297 if ppath['depth'] > 0:
298 child_path = os.path.join(ppath['path'], 'test_subdir')
299 result = check_protected_path(child_path)
300 if result is not None:
301 self.assertGreater(result['depth'], 0)
302 break
303
304 @requirePPXML
305 def test_check_protected_path_parent_match(self):
306 """Test that parent of protected path triggers warning
307
308 If /home/foo/.mozilla is protected with any depth, adding /home/foo
309 should also warn because it is a parent containing the protected path.
310
311 """
312 paths = load_protected_paths()
313 if not paths:
314 self.skipTest("No protected paths loaded")
315
316 # Find a protected path that has a parent directory
317 for ppath in paths:
318 protected = ppath['path']
319 parent = os.path.dirname(protected)
320 if parent and parent != protected:
321 result = check_protected_path(parent)
322 # Parent should match because it contains protected path
323 if result is not None:
324 self.assertIsNotNone(result)
325 break
326
327 @requirePPXML
328 def test_check_protected_path_git_variations(self):
329 """Test that .git entries are detected at various nesting levels"""
330 git_paths = [
331 '/home/test/.git',
332 '/home/test/bleachbit/.git',
333 '/home/test/projects/bleachbit/.git',
334 ]
335
336 for path in git_paths:
337 result = check_protected_path(path)
338 self.assertIsNotNone(result, msg=f"Expected .git match for {path}")
339 self.assertEqual(result['path'], '.git')
340
341 @requirePPXML
342 def test_check_protected_path_desktop_suffix(self):
343 """Ensure Desktop.old variants do not match Desktop protected entry"""
344 desktop = os.path.expanduser('~/Desktop')
345 paths = [
346 desktop + '.old',
347 os.path.join(desktop + '.old', 'photo.jpg'),
348 ]
349
350 for path in paths:
351 result = check_protected_path(path)
352 self.assertIsNone(
353 result, msg=f"Unexpected Desktop match for {path}")
354
355 def test_calculate_impact_nonexistent(self):
356 """Test calculate_impact with non-existent path"""
357 result = calculate_impact('/nonexistent/path/12345')
358 self.assertEqual(result['file_count'], 0)
359 self.assertEqual(result['total_size'], 0)
360 self.assertEqual(result['size_human'], '0B')
361
362 def test_calculate_impact_file(self):
363 """Test calculate_impact with a file"""
364 with tempfile.NamedTemporaryFile(delete=False, dir=self.tempdir) as f:
365 f.write(b'x' * 1000)
366 temp_path = f.name
367
368 try:
369 result = calculate_impact(temp_path)
370 self.assertEqual(result['file_count'], 1)
371 self.assertGreaterEqual(result['total_size'], 1000)
372 self.assertIsInstance(result['size_human'], str)
373 finally:
374 os.unlink(temp_path)
375
376 def test_calculate_impact_directory(self):
377 """Test calculate_impact with a directory"""
378 with tempfile.TemporaryDirectory() as tmpdir:
379 # Create some test files
380 for i in range(5):
381 filepath = os.path.join(tmpdir, f'file{i}.txt')
382 with open(filepath, 'w', encoding='utf-8') as f:
383 f.write('x' * 100)
384
385 result = calculate_impact(tmpdir)
386 self.assertEqual(result['file_count'], 5)
387 self.assertGreaterEqual(result['total_size'], 500)
388 self.assertIsInstance(result['size_human'], str)
389
390 def test_calculate_impact_nested_directory(self):
391 """Test calculate_impact with nested directories"""
392 with tempfile.TemporaryDirectory() as tmpdir:
393 # Create nested structure
394 subdir = os.path.join(tmpdir, 'subdir')
395 os.makedirs(subdir)
396
397 # Files in root
398 with open(os.path.join(tmpdir, 'root.txt'), 'w', encoding='utf-8') as f:
399 f.write('x' * 100)
400
401 # Files in subdir
402 with open(os.path.join(subdir, 'sub.txt'), 'w', encoding='utf-8') as f:
403 f.write('x' * 200)
404
405 result = calculate_impact(tmpdir)
406 self.assertEqual(result['file_count'], 2)
407 self.assertGreaterEqual(result['total_size'], 300)
408
409 def test_get_warning_message(self):
410 """Test get_warning_message function"""
411 impact = {
412 'file_count': 10,
413 'total_size': 1024000,
414 'size_human': '1MB',
415 }
416
417 msg = get_warning_message('/home/user', impact)
418 self.assertIsInstance(msg, str)
419 self.assertIn('/home/user', msg)
420 self.assertIn('10', msg) # file count
421 self.assertIn('1MB', msg) # size
422
423 def test_get_warning_message_no_files(self):
424 """Test get_warning_message with no files"""
425 impact = {
426 'file_count': 0,
427 'total_size': 0,
428 'size_human': '0B',
429 }
430
431 msg = get_warning_message('/some/path', impact)
432 self.assertIsInstance(msg, str)
433 self.assertIn('/some/path', msg)
434
435 @requirePPXML
436 def test_clear_cache(self):
437 """Test clear_cache function"""
438 # Load to populate cache
439 load_protected_paths()
440 self.assertIsNotNone(protected_path_module._protected_paths_cache)
441
442 # Clear cache
443 clear_cache()
444 self.assertIsNone(protected_path_module._protected_paths_cache)
445
446 @requirePPXML
447 def test_preview_all(self):
448 """Check whether any real cleaners return protected paths"""
449 register_all_cleaners()
450
451 def check_option(co_key, co_option_id):
452 for cmd in backends[co_key].get_commands(co_option_id):
453 try:
454 for ret in cmd.execute(False): # False = preview mode
455 if isinstance(ret, dict) and ret.get('path'):
456 path = ret['path']
457 result = check_protected_path(path)
458 if result is not None:
459 print(
460 f'warning: {path} is protected by {result}')
461 return
462 except Exception:
463 continue
464 option_counter = 0
465 for key in sorted(backends):
466 # loop over cleaners
467 for (option_id, _option_name) in backends[key].get_options():
468 # loop over options
469 check_option(key, option_id)
470 option_counter += 1
471 print(f'checked {option_counter} options')
472
473 @requirePPXML
474 def test_path_with_trailing_slash(self):
475 """Test that paths with trailing slashes are handled correctly"""
476 home = os.path.expanduser('~')
477 home_with_slash = home + os.sep
478
479 result1 = check_protected_path(home)
480 result2 = check_protected_path(home_with_slash)
481 self.assertIsNotNone(result1)
482 self.assertIsNotNone(result2)
483 self.assertEqual(result1['path'], result2['path'])
484
485 @requirePPXML
486 @common.skipUnlessWindows
487 def test_case_insensitive_windows(self):
488 """Test case-insensitive matching on Windows"""
489 profile_var = r'%userprofile%'
490 profile = os.path.expandvars(profile_var)
491 self.assertNotEqual(profile, profile_var)
492 for case_method in CASE_METHODS:
493 # the whole path is case-insensitive
494 cased_profile = case_method(profile)
495 self.assertIsNotNone(check_protected_path(cased_profile))
496
497 @requirePPXML
498 def test_case_insensitive(self):
499 """Test case insensitive cross platform"""
500 home = os.path.expanduser('~')
501 self.assertIsInstance(home, str)
502 protected_base = os.path.join(home, 'Desktop')
503 for case_method in CASE_METHODS:
504 fname = 'thesis.pdf'
505 check_path = os.path.join(protected_base, case_method(fname))
506 result = check_protected_path(check_path)
507 self.assertIsNotNone(
508 result, f'Failed to find protected path for {check_path}: {result}')
509 self.assertEqual(result['path'].lower(), protected_base.lower())
510
511
512 if __name__ == '__main__':
513 unittest.main()