Debian Codegraph @

tests/TestFileUtilities.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 FileUtilities
9 """
10
11 # standard library
12 import codecs
13 import contextlib
14 import ctypes
15 import errno
16 import itertools
17 import json
18 import locale
19 import os
20 import sqlite3
21 import stat
22 import subprocess
23 import sys
24 import tempfile
25 import time
26 import unittest.mock
27 import warnings
28
29 # third-party import
30 import psutil
31
32 from tests.common import pytest
33
34 # local import
35 from bleachbit.FileUtilities import (
36 _remove_windows_readonly,
37 _truncate_locked_file,
38 bytes_to_human,
39 children_in_directory,
40 clean_ini,
41 clean_json,
42 delete_file,
43 delete,
44 detect_encoding,
45 ego_owner,
46 exe_exists,
47 execute_sqlite3,
48 exists_in_path,
49 expand_glob_join,
50 extended_path_undo,
51 extended_path,
52 free_space,
53 get_filesystem_type,
54 getsize,
55 getsizedir,
56 globex,
57 guess_overwrite_paths,
58 human_to_bytes,
59 is_dir_empty,
60 is_hard_link,
61 is_normal_directory,
62 listdir,
63 open_files_lsof,
64 OpenFiles,
65 same_partition,
66 truncate_file,
67 uris_to_paths,
68 vacuum_sqlite3,
69 whitelisted
70 )
71 from bleachbit.General import gc_collect, run_external
72 from bleachbit.Options import init_configuration, options
73 from bleachbit import logger, FS_CASE_SENSITIVE, IS_POSIX, IS_WINDOWS
74 from tests import common
75
76
77 if IS_WINDOWS:
78 # pylint: disable=import-error
79 import win32api
80 import win32com.shell
81 import win32con
82 import win32file
83
84 from bleachbit import Windows
85 from tests.TestWindows import WindowsLinksMixIn
86 else:
87 WindowsLinksMixIn = object
88
89
90 def ini_helper(self, execute):
91 """Used to test .ini cleaning in TestAction and in TestFileUtilities"""
92
93 teststr = '#Test\n[RecentsMRL]\nlist=C:\\Users\\me\\Videos\\movie.mpg,C:\\Users\\me\\movie2.mpg\n'
94 for encoding in ['utf-8', 'utf-8-sig']:
95 with self.subTest(encoding=encoding):
96 bom_size = 3 if 'utf-8-sig' == encoding else 0
97 extra_size = bom_size
98 if IS_WINDOWS:
99 extra_size += teststr.count('\n')
100
101 # create test file
102 filename = self.write_file(
103 'bleachbit-test-ini', teststr, mode='w', encoding=encoding)
104 self.assertExists(filename)
105 size = os.path.getsize(filename)
106 self.assertEqual(len(teststr) + extra_size, size)
107
108 # The section does not exist, so no change.
109 execute(filename, 'Recents', None)
110 self.assertEqual(len(teststr) + extra_size,
111 os.path.getsize(filename))
112
113 # The parameter does not exist, so no change.
114 execute(filename, 'RecentsMRL', 'files')
115 self.assertEqual(len(teststr) + extra_size,
116 os.path.getsize(filename))
117
118 # The parameter does exist, so the file shrinks.
119 # Comments are not preserved, so only "[RecentsMRL]\n" (14
120 # bytes) remains. The BOM is preserved, so utf-8-sig files
121 # are 17 bytes and plain utf-8 files are 14 bytes. clean_ini
122 # writes with newline='' so there is no \r\n expansion.
123 execute(filename, 'RecentsMRL', 'list')
124 self.assertEqual(14 + bom_size, os.path.getsize(filename))
125
126 # The section does exist, so the file shrinks.
127 execute(filename, 'RecentsMRL', None)
128 self.assertEqual(0, os.path.getsize(filename))
129
130 # clean up
131 delete(filename)
132 self.assertNotExists(filename)
133
134
135 def json_helper(self, execute):
136 """Used to test JSON cleaning in TestAction and in TestFileUtilities"""
137
138 def load_js(js_fn):
139 with open(js_fn, 'r', encoding='utf-8') as js_fd:
140 return json.load(js_fd)
141
142 expected = {'deleteme': 1, 'spareme': {'deletemetoo': 1}}
143
144 # create test file
145 (fd, filename) = tempfile.mkstemp(
146 prefix='bleachbit-test-json', dir=self.tempdir)
147 os.write(fd, b'{ "deleteme" : 1, "spareme" : { "deletemetoo" : 1 } }')
148 os.close(fd)
149 self.assertExists(filename)
150 self.assertEqual(load_js(filename), expected)
151
152 # invalid key
153 execute(filename, 'doesnotexist')
154 self.assertEqual(load_js(filename), expected)
155
156 # invalid key
157 execute(filename, 'deleteme/doesnotexist')
158 self.assertEqual(load_js(filename), expected)
159
160 # valid key
161 execute(filename, 'deleteme')
162 self.assertEqual(load_js(filename), {'spareme': {'deletemetoo': 1}})
163
164 # valid key
165 execute(filename, 'spareme/deletemetoo')
166 self.assertEqual(load_js(filename), {'spareme': {}})
167
168 # valid key
169 execute(filename, 'spareme')
170 self.assertEqual(load_js(filename), {})
171
172 # clean up
173 delete(filename)
174 self.assertNotExists(filename)
175
176
177 def _is_child_path(parent_path, child_path):
178 """Check whether child_path is a child of parent_path."""
179 parent = os.path.abspath(parent_path)
180 child = os.path.abspath(child_path)
181 return os.path.commonpath([parent]) == os.path.commonpath([parent, child])
182
183
184 def _open_blocking_handle(path, share_mode):
185 """Open a file handle with the given share mode to block other processes.
186
187 Args:
188 path: Path to the file to open
189 share_mode: Windows share mode (e.g., win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE)
190 Returns:
191 File handle that blocks other processes from accessing the file
192 """
193 return win32file.CreateFile(
194 path,
195 win32con.GENERIC_READ | win32con.GENERIC_WRITE,
196 share_mode,
197 None,
198 win32con.OPEN_ALWAYS,
199 win32con.FILE_ATTRIBUTE_NORMAL,
200 None,
201 )
202
203
204 class FileUtilitiesTestCase(common.BleachbitTestCase, WindowsLinksMixIn):
205 """Test case for module FileUtilities"""
206
207 def setUp(self):
208 """Call before each test method"""
209 super().setUp()
210 self.old_locale_tuple = locale.getlocale(locale.LC_NUMERIC)
211 self.old_locale_str = locale.setlocale(locale.LC_NUMERIC)
212 locale.setlocale(locale.LC_NUMERIC, 'C')
213 init_configuration(log=False)
214
215 def tearDown(self):
216 """Call after each test method"""
217 super().tearDown()
218 if self.old_locale_tuple == (None, None):
219 locale.setlocale(locale.LC_NUMERIC, 'C')
220 return
221 try:
222 try:
223 locale.setlocale(locale.LC_NUMERIC, self.old_locale_str)
224 except locale.Error:
225 if self.old_locale_tuple[0] is None:
226 locale.setlocale(locale.LC_NUMERIC, None)
227 else:
228 try:
229 # First try with the full locale string
230 locale.setlocale(locale.LC_NUMERIC, '.'.join(
231 filter(None, self.old_locale_tuple)))
232 except locale.Error:
233 # If that fails, try just the language code part
234 try:
235 locale.setlocale(
236 locale.LC_NUMERIC, self.old_locale_tuple[0])
237 except locale.Error as e:
238 print(
239 "Failed to restore locale with just language code "
240 f"{self.old_locale_tuple[0]}: {e}")
241 except locale.Error as e:
242 print(f"Failed to restore locale {self.old_locale_tuple}: {e}")
243 # Check that running getlocale again does not raise an exception.
244 # For me, getlocale() fails after successful setlocale(..., 'en_MX') on Windows.
245 locale.getlocale(locale.LC_NUMERIC)
246 self.assertEqual(locale.setlocale(
247 locale.LC_NUMERIC), self.old_locale_str)
248
249 def test_bytes_to_human_one_way(self):
250 """Test one-way conversion of bytes_to_human()"""
251
252 # Test one-way conversion for predefined values
253 # Each test is a tuple in the format: (bytes, SI, EIC)
254 tests = ((-1, '-1B', '-1B'),
255 (0, '0B', '0B'),
256 (1, '1B', '1B'),
257 (1000, '1kB', '1000B'),
258 (1024, '1kB', '1KiB'),
259 (1110, '1.1kB', '1.1KiB'),
260 (1000**2, '1MB', '976.6KiB'),
261 (1024**2, '1MB', '1MiB'),
262 (1289748, '1.3MB', '1.2MiB'),
263 (1000**3, '1GB', '953.7MiB'),
264 (1024**3, '1.07GB', '1GiB'),
265 (1320702444, '1.32GB', '1.23GiB'),
266 (1000**4, '1TB', '931.32GiB'),
267 (1024**4, '1.1TB', '1TiB'),
268 (1000**5, '1PB', '909.49TiB'),
269 (1024**5, '1.13PB', '1PiB'))
270
271 options.set('units_iec', True)
272 for test in tests:
273 iec = bytes_to_human(test[0])
274 self.assertEqual(test[2], iec,
275 f"bytes_to_human({test[0]}) IEC = {iec}"
276 f" but expected {test[2]}")
277
278 options.set('units_iec', False)
279 for test in tests:
280 si = bytes_to_human(test[0])
281 self.assertEqual(test[1], si,
282 f"bytes_to_human({test[0]}) SI = {si}"
283 f" but expected {test[1]}")
284
285 def test_bytes_to_human_roundtrip(self):
286 """Test roundtrip conversion of bytes_to_human()
287
288 Example: 1,175,818 -> 1.2MB -> 1,200,000 is 2.06% different,
289 but only 24,182 bytes, within half of the displayed 0.1MB step.
290 """
291 old_iec = options.get('units_iec')
292 for units_iec in (False, True):
293 options.set('units_iec', units_iec)
294 base = 1024 if units_iec else 1000
295 for k in range(0, 6):
296 step = base ** k
297 decimals = 2 if k >= 3 else (1 if k >= 1 else 0)
298 half_step = 0.5 * 10 ** -decimals * step
299 for frac in (1.0, 1.049, 1.05, 2.5, 7.5, 9.994, 9.995):
300 for delta in (-1, 0, 1):
301 bytes1 = int(frac * step) + delta
302 if bytes1 <= 0:
303 continue
304 human = bytes_to_human(bytes1)
305 if units_iec:
306 bytes2 = human_to_bytes(
307 human.replace('i', ''), 'du')
308 else:
309 bytes2 = human_to_bytes(human)
310 self.assertLessEqual(
311 abs(bytes2 - bytes1), half_step + 1,
312 f"{bytes1:,} -> {human} -> {bytes2:,} exceeds "
313 f"half a display unit ({half_step:,.0f})")
314 options.set('units_iec', old_iec)
315
316 def test_bytes_to_human_localization(self):
317 """Test localization of bytes_to_human()"""
318 if not hasattr(locale, 'format_string'):
319 self.skipTest('Locale module does not support format_string')
320 old_locale = locale.setlocale(locale.LC_NUMERIC, None)
321 try:
322 locale.setlocale(locale.LC_NUMERIC, 'de_DE.utf8')
323 except locale.Error as e:
324 logger.warning('exception when setlocale to de_DE.utf8: %s', e)
325 else:
326 try:
327 self.assertEqual("1,01GB", bytes_to_human(1000 ** 3 + 5812389))
328 finally:
329 locale.setlocale(locale.LC_NUMERIC, old_locale)
330
331 def test_children_in_directory(self):
332 """Unit test for function children_in_directory()"""
333
334 # test an existing directory that usually exists
335 dirname = os.path.expanduser("~/.config")
336 for filename in children_in_directory(dirname, True):
337 self.assertTrue(os.path.isabs(filename))
338 for filename in children_in_directory(dirname, False):
339 self.assertTrue(os.path.isabs(filename))
340 self.assertFalse(os.path.isdir(filename))
341 self.assertFalse(is_normal_directory(filename))
342
343 # test a constructed file in a constructed directory
344 dirname = self.mkdtemp(prefix='bleachbit-test-children')
345 filename = self.mkstemp(prefix="somefile", dir=dirname)
346 for loopfilename in children_in_directory(dirname, True):
347 self.assertEqual(loopfilename, filename)
348 for loopfilename in children_in_directory(dirname, False):
349 self.assertEqual(loopfilename, filename)
350 os.remove(filename)
351
352 # test subdirectory
353 subdirname = os.path.join(dirname, "subdir")
354 self.mkdir(subdirname)
355 for filename in children_in_directory(dirname, True):
356 self.assertEqual(filename, subdirname)
357 for filename in children_in_directory(dirname, False):
358 raise AssertionError(
359 'Found a file that shouldn\'t have been found: ' + filename)
360 os.rmdir(subdirname)
361
362 os.rmdir(dirname)
363
364 def test_children_in_directory_ordering(self):
365 """Verify children_in_directory yields files before their parent directories.
366
367 Regression test: with sibling directories, a dir could appear in the
368 output before files contained inside it, causing rmdir to fail on a
369 non-empty directory.
370
371 Tree:
372 root/
373 file_root.txt
374 sub1/
375 file1.txt
376 nested/
377 file_nested.txt
378 sub2/
379 file2.txt
380 """
381 root = self.mkdir('directory-order-root') # relative to self.tempdir
382 sub1 = self.mkdir(os.path.join(root, 'sub1'))
383 nested = self.mkdir(os.path.join(sub1, 'nested'))
384 sub2 = self.mkdir(os.path.join(root, 'sub2'))
385
386 file_root = self.mkstemp(prefix='file_root', dir=root)
387 file1 = self.mkstemp(prefix='file1', dir=sub1)
388 file_nested = self.mkstemp(prefix='file_nested', dir=nested)
389 file2 = self.mkstemp(prefix='file2', dir=sub2)
390
391 children = list(children_in_directory(root, list_directories=True))
392 expected = [file_root, file1, file_nested, file2, sub1, nested, sub2]
393 self.assertCountEqual(children, expected)
394
395 idx = {p: children.index(p)
396 for p in expected}
397
398 self.assertLess(idx[file1], idx[sub1],
399 'file1 must appear before sub1')
400 self.assertLess(idx[file_nested], idx[nested],
401 'file_nested must appear before nested')
402 self.assertLess(idx[nested], idx[sub1],
403 'nested must appear before sub1')
404 self.assertLess(idx[file2], idx[sub2],
405 'file2 must appear before sub2')
406 for child in children:
407 if os.path.isdir(child):
408 self.assertTrue(is_dir_empty(child),
409 f'{child} must be empty before deletion')
410 self.assertTrue(delete(child))
411 self.assertTrue(delete(root))
412 self.assertNotExists(root)
413
414 def test_children_in_directory_scandir_unreadable_mid_iteration(self):
415 """Regression test: a directory becoming unreadable mid-iteration
416 must not abort the whole cleanup.
417
418 os.walk silently skips directories that turn unreadable while being
419 listed; _scan_children must do the same instead of propagating the
420 OSError/PermissionError from the scandir iterator.
421 """
422 root = self.mkdir('scandir-unreadable-root')
423 self.mkstemp(prefix='file_before', dir=root)
424
425 class _FakeEntry:
426 def __init__(self, path, is_dir=False):
427 self.path = path
428 self._is_dir = is_dir
429
430 def is_dir(self):
431 return self._is_dir
432
433 def is_symlink(self):
434 return False
435
436 class _RaisingScandir:
437 """Yields one file entry, then raises PermissionError mid-iteration."""
438
439 def __init__(self, first_entry):
440 self._first = first_entry
441
442 def __iter__(self):
443 return self
444
445 def __next__(self):
446 if self._first is None:
447 raise PermissionError('simulated mid-iteration failure')
448 entry = self._first
449 self._first = None
450 return entry
451
452 def __enter__(self):
453 return self
454
455 def __exit__(self, *exc):
456 return False
457
458 first_entry = _FakeEntry(os.path.join(
459 root, 'file_before'), is_dir=False)
460 with unittest.mock.patch(
461 'bleachbit.FileUtilities.os.scandir',
462 return_value=_RaisingScandir(first_entry)):
463 # Must not raise; entries yielded before the failure are kept.
464 results = list(children_in_directory(root, list_directories=False))
465 self.assertEqual(results, [os.path.join(root, 'file_before')])
466
467 def test_children_in_directory_deep_tree(self):
468 """Regression test: a deeply nested tree must not exhaust the
469 recursion limit.
470
471 A recursive walk raises RecursionError past about 1000 levels, which
472 would abort the cleanup and leave the remaining files behind. os.scandir
473 is faked so the depth is not capped by the platform's maximum path
474 length.
475 """
476 depth = 5000
477
478 class _FakeEntry:
479 def __init__(self, path, is_dir):
480 self.path = path
481 self._is_dir = is_dir
482
483 def is_dir(self):
484 return self._is_dir
485
486 def is_symlink(self):
487 return False
488
489 def is_junction(self):
490 return False
491
492 class _FakeScandir:
493 def __init__(self, entries):
494 self._entries = entries
495
496 def __iter__(self):
497 return iter(self._entries)
498
499 def __enter__(self):
500 return self
501
502 def __exit__(self, *exc):
503 return False
504
505 # One subdirectory per level, with a single file at the bottom
506 root = 'deep-tree-root'
507 tree = {}
508 path = root
509 for _ in range(depth):
510 child = os.path.join(path, 'a')
511 tree[path] = [_FakeEntry(child, True)]
512 path = child
513 deep_file = os.path.join(path, 'deepfile')
514 tree[path] = [_FakeEntry(deep_file, False)]
515
516 with unittest.mock.patch('bleachbit.FileUtilities.os.scandir',
517 side_effect=lambda p: _FakeScandir(tree[p])):
518 results = list(children_in_directory(root, list_directories=True))
519
520 self.assertEqual(len(results), depth + 1)
521 # The file comes first, then the directories, deepest first
522 self.assertEqual(results[0], deep_file)
523 self.assertEqual(results[1], path)
524 self.assertEqual(results[-1], os.path.join(root, 'a'))
525
526 @common.skipIfWindows
527 def test_children_in_directory_posix_symlink(self):
528 """POSIX: ensure directory symlinks are not followed"""
529
530 base_dir = self.mkdir('children-symlink-primary')
531
532 # Real directory inside base for normal traversal
533 real_dir = os.path.join(base_dir, 'real-dir')
534 self.mkdir(real_dir)
535 real_file = self.mkstemp(prefix='real-file-', dir=real_dir)
536
537 # Symlink inside base pointing outside of base_dir
538 external_target = self.mkdir('children-symlink-external')
539 external_file = self.mkstemp(
540 prefix='external-file-', dir=external_target)
541 self.assertExists(external_target)
542 self.assertExists(external_file)
543 link_dir = os.path.join(base_dir, 'linked-dir')
544 os.symlink(external_target, link_dir)
545 self.assertExists(link_dir)
546 self.assertFalse(is_normal_directory(link_dir))
547
548 # list_directories=True should yield the link itself but not descend
549 entries_with_dirs = list(children_in_directory(base_dir, True))
550 self.assertIn(link_dir, entries_with_dirs)
551 self.assertIn(real_file, entries_with_dirs)
552 self.assertIn(real_dir, entries_with_dirs)
553 self.assertEqual(len(entries_with_dirs), 3)
554
555 # list_directories=False should only yield the real file
556 entries_files_only = list(children_in_directory(base_dir, False))
557 self.assertEqual(entries_files_only, [real_file])
558 self.assertEqual(len(entries_files_only), 1)
559
560 @common.skipIfWindows
561 def test_children_in_directory_posix_circular_symlink(self):
562 """POSIX: ensure circular directory symlinks are not followed"""
563
564 base_dir = self.mkdir('children-circular-')
565
566 # Create a normal directory and file inside the base directory
567 real_dir = os.path.join(base_dir, 'real-dir')
568 self.mkdir(real_dir)
569 real_file = self.mkstemp(prefix='real-file-', dir=real_dir)
570
571 # Symlink inside base pointing back to base_dir to create circular reference
572 loop_link = os.path.join(base_dir, 'loop-link')
573 os.symlink(base_dir, loop_link)
574 self.assertExists(loop_link)
575 self.assertFalse(is_normal_directory(loop_link))
576
577 entries_with_dirs = list(children_in_directory(base_dir, True))
578 self.assertIn(loop_link, entries_with_dirs)
579 self.assertIn(real_file, entries_with_dirs)
580 self.assertIn(real_dir, entries_with_dirs)
581 self.assertEqual(len(entries_with_dirs), 3)
582
583 entries_files_only = list(children_in_directory(base_dir, False))
584 self.assertEqual(entries_files_only, [real_file])
585 self.assertEqual(len(entries_files_only), 1)
586
587 @common.skipUnlessWindows
588 def test_children_in_directory_windows_links(self):
589 """Windows: ensure symlinked dirs and junctions are not followed"""
590
591 base_dir = self.mkdir('children-links')
592
593 # Regular directory to confirm normal traversal still works
594 normal_dir = os.path.join(base_dir, 'normal-dir')
595 self.mkdir(normal_dir)
596 normal_file = os.path.join(normal_dir, 'normal-file')
597 common.touch_file(normal_file)
598 self.assertExists(normal_file)
599
600 # Symlink target lives outside base_dir
601 symlink_target = self.mkdir('children-symlink-target')
602 symlink_target_file = self.mkstemp(
603 prefix='symlink-target-file-', dir=symlink_target)
604 symlink_path = os.path.join(base_dir, 'symlinked-dir')
605 try:
606 self._create_win_dir_symlink(symlink_target, symlink_path)
607 except OSError as exc:
608 self.skipTest(f'Cannot create Windows directory symlink: {exc}')
609 self.assertFalse(is_hard_link(symlink_target))
610 self.assertFalse(is_hard_link(symlink_path))
611 self.assertFalse(is_normal_directory(symlink_path))
612 self.assertTrue(is_normal_directory(symlink_target))
613
614 # Junction target lives outside base_dir
615 junction_target = self.mkdir('children-junction-target')
616 junction_target_file = self.mkstemp(
617 prefix='junction-target-file-', dir=junction_target)
618 junction_path = os.path.join(base_dir, 'junction-dir')
619 try:
620 self._create_win_junction(junction_target, junction_path)
621 except (OSError, subprocess.CalledProcessError) as exc:
622 self.skipTest(f'Cannot create Windows junction: {exc}')
623 self.assertFalse(is_hard_link(junction_target))
624 self.assertFalse(is_hard_link(junction_path))
625 self.assertFalse(is_normal_directory(junction_path))
626 self.assertTrue(is_normal_directory(junction_target))
627
628 entries_with_dirs = list(children_in_directory(base_dir, True))
629 entries_files_only = list(children_in_directory(base_dir, False))
630
631 self.assertIn(normal_file, entries_files_only)
632 for link_dir in (symlink_path, junction_path):
633 self.assertIn(link_dir, entries_with_dirs)
634 # There must be no children of the linked directories.
635 offending_paths = [
636 path for path in entries_with_dirs + entries_files_only
637 if _is_child_path(link_dir, path) and path != link_dir
638 ]
639 self.assertEqual(
640 offending_paths,
641 [],
642 f"Traversal into {link_dir} detected in children_in_directory results",
643 )
644
645 # Files living only behind the link targets should never appear
646 for hidden_file in (symlink_target_file, junction_target_file):
647 self.assertNotIn(hidden_file, entries_with_dirs)
648 self.assertNotIn(hidden_file, entries_files_only)
649
650 self.assertEqual(len(entries_with_dirs), 4)
651 self.assertEqual(len(entries_files_only), 1)
652
653 def test_clean_ini(self):
654 """Unit test for clean_ini()"""
655 for shred in (False, True):
656 with self.subTest(shred=shred):
657 options.set('shred', shred)
658 ini_helper(self, clean_ini)
659
660 def test_clean_ini_kde(self):
661 """Unit test for clean_ini() with KDE ini file
662
663 It was reading the colon as a delimiter, but now delimiters are limited to equals sign.
664 See https://github.com/bleachbit/bleachbit/issues/1902
665 """
666
667 ini_content_kfile = """
668 [KFileDialog Settings]
669 Recent Files[$e]=file:///run/media/AAA1/BBBBB/cccc_ddddddd.zip
670 Recent URLs[$e]=file:///run/media/AAA1/BBBBB/
671 """.lstrip()
672
673 ini_content_mainwindow = """
674 [MainWindow]
675 1680x1050 screen: Height=600
676 1680x1050 screen: Width=990
677 State=AAAA/wA...
678 """.lstrip()
679
680 path = os.path.join(self.tempdir, "arkstaterc")
681
682 tests = [
683 ("KFileDialog Settings", ini_content_mainwindow),
684 ("MainWindow", ini_content_kfile),
685 ]
686 for section, content in tests:
687 with open(path, "w", encoding="utf-8") as f:
688 f.write(ini_content_kfile + "\n" + ini_content_mainwindow)
689
690 clean_ini(path, section=section, parameter=None)
691
692 with open(path, "r", encoding="utf-8") as f:
693 cleaned_content = f.read()
694
695 self.assertEqual(
696 content.strip(), cleaned_content.strip().replace(" = ", "="))
697
698 def test_clean_json(self):
699 """Unit test for clean_json()"""
700 for shred in (False, True):
701 with self.subTest(shred=shred):
702 options.set('shred', shred)
703 json_helper(self, clean_json)
704
705 def test_clean_ini_refuses_symlink(self):
706 """clean_ini() must not write through a symlink to another file
707
708 With shred disabled, the original file is never deleted, so a
709 (simulated) symlink at its path must block the write and leave
710 the original content in place. With shred enabled, the original
711 is deleted first as usual, and the guard must then block the
712 symlinked path from being recreated.
713 """
714 content = '[Section]\nkey=value\n'
715
716 options.set('shred', False)
717 filename = self.write_file('clean_ini_target_noshred', text=content)
718 with unittest.mock.patch(
719 'bleachbit.FileUtilities.os.path.islink',
720 side_effect=lambda p: p == filename):
721 with self.assertRaises(OSError):
722 clean_ini(filename, 'Section', None)
723 with open(filename, encoding='utf-8') as f:
724 self.assertEqual(f.read(), content)
725
726 options.set('shred', True)
727 filename = self.write_file('clean_ini_target_shred', text=content)
728 with unittest.mock.patch(
729 'bleachbit.FileUtilities.os.path.islink',
730 side_effect=lambda p: p == filename):
731 with self.assertRaises(OSError):
732 clean_ini(filename, 'Section', None)
733 self.assertNotExists(filename)
734
735 def test_clean_json_refuses_symlink(self):
736 """clean_json() must not write through a symlink to another file
737
738 See test_clean_ini_refuses_symlink for why shred=True and
739 shred=False need different post-conditions.
740 """
741 content = '{"deleteme": 1, "keep": 2}'
742
743 options.set('shred', False)
744 filename = self.write_file('clean_json_target_noshred', text=content)
745 with unittest.mock.patch(
746 'bleachbit.FileUtilities.os.path.islink',
747 side_effect=lambda p: p == filename):
748 with self.assertRaises(OSError):
749 clean_json(filename, 'deleteme')
750 with open(filename, encoding='utf-8') as f:
751 self.assertEqual(f.read(), content)
752
753 options.set('shred', True)
754 filename = self.write_file('clean_json_target_shred', text=content)
755 with unittest.mock.patch(
756 'bleachbit.FileUtilities.os.path.islink',
757 side_effect=lambda p: p == filename):
758 with self.assertRaises(OSError):
759 clean_json(filename, 'deleteme')
760 self.assertNotExists(filename)
761
762 @pytest.mark.no_xdist
763 def test_delete(self):
764 """Unit test for method delete()"""
765 for shred in (False, True):
766 for delete_func in (delete, delete_file):
767 with self.subTest(delete_func=delete_func.__name__, shred=shred):
768 self.delete_helper(delete_func, shred=shred)
769
770 def test_delete_ignore_missing(self):
771 """Unit test for delete() with ignore_missing=True"""
772 self.assertFalse(delete('does-not-exist', ignore_missing=True))
773 self.assertRaises(OSError, delete, 'does-not-exist')
774
775 def test_delete_access_denied(self):
776 """delete() raises PermissionError on access denied"""
777 path = self.write_file('test_delete_access_denied', b'secret')
778 e = PermissionError(13, 'Access is denied', path)
779 if IS_WINDOWS:
780 e.winerror = 5
781 with unittest.mock.patch('os.remove', side_effect=e):
782 with self.assertRaises(PermissionError):
783 delete(path, shred=False)
784 self.assertExists(path)
785
786 def delete_helper(self, delete_func, shred):
787 """Called by test_delete() with shred = False and = True"""
788
789 # test deleting with various kinds of filenames
790 tests = common.SPECIAL_TEST_STRINGS.copy()
791 if IS_POSIX:
792 # Windows doesn't allow these characters but Unix systems do
793 tests += common.POSIX_SPECIAL_TEST_STRINGS
794 for test in tests:
795 # create the file
796 filename = self.write_file(test, b"top secret")
797 # delete the file
798 self.assertTrue(delete_func(filename, shred))
799 self.assertNotExists(filename)
800
801 # delete an empty directory
802 dirname = self.mkdtemp(prefix=test)
803 self.assertExists(dirname)
804 # delete_file() doesn't delete directories, so do not use delete_func.
805 self.assertTrue(delete(dirname, shred))
806 self.assertNotExists(dirname)
807
808 def symlink_helper(link_fn):
809 if IS_WINDOWS:
810 # pylint: disable=no-member
811 if not win32com.shell.shell.IsUserAnAdmin():
812 self.skipTest(
813 'skipping symlink test because of insufficient privileges')
814
815 # make regular file
816 srcname = self.mkstemp(prefix='bleachbit-test-delete-regular')
817
818 # make symlink
819 self.assertExists(srcname)
820 linkname = os.path.join(self.tempdir, 'bblink')
821 self.assertNotExists(linkname)
822 link_fn(srcname, linkname)
823 self.assertExists(linkname)
824 self.assertLExists(linkname)
825
826 # delete symlink
827 self.assertTrue(delete(linkname, shred))
828 self.assertExists(srcname)
829 self.assertNotLExists(linkname)
830
831 # delete regular file
832 self.assertTrue(delete(srcname, shred))
833 self.assertNotExists(srcname)
834
835 #
836 # test broken symlink
837 #
838 srcname = self.mkstemp(prefix='bleachbit-test-delete-sym')
839 self.assertLExists(srcname)
840 link_fn(srcname, linkname)
841 self.assertLExists(linkname)
842 self.assertExists(linkname)
843
844 # delete regular file first
845 self.assertTrue(delete(srcname, shred))
846 self.assertNotExists(srcname)
847 self.assertLExists(linkname)
848
849 # clean up
850 self.assertTrue(delete(linkname, shred))
851 self.assertNotExists(linkname)
852 self.assertNotLExists(linkname)
853
854 if IS_WINDOWS:
855 logger.debug('testing symbolic link')
856 kern = ctypes.windll.LoadLibrary("kernel32.dll")
857
858 def win_symlink(src, linkname):
859 rc = kern.CreateSymbolicLinkW(linkname, src, 0)
860 if rc == 0:
861 print(f'CreateSymbolicLinkW({linkname}, {src})')
862 print(
863 f'CreateSymbolicLinkW() failed, error = {ctypes.FormatError()}')
864 self.assertNotEqual(rc, 0)
865 symlink_helper(win_symlink)
866
867 # test empty directory on Windows
868 path = self.mkdtemp(prefix='bleachbit-test-delete-dir')
869 self.assertExists(path)
870 self.assertTrue(delete(path, shred))
871 self.assertNotExists(path)
872
873 return
874
875 # below this point, only posix
876
877 # test file with mode 0400/-r--------
878 filename = self.write_file('bleachbit-test-0400')
879 os.chmod(filename, 0o400)
880 self.assertTrue(delete(filename, shred))
881 self.assertNotExists(filename)
882
883 # test symlink
884 symlink_helper(os.symlink)
885
886 # test FIFO
887 args = ["mkfifo", filename]
888 ret = subprocess.call(args)
889 self.assertEqual(ret, 0)
890 self.assertExists(filename)
891 self.assertTrue(delete(filename, shred))
892 self.assertNotExists(filename)
893
894 # test directory
895 path = self.mkdtemp(prefix='bleachbit-test-delete-dir')
896 self.assertExists(path)
897 self.assertTrue(delete(path, shred))
898 self.assertNotExists(path)
899
900 @common.skipUnlessWindows
901 def test_delete_hidden(self):
902 """Unit test for delete() with hidden file"""
903 for shred in (False, True):
904 fn = os.path.join(self.tempdir, 'hidden')
905 common.touch_file(fn)
906 # pylint: disable=possibly-used-before-assignment, c-extension-no-member
907 win32api.SetFileAttributes(fn, win32con.FILE_ATTRIBUTE_HIDDEN)
908 self.assertExists(fn)
909 self.assertFalse(is_hard_link(fn))
910 self.assertFalse(is_normal_directory(fn))
911 self.assertTrue(delete(fn, shred=shred))
912 self.assertNotExists(fn)
913
914 @common.skipUnlessWindows
915 def test_delete_locked_file(self):
916 """Unit test for delete() with locked file"""
917 # set up
918 def test_delete_locked_setup(share_mode):
919 filename = self.write_file('locked.txt', text='123')
920 self.assertExists(filename)
921 self.assertEqual(3, getsize(filename))
922 handle = _open_blocking_handle(filename, share_mode)
923 self.assertFalse(is_hard_link(filename))
924 return filename, handle
925
926 # Each test is:
927 # (share_mode, delete_expected, truncate_expected)
928 # The overall outcomes in matrix:
929 # - file deleted (True, None)
930 # - file truncated but not deleted (False, True)
931 # - file not deleted and not truncated (False, False)
932 tests = [
933
934
935 (0, False, False), # exclusive
936
937 (win32con.FILE_SHARE_READ, False, False), # read-only sharing
938
939 (
940 win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
941 False,
942 True,
943 ),
944
945 (
946 win32con.FILE_SHARE_READ | win32con.FILE_SHARE_DELETE,
947 True,
948 None, # truncate not attempted
949 ),
950
951 (
952 win32con.FILE_SHARE_READ
953 | win32con.FILE_SHARE_WRITE
954 | win32con.FILE_SHARE_DELETE,
955 True,
956 None, # truncate not attempted
957 ),
958 ]
959
960 for (share_mode, delete_expected, truncate_expected), shred in itertools.product(tests, (False, True)):
961 with self.subTest(share_mode=share_mode, shred=shred):
962 filename, handle = test_delete_locked_setup(share_mode)
963
964 if delete_expected:
965 # Delete expected to suceed.
966 self.assertTrue(delete_file(filename, shred))
967 else:
968 # Delete expected to fail.
969 # pylint: disable=undefined-variable
970 with self.assertRaises(WindowsError):
971 delete_file(filename, shred)
972 win32file.CloseHandle(handle)
973 if delete_expected:
974 self.assertNotExists(filename)
975 else:
976 self.assertExists(filename)
977 self.assertIsNotNone(truncate_expected)
978 expected_size = 0 if truncate_expected else 3
979 self.assertEqual(expected_size, getsize(filename))
980 delete(filename)
981 self.assertNotExists(filename)
982
983 @common.skipIfWindows
984 @common.also_with_sudo
985 def test_delete_mount_point(self):
986 """Unit test for deleting a mount point in use"""
987 if not common.have_root():
988 self.skipTest('not enough privileges')
989 from_dir = self.mkdir('mount_from')
990 from_file = os.path.join(from_dir, 'normal-file')
991 common.touch_file(from_file)
992 to_dir = self.mkdir('mount_to')
993 args = ['mount', '--bind', from_dir, to_dir]
994 (rc, _, stderr) = run_external(args)
995 self.assertEqual(
996 rc, 0, f'error calling mount\nargs={args}\nstderr={stderr}')
997 try:
998 self.assertTrue(os.path.isdir(to_dir))
999 to_file = os.path.join(to_dir, 'normal-file')
1000 all_objs = (to_file, from_file, to_dir, from_dir)
1001 # os.path.isjunction() was added in Python 3.12, but BleachBit
1002 # supports older versions. Junctions are a Windows-only concept,
1003 # so on Linux the fallback always returns False.
1004 isjunction = getattr(os.path, 'isjunction', lambda _p: False)
1005 for func in (os.path.islink, isjunction, os.path.ismount, is_hard_link):
1006 for pathname in all_objs:
1007 self.assertFalse(func(pathname))
1008 # delete() should return False for a busy mount point
1009 ret = delete(to_dir)
1010 self.assertFalse(ret)
1011 # The mount point and its contents should still exist.
1012 for pathname in all_objs:
1013 self.assertExists(pathname)
1014 finally:
1015 args = ['umount', to_dir]
1016 (rc, _, stderr) = run_external(args)
1017 self.assertEqual(
1018 rc, 0, f'error calling umount\nargs={args}\nstderr={stderr}')
1019 self.assertNotExists(to_file)
1020
1021 def test_delete_not_empty(self):
1022 """Test for scenario directory is not empty"""
1023 # common.py puts bleachbit.ini in self.tempdir, but it may
1024 # not be flushed
1025 dirname = self.mkdir('a_dir')
1026 self.assertFalse(is_dir_empty(self.tempdir))
1027 self.assertTrue(is_dir_empty(dirname))
1028 fn = self.write_file(os.path.join(dirname, 'a_file'), b'content')
1029 self.assertFalse(is_dir_empty(dirname))
1030
1031 for path in (fn, dirname, self.tempdir):
1032 self.assertExists(path)
1033 self.assertFalse(is_hard_link(path))
1034
1035 # Make sure shredding does not leave a renamed directory like
1036 # in https://github.com/bleachbit/bleachbit/issues/783
1037 for allow_shred in (False, True):
1038 self.assertFalse(delete(dirname, allow_shred=allow_shred))
1039 self.assertExists(fn)
1040 self.assertExists(dirname)
1041 os.remove(fn)
1042 self.assertTrue(is_dir_empty(dirname))
1043
1044 def test_delete_read_only_file(self):
1045 """Unit test for delete() with read-only file"""
1046 for option_shred, parameter_shred, delete_func in itertools.product(
1047 [False, True], [False, True], [delete, delete_file]
1048 ):
1049 with self.subTest(option_shred=option_shred, parameter_shred=parameter_shred, delete_func=delete_func.__name__):
1050 shred = parameter_shred
1051 variation_dir = f"{option_shred}-{parameter_shred}-{delete_func.__name__}"
1052 options.set('shred', option_shred)
1053 # The directory is not read-only, but it used for the read-only test.
1054 tmp_dir = self.mkdtemp(prefix=f'read-only-dir_{variation_dir}')
1055 self.assertDirectoryCount(tmp_dir, 0)
1056
1057 fn = self.write_file(
1058 os.path.join(tmp_dir, f'read-only-file_{variation_dir}'),
1059 b'read-only content',
1060 )
1061 os.chmod(fn, stat.S_IREAD)
1062 self.assertExists(fn)
1063 self.assertFalse(is_hard_link(fn))
1064 self.assertDirectoryCount(tmp_dir, 1)
1065 try:
1066 delete_func(fn, shred=shred)
1067 except PermissionError as e:
1068 _remove_windows_readonly(fn)
1069 raise e
1070 self.assertNotExists(fn)
1071 self.assertDirectoryCount(tmp_dir, 0)
1072
1073 def test_delete_hard_link(self):
1074 """Unit test for delete() with hard link
1075
1076 - Tests both shredding and unlink.
1077 - Target is a file (not a directory).
1078 - Test is cross platform.
1079 """
1080 for shred in (False, True):
1081 with self.subTest(shred=shred):
1082 tmp_dir = self.mkdtemp(prefix=f'delete_hard_{shred}')
1083 target = self.write_file(
1084 os.path.join(tmp_dir, f'hardlink-target-{shred}-'),
1085 b'canary data',
1086 )
1087 self.assertDirectoryCount(tmp_dir, 1)
1088
1089 link = os.path.join(tmp_dir, f'hardlink-{shred}')
1090 os.link(target, link)
1091 self.assertExists(link)
1092 self.assertFalse(os.path.islink(link))
1093 self.assertTrue(os.path.isfile(link))
1094 if IS_WINDOWS:
1095 self.assertFalse(Windows.is_junction(link))
1096 self.assertDirectoryCount(tmp_dir, 2)
1097 self.assertTrue(is_hard_link(link))
1098 self.assertTrue(is_hard_link(target))
1099
1100 self.assertTrue(delete(link, shred=shred))
1101 self.assertNotExists(link)
1102 self.assertExists(target)
1103 # Regardless of shred setting, original should have canary data
1104 with open(target, 'rb') as f:
1105 self.assertEqual(f.read(), b'canary data')
1106 self.assertDirectoryCount(tmp_dir, 1)
1107
1108 delete(target, shred=False)
1109 self.assertDirectoryCount(tmp_dir, 0)
1110
1111 @common.skipUnlessWindows
1112 def test_truncate_file_refuses_reparse_point(self):
1113 """truncate_file() refuses a junction or symlink target"""
1114 target_dir = self.mkdtemp(prefix='truncate-target')
1115 junction = os.path.join(self.mkdtemp(prefix='truncate'), 'link')
1116 self._create_win_junction(target_dir, junction)
1117 with self.assertRaises(OSError):
1118 truncate_file(junction)
1119
1120 @common.skipIfWindows
1121 def test_truncate_file_refuses_symlink(self):
1122 """truncate_file() must not truncate a symlink's target"""
1123 target = self.write_file('truncate_target', b'keepme')
1124 link = os.path.join(self.tempdir, 'truncate_link')
1125 os.symlink(target, link)
1126 with self.assertRaises(OSError):
1127 truncate_file(link)
1128 self.assertEqual(os.path.getsize(target), len(b'keepme'))
1129
1130 @common.skipIfWindows
1131 def test_truncate_locked_file_refuses_symlink(self):
1132 """_truncate_locked_file() must not truncate a symlink's target"""
1133 target = self.write_file('locked_truncate_target', b'keepme')
1134 link = os.path.join(self.tempdir, 'locked_truncate_link')
1135 os.symlink(target, link)
1136 self.assertFalse(_truncate_locked_file(link))
1137 self.assertEqual(os.path.getsize(target), len(b'keepme'))
1138
1139 @common.skipUnlessWindows
1140 def test_delete_junction(self):
1141 """Unit test for delete() with Windows junction
1142
1143 - Tests both shredding and unlink.
1144 - Tests junction (not directory symlink).
1145 - Target is a directory (not a file).
1146 - Target exists (not broken).
1147 - Test is Windows only.
1148 """
1149 for shred in (False, True):
1150 with self.subTest(shred=shred):
1151 tmp_dir = self.mkdtemp(prefix=f'delete_junction_{shred}')
1152 # Use empty target: with shred=True, non-empty dirs trigger early return
1153 target_dir = self.mkdtemp(
1154 prefix=f'junction-target-{shred}', dir=tmp_dir)
1155 self.assertDirectoryCount(tmp_dir, 1)
1156
1157 junction = os.path.join(tmp_dir, f'junction-{shred}')
1158 self._create_win_junction(target_dir, junction)
1159 self.assertExists(junction)
1160 self.assertTrue(Windows.is_junction(junction))
1161 self.assertFalse(Windows.is_junction(target_dir))
1162 self.assertFalse(is_hard_link(junction))
1163 self.assertFalse(is_hard_link(target_dir))
1164 self.assertDirectoryCount(tmp_dir, 2)
1165
1166 delete(junction, shred=shred)
1167 self.assertNotExists(junction)
1168 self.assertExists(target_dir)
1169 self.assertDirectoryCount(tmp_dir, 1)
1170
1171 delete(target_dir, shred=False)
1172 self.assertDirectoryCount(tmp_dir, 0)
1173
1174 @common.skipUnlessWindows
1175 def test_delete_junction_nonempty_target(self):
1176 """Unit test for delete() with a junction whose target is not empty
1177
1178 Unlike test_delete_junction, the target here is non-empty. The
1179 junction itself should still be removed regardless.
1180 """
1181 for shred in (False, True):
1182 with self.subTest(shred=shred):
1183 tmp_dir = self.mkdtemp(prefix=f'delete_junction_ne_{shred}')
1184 target_dir = self.mkdtemp(
1185 prefix=f'junction-target-ne-{shred}', dir=tmp_dir)
1186 target_file = self.mkstemp(
1187 prefix='keep-me-', dir=target_dir)
1188
1189 junction = os.path.join(tmp_dir, f'junction-ne-{shred}')
1190 self._create_win_junction(target_dir, junction)
1191 self.assertExists(junction)
1192 self.assertTrue(Windows.is_junction(junction))
1193
1194 self.assertTrue(delete(junction, shred=shred))
1195 self.assertNotExists(junction)
1196 # The junction is gone, but its target and target's
1197 # contents must be completely untouched.
1198 self.assertExists(target_dir)
1199 self.assertExists(target_file)
1200
1201 @common.skipUnlessWindows
1202 def test_delete_read_only_directory(self):
1203 """Unit test for delete() with read-only directory on Windows
1204
1205 - Expects directory to be removed.
1206 - Tets both shred=True and False.
1207 """
1208 kernel32 = ctypes.windll.kernel32
1209 FILE_ATTRIBUTE_READONLY = 0x1
1210 for shred in (False, True):
1211 with self.subTest(shred=shred):
1212 container = self.mkdtemp(prefix=f'ro-container-{shred}')
1213 self.assertTrue(is_dir_empty(container))
1214 self.assertDirectoryCount(container, 0)
1215
1216 ro_dir = os.path.join(container, f'readonly-{shred}')
1217 self.mkdir(ro_dir)
1218 kernel32.SetFileAttributesW(ro_dir, FILE_ATTRIBUTE_READONLY)
1219 self.assertExists(ro_dir)
1220 self.assertDirectoryCount(container, 1)
1221
1222 try:
1223 delete(ro_dir, shred=shred)
1224
1225 self.assertNotExists(ro_dir)
1226 self.assertDirectoryCount(container, 0)
1227 except Exception:
1228 # Cleanup: clear read-only attribute so tearDown can remove it
1229 for item in os.listdir(container):
1230 item_path = os.path.join(container, item)
1231 _remove_windows_readonly(item_path)
1232 raise
1233
1234 @common.skipUnlessWindows
1235 def test_delete_extended_path(self):
1236 """Unit test for delete() with extended Windows path (>260 chars)"""
1237 for shred in (False, True):
1238 with self.subTest(shred=shred):
1239 long_name = 'x' * 200
1240 long_dir = self.mkdir(f'{long_name}-dir-{shred}')
1241
1242 long_file = self.write_file(
1243 extended_path(os.path.join(
1244 long_dir, f'{long_name}-file-{shred}.txt')),
1245 b'canary data',
1246 )
1247
1248 delete(long_file, shred=shred)
1249 self.assertNotExists(extended_path(long_file))
1250
1251 delete(long_dir, shred=shred)
1252 self.assertNotExists(extended_path(long_dir))
1253
1254 def test_clean_ini_non_utf8(self):
1255 """clean_ini() leaves a non-UTF-8 file untouched and logs an error"""
1256 # Latin-1 bytes that are invalid as UTF-8 (0xe9 = 'é' in Latin-1).
1257 content = b'[RecentsMRL]\nlist=\xe9\xe9\n'
1258 filename = self.write_file('bleachbit-test-ini-latin1', content)
1259 with open(filename, 'rb') as f:
1260 original = f.read()
1261 with self.assertLogs('bleachbit.FileUtilities', level='ERROR') as cm:
1262 clean_ini(filename, 'RecentsMRL', None)
1263 self.assertIn('not valid UTF-8', cm.output[0])
1264 # The file must not have been modified.
1265 with open(filename, 'rb') as f:
1266 self.assertEqual(original, f.read())
1267 delete(filename)
1268 self.assertNotExists(filename)
1269
1270 @common.skipUnlessWindows
1271 def test_detect_encoding(self):
1272 """Unit test for detect_encoding
1273
1274 The detect_encoding function is used only on Windows.
1275
1276 Old Linux distributions (e.g., openSUSE 15.6) charset_normalizer <= 3.4.1
1277 misclassifies EUC-KR as big5hkscs. This was fixed in 3.4.2, but it's moot
1278 because detect_encoding is not used on Linux. Also, the standard winapp2.ini
1279 is ASCII as of September 2026.
1280
1281 311e49c: added use of detect_encoding for Winapp
1282
1283 498abfb: removed use of detect_encoding for cleaning .ini files, so
1284 detect_encoding is no longer needed on Linux.
1285 """
1286 eat_glass = '나는 유리를 먹을 수 있어요. 그래도 아프지 않아요'
1287 bom = '\ufeff' + eat_glass # Add BOM for utf-8-sig
1288 # ASCII is valid UTF-8, so either answer reads the file correctly
1289 tests = (('This is just an ASCII file', ['ascii', 'utf-8']),
1290 (eat_glass, ['utf-8']),
1291 # Accept both EUC-KR and CP949 for Korean
1292 (eat_glass, ['EUC-KR', 'CP949']),
1293 (bom, ['UTF-8-SIG']))
1294 for file_contents, expected_encodings in tests:
1295 with self.subTest(encoding=expected_encodings):
1296 # Use first encoding for writing
1297 write_encoding = expected_encodings[0]
1298
1299 with tempfile.NamedTemporaryFile(mode='w', delete=False,
1300 dir=self.tempdir,
1301 encoding=write_encoding) as temp:
1302 temp.write(file_contents)
1303 temp.flush()
1304 det = detect_encoding(temp.name)
1305
1306 # Detectors spell codec names differently, so compare
1307 # the canonical names
1308 expected_names = [codecs.lookup(e).name
1309 for e in expected_encodings]
1310 self.assertIn(
1311 codecs.lookup(det).name, expected_names,
1312 f"{file_contents} -> {det}, expected one of {expected_encodings}")
1313
1314 def test_detect_encoding_missing_charset_normalizer(self):
1315 """detect_encoding should log a warning when charset_normalizer is missing."""
1316 with common.mock_missing_package('charset_normalizer'):
1317 # Latin-1 is not valid UTF-8, so a detector is needed
1318 with tempfile.NamedTemporaryFile(mode='w', delete=False,
1319 dir=self.tempdir,
1320 encoding='latin-1') as temp:
1321 temp.write('café')
1322 temp.flush()
1323 with self.assertLogs('bleachbit.FileUtilities', level='WARNING') as cm:
1324 self.assertIsNone(detect_encoding(temp.name))
1325 self.assertIn(
1326 'charset_normalizer module is not available', cm.output[0])
1327 os.unlink(temp.name)
1328
1329 @common.skipIfWindows
1330 def test_ego_owner(self):
1331 """Unit test for ego_owner()"""
1332 # pylint: disable=no-member
1333 self.assertEqual(ego_owner('/bin/ls'), os.getuid() == 0)
1334
1335 own_fn = self.mkstemp()
1336 self.assertTrue(ego_owner(own_fn))
1337
1338 # A path that vanished must not raise
1339 os.unlink(own_fn)
1340 self.assertFalse(ego_owner(own_fn))
1341 self.assertFalse(
1342 ego_owner(os.path.join(self.tempdir, 'does_not_exist')))
1343
1344 def test_execute_sqlite3(self):
1345 """Unit test for execute_sqlite3()"""
1346 db_path = self.mkstemp(suffix='.sqlite')
1347
1348 cmds = ['CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)',
1349 "INSERT INTO test (name) VALUES ('A'), ('B')",
1350 "UPDATE test SET name = 'C' WHERE name = 'B'",
1351 "DELETE FROM test WHERE name = 'C'"]
1352
1353 execute_sqlite3(db_path, ';'.join(cmds))
1354 execute_sqlite3(db_path, 'vacuum')
1355
1356 with contextlib.closing(sqlite3.connect(db_path)) as conn:
1357 res = conn.execute("select 1 from test where name = 'A'")
1358 row = res.fetchone()
1359 self.assertIsNotNone(row)
1360 self.assertEqual(row[0], 1)
1361
1362 gc_collect()
1363 os.unlink(db_path)
1364 self.assertNotExists(db_path)
1365
1366 def test_execute_sqlite3_open_error_translation(self):
1367 """Unit test for execute_sqlite3() open-error translation
1368
1369 A cryptic sqlite3 "unable to open database file" must be translated
1370 into OSError(EACCES) (or FileNotFoundError if the path is gone) so the
1371 Worker can surface the same "Access denied" summary users see for
1372 locked files.
1373 """
1374 # Path whose parent directory does not exist: sqlite cannot create
1375 # it and raises "unable to open database file"; the path itself is
1376 # gone -> FileNotFoundError.
1377 gone_path = os.path.join(self.tempdir, 'no_such_subdir', 'gone.sqlite')
1378 self.assertNotExists(gone_path)
1379 with self.assertRaises(FileNotFoundError) as ctx:
1380 execute_sqlite3(gone_path, 'vacuum')
1381 self.assertEqual(ctx.exception.errno, errno.ENOENT)
1382 self.assertEqual(ctx.exception.filename, gone_path)
1383
1384 # Path that exists but is a directory: sqlite cannot open a directory
1385 # as a database and raises "unable to open database file"; the path
1386 # is present -> OSError(EACCES) "Access denied".
1387 present_path = self.tempdir
1388 self.assertExists(present_path)
1389 with self.assertRaises(OSError) as ctx:
1390 execute_sqlite3(present_path, 'vacuum')
1391 self.assertEqual(ctx.exception.errno, errno.EACCES)
1392 self.assertEqual(ctx.exception.filename, present_path)
1393 self.assertIn('Access denied', ctx.exception.strerror)
1394
1395 def test_exe_exists(self):
1396 """Unit test for exe_exists()"""
1397 tests = [("/bin/sh", True),
1398 ("sh", True),
1399 ("doesnotexist", False),
1400 ("/bin/doesnotexist", False)]
1401 if IS_WINDOWS:
1402 tests = [('c:\\windows\\system32\\cmd.exe', True),
1403 ('cmd.exe', True),
1404 ('doesnotexist', False),
1405 ('c:\\windows\\doesnotexist.exe', False)]
1406 for exe, expected in tests:
1407 with self.subTest(exe=exe, expected=expected):
1408 if IS_POSIX and not os.getenv('PATH') and not os.path.isabs(exe):
1409 self.skipTest('PATH not set')
1410 self.assertEqual(exe_exists(exe), expected,
1411 f"{exe} -> {expected}")
1412
1413 def test_exists_in_path(self):
1414 """Unit test for exists_in_path()"""
1415 filename = 'ls'
1416 if IS_WINDOWS:
1417 filename = 'cmd.exe'
1418 if IS_POSIX and not os.getenv('PATH'):
1419 self.assertFalse(exists_in_path(filename))
1420 else:
1421 self.assertTrue(exists_in_path(filename))
1422 self.assertFalse(exists_in_path('doesnotexist'))
1423 if IS_POSIX:
1424 with self.assertRaises(AssertionError):
1425 exists_in_path('/usr/bin/doesnotexist')
1426 if IS_WINDOWS:
1427 with self.assertRaises(AssertionError):
1428 exists_in_path('c:\\does\\not\\exist.exe')
1429
1430 def test_expand_glob_join(self):
1431 """Unit test for expand_glob_join()"""
1432 if IS_POSIX:
1433 expand_glob_join('/bin', '*sh')
1434 if IS_WINDOWS:
1435 expand_glob_join(r'c:\windows', '*.exe')
1436
1437 def test_expand_vars_user(self):
1438 """Unit test for expandvars() and expanduser()
1439
1440 We had custom implementations of expandvars() and expanduser()
1441 until commit 3a3913 that switched to Python 3.
1442 """
1443
1444 if IS_WINDOWS:
1445 home_vars = ('%USERPROFILE%', '$userprofile', '${USERprofile}')
1446 else:
1447 home_vars = ['$HOME', '${HOME}']
1448 for var in home_vars:
1449 var_stripped = var.strip('%${}')
1450 if not os.getenv(var_stripped):
1451 self.skipTest(f'Environment variable {var_stripped} not set')
1452 expanded = os.path.expandvars(var)
1453 self.assertIsString(expanded)
1454 self.assertNotEqual(
1455 expanded, var, 'Environment variable was not expanded')
1456 self.assertEqual(expanded, os.path.expanduser('~'))
1457 self.assertExists(expanded)
1458 # An absolute path should not be altered.
1459 self.assertEqual(expanded, os.path.expandvars(expanded))
1460 self.assertEqual(expanded, os.path.expanduser(expanded))
1461
1462 def test_expand_vars_no_change(self):
1463 """Unit test for expandvars() and expanduser()
1464
1465 These expect no change.
1466 """
1467 # An empty string should not be altered.
1468 self.assertEqual(os.path.expandvars(''), '')
1469
1470 # Non-existent variables should not be altered.
1471 self.assertEqual(os.path.expandvars('$nonexistent'), '$nonexistent')
1472
1473 # A relative path should not be expanded.
1474 for p in ('common', 'common/', 'common', 'home', 'userprofile'):
1475 self.assertEqual(os.path.expanduser(p), p)
1476
1477 def test_extended_path(self):
1478 """Unit test for extended_path() and extended_path_undo()"""
1479 if IS_WINDOWS:
1480 tests = [
1481 (r'c:\windows\notepad.exe', r'\\?\c:\windows\notepad.exe'),
1482 (r'\\server\share\windows\notepad.exe',
1483 r'\\?\unc\server\share\windows\notepad.exe'),
1484 ]
1485 else:
1486 # unchanged
1487 tests = (('/home/foo', '/home/foo'),)
1488 for short, extended in tests:
1489 # already extended path shouldn't be changed
1490 self.assertEqual(extended_path(extended), extended)
1491 # does the conversion work both ways?
1492 self.assertEqual(extended_path(short), extended)
1493 self.assertEqual(extended_path_undo(extended), short)
1494 # unextended paths shouldn't be shortened any more
1495 self.assertEqual(extended_path_undo(short), short)
1496
1497 def test_free_space(self):
1498 """Unit test for free_space()"""
1499
1500 partitions = []
1501 os_paths = []
1502 if IS_WINDOWS:
1503 # Allow CD-ROM, network drive, etc.
1504 partitions = psutil.disk_partitions(all=True)
1505 os_paths = (r'%windir%', r'%userprofile%', r'%temp%')
1506 elif IS_POSIX:
1507 # Do not allow proc, sysfs, udev, etc.
1508 partitions_original = psutil.disk_partitions(all=False)
1509 # Allow ext4, vfat, etc. but not squashfs
1510 partitions = [
1511 p for p in partitions_original if p.fstype != 'squashfs']
1512 os_paths = ("/home", "/var", "/tmp", "$home", "$temp", "/dev/shm")
1513 self.assertGreater(len(partitions), 0, "No disk partitions found")
1514
1515 test_counter = 0
1516 test_paths = set()
1517 for partition in partitions:
1518 test_paths.add(partition.mountpoint)
1519 for os_path in os_paths:
1520 expanded = os.path.expandvars(os_path)
1521 if os.path.exists(expanded):
1522 test_paths.add(expanded)
1523 test_paths.add(os.getcwd())
1524
1525 for path in test_paths:
1526 with self.subTest(path=path):
1527 if IS_WINDOWS and not os.path.exists(path):
1528 # e.g., disconnected network drive or empty CD-ROM
1529 continue
1530 test_counter += 1
1531 try:
1532 free = free_space(path)
1533 except OSError:
1534 # e.g., disconnected network drive
1535 continue
1536 self.assertIsInstance(
1537 free, int, f"free_space({path}) should return int")
1538 self.assertGreaterEqual(
1539 free, 0, f"free_space({path}) should be non-negative")
1540 self.assertGreater(test_counter, 0)
1541
1542 def test_free_space_sub_dir(self):
1543 """Unit test for free_space() with subdirectories"""
1544 subdir = self.mkdtemp()
1545 passed = False
1546 for _ in range(5):
1547 diff = abs(free_space(subdir) - free_space(self.tempdir))
1548 if diff <= 1024 * 1024: # 1MB
1549 passed = True
1550 break
1551 self.assertTrue(
1552 passed, "free_space() for subdir should be within 1MB of parent dir at least once")
1553
1554 def test_free_space_invalid(self):
1555 """Check invalid inputs to free_space()"""
1556 # Test with invalid paths
1557 for path in ("invalid", "", None):
1558 with self.assertRaises((TypeError, FileNotFoundError)):
1559 free_space(path)
1560
1561 def test_get_filesystem_type(self):
1562 """Unit test for get_filesystem_type()"""
1563 home = os.path.expanduser('~')
1564 if IS_WINDOWS:
1565 path = self.tempdir
1566 fs_type = get_filesystem_type(path)[0]
1567 while path:
1568 print(path)
1569 self.assertEqual(get_filesystem_type(path)[0], fs_type)
1570 self.assertEqual(get_filesystem_type(path.lower())[0], fs_type)
1571 self.assertEqual(get_filesystem_type(path.upper())[0], fs_type)
1572 if path == os.path.dirname(path):
1573 break
1574 path = os.path.dirname(path)
1575 self.assertNotEqual(fs_type, 'unknown')
1576 self.assertEqual(get_filesystem_type(r'a:\\')[0], 'unknown')
1577 self.assertEqual(get_filesystem_type(r'Z:\\')[0], 'unknown')
1578 for check_path in (home, r'c:\\', r'c:'):
1579 self.assertEqual(get_filesystem_type(
1580 check_path)[0], 'NTFS', check_path)
1581 self.assertEqual(get_filesystem_type(
1582 check_path.lower())[0], 'NTFS')
1583 self.assertEqual(get_filesystem_type(
1584 check_path.upper())[0], 'NTFS')
1585 elif IS_POSIX:
1586 for check_path in (home, '/'):
1587 detected_fs = get_filesystem_type(check_path)[0]
1588 self.assertIn(detected_fs, ['apfs', 'btrfs', 'ext4', 'ext3', 'hfs', 'squashfs', 'unknown'],
1589 f"Unexpected file system type for {check_path}: {detected_fs}")
1590
1591 def test_get_filesystem_type_missing_psutil(self):
1592 """get_filesystem_type should return unknown when psutil is missing."""
1593 with common.mock_missing_package('psutil'):
1594 with self.assertLogs('bleachbit.FileUtilities', level='WARNING') as cm:
1595 result = get_filesystem_type('/')
1596 self.assertEqual(result, ("unknown", "none"))
1597 self.assertIn('psutil', cm.output[0])
1598
1599 def test_getsize(self):
1600 """Unit test for method getsize()"""
1601 dirname = self.mkdtemp(prefix='bleachbit-test-getsize')
1602
1603 def test_getsize_helper(fname):
1604 filename = self.write_file(os.path.join(
1605 dirname, fname), b"abcdefghij" * 12345)
1606
1607 if IS_WINDOWS:
1608 self.assertEqual(getsize(filename), 10 * 12345)
1609 # Expand the directory names, which are in the short format,
1610 # to test the case where the full path (including the directory)
1611 # is longer than 255 characters.
1612 # pylint: disable=possibly-used-before-assignment, c-extension-no-member
1613 lname = win32api.GetLongPathNameW(extended_path(filename))
1614 self.assertEqual(getsize(lname), 10 * 12345)
1615 # this function returns a byte string instead of Unicode
1616 counter = 0
1617 for child in children_in_directory(dirname, False):
1618 self.assertEqual(getsize(child), 10 * 12345)
1619 counter += 1
1620 self.assertEqual(counter, 1)
1621 if IS_POSIX:
1622 encoding = sys.getdefaultencoding()
1623 output = str(subprocess.Popen(
1624 ["du", "-h", filename],
1625 stdout=subprocess.PIPE).communicate()[0], encoding=encoding)
1626 output = output.replace("\n", "")
1627 du_size = output.split('\t', maxsplit=1)[0] + "B"
1628 print(f"output = '{output}', size='{du_size}'")
1629 du_bytes = human_to_bytes(du_size, 'du')
1630 print(output, du_size, du_bytes)
1631 self.assertEqual(getsize(filename), du_bytes)
1632 delete(filename)
1633 self.assertNotExists(filename)
1634
1635 # create regular file
1636 test_getsize_helper('bleachbit-test-regular')
1637
1638 # special characters
1639 test_getsize_helper('bleachbit-test-special-characters-∺ ∯')
1640
1641 # em-dash (LP1454030)
1642 test_getsize_helper('bleachbit-test-em-dash-\u2014')
1643
1644 # long
1645 test_getsize_helper('bleachbit-test-long' + 'x' * 200)
1646
1647 # delete the empty directory
1648 delete(dirname)
1649
1650 if IS_WINDOWS:
1651 # the following tests do not apply to Windows
1652 return
1653
1654 # create a symlink
1655 filename = self.write_file(
1656 'bleachbit-test-symlink', b'abcdefghij' * 12345)
1657 linkname = os.path.join(self.tempdir, 'bleachbitsymlinktest')
1658 if os.path.lexists(linkname):
1659 delete(linkname)
1660 os.symlink(filename, linkname)
1661 self.assertLess(getsize(linkname), 8192,
1662 f"Symlink size is {getsize(filename)}")
1663 delete(filename)
1664
1665 @common.skipIfWindows
1666 def test_getsize_sparse(self):
1667 """Test getsize() with a sparse file"""
1668 # macOS HFS+ did not support sparse files, but APFS does.
1669 (handle, filename) = tempfile.mkstemp(
1670 prefix="bleachbit-test-sparse-", dir=self.tempdir)
1671 os.ftruncate(handle, 1000 ** 2)
1672 os.close(handle)
1673 self.assertEqual(getsize(filename), 0)
1674
1675 def test_getsizedir(self):
1676 """Unit test for getsizedir()"""
1677 path = '/bin'
1678 if IS_WINDOWS:
1679 path = 'c:\\windows\\system32'
1680 self.assertGreater(getsizedir(path), 0)
1681
1682 def test_getsizedir_vanished(self):
1683 """getsizedir() skips a file that vanishes between the walk and the stat"""
1684 dirname = self.mkdtemp(prefix='bleachbit-test-getsizedir-vanished')
1685 real_fn = os.path.join(dirname, 'real')
1686 self.write_file(real_fn, contents=b'0123456789')
1687 expected = getsize(real_fn)
1688 self.assertGreater(expected, 0)
1689
1690 ghost_fn = os.path.join(dirname, 'ghost')
1691 with unittest.mock.patch('bleachbit.FileUtilities.children_in_directory',
1692 return_value=iter([real_fn, ghost_fn])):
1693 self.assertEqual(getsizedir(dirname), expected)
1694
1695 # Other errors must still propagate
1696 with unittest.mock.patch('bleachbit.FileUtilities.getsize',
1697 side_effect=PermissionError('denied')):
1698 with self.assertRaises(PermissionError):
1699 getsizedir(dirname)
1700
1701 def test_globex(self):
1702 """Unit test for method globex()"""
1703 for path in globex('/bin/*', '/ls$'):
1704 self.assertEqual(path, '/bin/ls')
1705
1706 def test_guess_overwrite_paths(self):
1707 """Unit test for guess_overwrite_paths()"""
1708 for path in guess_overwrite_paths():
1709 self.assertTrue(os.path.isdir(path),
1710 f'{path} is not a directory')
1711
1712 def test_human_to_bytes(self):
1713 """Unit test for human_to_bytes()"""
1714 self.assertRaises(ValueError, human_to_bytes, '', hformat='invalid')
1715
1716 for test in ['Bazillion kB', '120XB', '.12MB']:
1717 self.assertRaises(ValueError, human_to_bytes, test)
1718
1719 valid = {'1kB': 1000,
1720 '1.1MB': 1100000,
1721 '12B': 12,
1722 '1.0M': 1000 * 1000,
1723 '1TB': 1000**4,
1724 '1000': 1000}
1725 for test, result in valid.items():
1726 self.assertEqual(human_to_bytes(test), result)
1727
1728 self.assertEqual(human_to_bytes('1 MB', 'du'), 1024 * 1024)
1729
1730 def test_listdir(self):
1731 """Unit test for listdir()"""
1732 if IS_POSIX:
1733 dir1 = '/bin'
1734 dir2 = os.path.expanduser('/sbin')
1735 elif IS_WINDOWS:
1736 dir1 = os.path.expandvars(r'%windir%\fonts')
1737 dir2 = os.path.expandvars(r'%windir%\logs')
1738 else:
1739 raise NotImplementedError()
1740 # If these directories do not exist, the test results are not valid.
1741 self.assertExists(dir1)
1742 self.assertExists(dir2)
1743 # Every path found in dir1 and dir2 should be found in (dir1, dir2).
1744 paths1 = set(listdir(dir1))
1745 paths2 = set(listdir(dir2))
1746 self.assertGreater(len(paths1), 4)
1747 self.assertGreater(len(paths2), 4)
1748 paths12 = set(listdir((dir1, dir2)))
1749 self.assertLess(paths1, paths12)
1750 self.assertLess(paths2, paths12)
1751 # The individual calls should be equivalent to a combined call.
1752 self.assertSetEqual(paths1.union(paths2), paths12)
1753 # The directories should not be empty.
1754 self.assertGreater(len(paths1), 0)
1755 self.assertGreater(len(paths2), 0)
1756 # Every path found should exist.
1757 for pathname in paths12:
1758 self.assertLExists(pathname)
1759
1760 def test_is_normal_directory_real(self):
1761 """Unit test for is_normal_directory() with real files"""
1762 # Test with a real directory.
1763 self.assertTrue(is_normal_directory(self.tempdir))
1764
1765 # Test with a normal file.
1766 self.assertFalse(is_normal_directory(__file__))
1767
1768 # Test with a non-existent path.
1769 self.assertFalse(is_normal_directory(
1770 os.path.join(self.tempdir, 'doesnotexist')))
1771
1772 # Check common junctions on Windows
1773 if IS_WINDOWS:
1774 user_docs = os.path.expandvars(r'%userprofile%\My Documents')
1775 prog_docs = os.path.expandvars(r'%ProgramData%\Documents')
1776 for junction_path in (user_docs, prog_docs):
1777 if os.path.exists(junction_path):
1778 self.assertTrue(Windows.is_junction(junction_path),
1779 f"{junction_path} should be a junction")
1780 self.assertFalse(is_normal_directory(junction_path),
1781 f"{junction_path} should not be a normal directory")
1782 else:
1783 logger.warning("junction not found: %s", junction_path)
1784
1785 def test_open_files_lsof(self):
1786 """Unit test for open_files_lsof()"""
1787 self.assertEqual(list(open_files_lsof(
1788 lambda: 'n/bar/foo\nn/foo/bar\nnoise')), ['/bar/foo', '/foo/bar'])
1789
1790 @common.skipIfWindows
1791 def test_open_files(self):
1792 """Unit test for class OpenFiles"""
1793
1794 filename = os.path.join(self.tempdir, 'bleachbit-test-open-files')
1795 with open(filename, 'wb'):
1796 openfiles = OpenFiles()
1797 ago = None
1798 if openfiles.last_scan_time:
1799 ago = time.time() - openfiles.last_scan_time
1800 self.assertTrue(openfiles.is_open(filename),
1801 f"Expected is_open({filename}) to return True)\n"
1802 f"openfiles.last_scan_time (ago)={ago}\n"
1803 f"openfiles.files={openfiles.files}")
1804
1805 openfiles.scan()
1806 self.assertFalse(openfiles.is_open(filename))
1807
1808 os.unlink(filename)
1809 openfiles.scan()
1810 self.assertFalse(openfiles.is_open(filename))
1811
1812 def test_same_partition(self):
1813 """Unit test for same_partition()"""
1814 home = os.path.expanduser('~')
1815 self.assertTrue(same_partition(home, home))
1816 if IS_POSIX:
1817 self.assertFalse(same_partition(home, '/dev'))
1818 elif IS_WINDOWS:
1819 home_drive = os.path.splitdrive(home)[0]
1820 # pylint: disable=import-outside-toplevel
1821 from bleachbit.Windows import get_fixed_drives
1822 for drive in get_fixed_drives():
1823 this_drive = os.path.splitdrive(drive)[0]
1824 self.assertEqual(same_partition(home, drive),
1825 home_drive == this_drive)
1826
1827 def test_uris_to_paths(self):
1828 """Unit test for uris_to_paths()"""
1829 self.assertEqual(uris_to_paths(['']), [])
1830
1831 # Unix-style
1832 uri_u = ['file:///usr/bin/bleachbit']
1833 path_u = [os.path.normpath('/usr/bin/bleachbit'), ]
1834 self.assertEqual(uris_to_paths(uri_u), path_u)
1835
1836 # Windows
1837 uri_w = [r'file:///C:/program%20files/bleachbit.exe']
1838 path_w = [os.path.normpath(r'C:/program files/bleachbit.exe'), ]
1839 self.assertEqual(uris_to_paths(uri_w), path_w)
1840
1841 # Multiple
1842 self.assertEqual(uris_to_paths(uri_u + uri_w), path_u + path_w)
1843
1844 # Unsupported scheme
1845 uri_s = ['foo://bar']
1846 self.assertEqual(uris_to_paths(uri_u + uri_w + uri_s), path_u + path_w)
1847
1848 # Malformed file URIs must not yield an empty path, which previously
1849 # resolved to CWD in create_simple_cleaner.
1850 self.assertEqual(uris_to_paths(['file:']), [])
1851 self.assertEqual(uris_to_paths(['file://']), [])
1852 self.assertEqual(uris_to_paths(['file:///']), [os.path.normpath('/')])
1853
1854 def test_vacuum_sqlite3(self):
1855 """Unit test for method vacuum_sqlite3()"""
1856 path = os.path.join(self.tempdir, 'bleachbit_test_vacuum.sqlite3')
1857 conn = sqlite3.connect(path)
1858 # Use in-memory journal to avoid creating a transient
1859 # file that could trigger TOCTOU error in parallel tests.
1860 # (This prevents writing the `-journal` file, but the `.sqlite3`
1861 # database is still written.)
1862 conn.execute('PRAGMA journal_mode=memory')
1863 conn.execute('create table numbers (number)')
1864 conn.commit()
1865 empty_size = getsize(path)
1866
1867 def number_generator():
1868 for x in range(1, 10000):
1869 yield (x, )
1870 conn.executemany(
1871 'insert into numbers (number) values ( ? ) ', number_generator())
1872 conn.commit()
1873 self.assertLess(empty_size, getsize(path))
1874 conn.execute('delete from numbers')
1875 conn.commit()
1876 conn.close()
1877
1878 vacuum_sqlite3(path)
1879 self.assertEqual(empty_size, getsize(path))
1880
1881 gc_collect()
1882 delete(path)
1883 self.assertNotExists(path)
1884
1885 def test_sqlite_loop(self):
1886 """Repeat SQLite tests
1887
1888 This may raise ResourceWarning on Python 3.13.
1889 """
1890 warnings.simplefilter("error")
1891 start_time = time.time()
1892 for _ in range(5):
1893 self.test_execute_sqlite3()
1894 self.test_vacuum_sqlite3()
1895 # Slow on OpenSUSE Build Service
1896 if time.time() - start_time > 30:
1897 logger.info(
1898 "SQLite loop tests stopped early after %d seconds", time.time() - start_time)
1899 break
1900 logger.info(
1901 "SQLite loop tests fully completed after %d seconds", time.time() - start_time)
1902
1903 def assert_is_whitelisted(self, path, allow_swapcase=True):
1904 """Helper to assert a path is whitelisted"""
1905 self.assertTrue(whitelisted(path),
1906 f"Path {path} should be whitelisted")
1907 if allow_swapcase and not FS_CASE_SENSITIVE:
1908 self.assertTrue(whitelisted(path.swapcase()),
1909 f"Path {path.swapcase()} should be whitelisted")
1910
1911 def test_whitelisted(self):
1912 """Unit test for whitelisted()"""
1913 # FIXME: finish renaming whitelist to keep list
1914 # setup
1915 keep_list = [('file', '/home/foo'), ('folder', '/home/folder')]
1916 options.set_whitelist_paths(keep_list)
1917 self.assertEqual(set(keep_list), set(options.get_whitelist_paths()))
1918
1919 # test
1920 # '/' is system-critical and always kept, so it is excluded here
1921 tests = ('', '/home/foo2', '/home/fo', '/home/', '/home')
1922 for path in tests:
1923 self.assertFalse(whitelisted(
1924 path), f"{path} should not be whitelisted")
1925
1926 with self.assertRaises(TypeError):
1927 whitelisted(None)
1928
1929 # Verbatim of whitelisted.
1930 self.assert_is_whitelisted('/home/foo')
1931 self.assert_is_whitelisted('/home/folder')
1932 if IS_POSIX:
1933 # Whitelisted + path separator.
1934 self.assert_is_whitelisted('/home/folder/')
1935 # File under whitelisted directory.
1936 self.assert_is_whitelisted('/home/folder/file')
1937 # Same as explicit whitelisted, minus one character.
1938 self.assertFalse(whitelisted('/home/folde'))
1939 # Same as explicit whitelisted, plus one character.
1940 self.assertFalse(whitelisted('/home/folder2'))
1941
1942 # Test a blank whitelist.
1943 options.set_whitelist_paths([])
1944 self.assertFalse(whitelisted('/home/foo'))
1945 self.assertFalse(whitelisted('/home/folder'))
1946 self.assertFalse(whitelisted('/home/folder/file'))
1947
1948 # Remove the whitelist section from the configuration.
1949 options.config.remove_section('whitelist/paths')
1950 self.assertFalse(whitelisted('/home/foo'))
1951 self.assertFalse(whitelisted('/home/folder'))
1952 self.assertFalse(whitelisted('/home/folder/file'))
1953
1954 def test_whitelisted_posix_system_critical(self):
1955 """System-critical POSIX paths are kept even with an empty keep list."""
1956 if not IS_POSIX:
1957 self.skipTest('POSIX only')
1958 options.set_whitelist_paths([])
1959 for path in ('/', '//', '/proc', '/proc/cpuinfo', '/sys/',
1960 '/sys/kernel', '/run', '/run/user/0'):
1961 self.assertTrue(whitelisted(path),
1962 f"{path} should be protected")
1963 # Real cleaners legitimately act under /var, /dev/shm, /etc
1964 for path in ('/home/user/file', '/tmp/scratch', '/opt/data/x',
1965 '/etc/passwd', '/var/log/syslog', '/dev/shm/x',
1966 '/procfile', '/sysfs2/x', ''):
1967 self.assertFalse(whitelisted(path),
1968 f"{path} should not be protected")
1969
1970 @common.skipUnlessWindows
1971 def test_whitelisted_windows(self):
1972 """Test whitelisted() on Windows"""
1973 keep_list = [('folder', 'D:\\'),
1974 ('file', 'c:\\windows\\foo.log'),
1975 ('file', 'c:\\de\\straße.txt'),
1976 ('folder', 'e:\\users')
1977 ]
1978 options.set_whitelist_paths(keep_list)
1979 # verbatim paths
1980 self.assert_is_whitelisted('d:\\')
1981 self.assert_is_whitelisted('c:\\windows\\foo.log')
1982 self.assert_is_whitelisted('c:\\de\\straße.txt', False)
1983 self.assert_is_whitelisted('e:\\users')
1984 # explicit folder plus trailing slash
1985 self.assert_is_whitelisted('e:\\users\\')
1986 # file in explicit folder
1987 self.assert_is_whitelisted('e:\\users\\foo.log')
1988 self.assert_is_whitelisted('d:\\folder\\foo.log')
1989 # file in folder not in keep list
1990 self.assertFalse(whitelisted('e:\\windows\\foo.log'))
1991 # Same as whitelisted minus one character.
1992 self.assertFalse(whitelisted('e:\\user'))
1993 # Same as whitelisted plus a character.
1994 self.assertFalse(whitelisted('e:\\users2'))
1995 # Bare root of whitelisted folder
1996 self.assertFalse(whitelisted('e:\\'))
1997 self.assertFalse(whitelisted('e:'))
1998 # German Eszett
1999 # Windows treats 'ß' and 'ss' as separate filenames.
2000 self.assertEqual('ß'.lower(), 'ß')
2001 self.assertEqual('ß'.swapcase(), 'SS')
2002 self.assertNotEqual('ß'.swapcase().swapcase(), 'ß')
2003 self.assert_is_whitelisted('c:\\de\\STRAßE.TXT', False)
2004 self.assertFalse(whitelisted('c:\\de\\strasse.txt'))
2005 self.assertFalse(whitelisted('c:\\de\\straSSe.txt'))
2006
2007 @common.skipUnlessWindows
2008 def test_whitelisted_windows_temp_roots(self):
2009 """Windows temp roots are preserved, but their contents are not."""
2010 options.set_whitelist_paths([])
2011 temp_roots = [
2012 r'C:\Windows\Temp',
2013 r'C:\WINDOWS\ServiceProfiles\MariaDB\AppData\Local\Temp',
2014 r'C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp',
2015 r'C:\Users\example\AppData\Local\Temp',
2016 r'C:\Documents and Settings\example\Local Settings\Temp',
2017 ]
2018
2019 for temp_root in temp_roots:
2020 with self.subTest(temp_root=temp_root):
2021 self.assert_is_whitelisted(temp_root)
2022 self.assert_is_whitelisted(temp_root + '\\')
2023 self.assertFalse(whitelisted(temp_root + r'\bleachbit.tmp'))
2024 self.assertFalse(whitelisted(temp_root + r'\subdir'))
2025
2026 @common.skipIfWindows
2027 def test_whitelisted_posix_symlink(self):
2028 """Symlink test for whitelisted_posix()"""
2029 # setup
2030 # reminder: unit tests run with a fresh config file each time,
2031 # so we do not need to keep the old settings.
2032 realpath = self.write_file('real')
2033 linkpath = os.path.join(self.tempdir, 'link')
2034 os.symlink(realpath, linkpath)
2035 self.assertExists(realpath)
2036 self.assertFalse(os.path.islink(realpath))
2037 self.assertExists(linkpath)
2038 self.assertTrue(os.path.islink(linkpath))
2039
2040 # test 1: the real path is whitelisted
2041 keep_list1 = [('file', realpath)]
2042 options.set_whitelist_paths(keep_list1)
2043 self.assertFalse(whitelisted(self.tempdir))
2044 self.assertTrue(whitelisted(realpath))
2045 self.assertTrue(whitelisted(linkpath))
2046
2047 # test 2: the link is whitelisted
2048 keep_list2 = [('file', linkpath)]
2049 options.set_whitelist_paths(keep_list2)
2050 self.assertFalse(whitelisted(self.tempdir))
2051 self.assertFalse(whitelisted(realpath))
2052 self.assertTrue(whitelisted(linkpath))
2053
2054 # test 3: folder symlinks
2055 realfolder = self.mkdir('realfolder')
2056 linkfolder = os.path.join(self.tempdir, 'linkfolder')
2057 os.symlink(realfolder, linkfolder)
2058
2059 keep_list3 = [('folder', realfolder)]
2060 options.set_whitelist_paths(keep_list3)
2061 self.assertTrue(whitelisted(realfolder))
2062 self.assertTrue(whitelisted(linkfolder))
2063
2064 def test_whitelisted_speed(self):
2065 """Benchmark the speed of whitelisted()
2066
2067 It is called frequently, so the speed is important."""
2068 d = '/usr/bin'
2069 keep_list = [('file', '/home/foo'), ('folder', '/home/folder')]
2070 if IS_WINDOWS:
2071 d = os.path.expandvars(r'%windir%\system32')
2072 keep_list = [('file', r'c:\filename'), ('folder', r'c:\\folder')]
2073 reps = 20
2074 paths = [p for p in children_in_directory(d, True)]
2075 paths = paths[:1000] # truncate
2076 self.assertGreater(len(paths), 10)
2077 old_keep_list = options.get_whitelist_paths()
2078 options.set_whitelist_paths(keep_list)
2079
2080 t0 = time.time()
2081 for _i in range(0, reps):
2082 for p in paths:
2083 _ = whitelisted(p)
2084 t1 = time.time()
2085 logger.info('whitelisted() with %d repetitions and %d paths took %g seconds',
2086 reps, len(paths), t1 - t0)
2087
2088 options.set_whitelist_paths(old_keep_list)