Debian Codegraph @

tests/TestWipe.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 Wipe
9 """
10
11 import errno
12 import itertools
13 import os
14 import unittest
15 from contextlib import ExitStack
16 from unittest import mock
17
18 import bleachbit
19 from bleachbit.Options import options
20 from bleachbit import Wipe
21 from bleachbit.Wipe import (
22 detect_orphaned_wipe_files,
23 sync,
24 wipe_contents,
25 wipe_path,
26 wipe_name,
27 wipe_write
28 )
29 from tests import common
30
31 if bleachbit.IS_WINDOWS:
32 import pywintypes
33
34
35 class WipeTestCase(common.BleachbitTestCase):
36
37 def test_detect_orphaned_wipe_files(self):
38 """Unit test for detect_orphaned_wipe_files()"""
39 # Save original shred_drives
40 original_drives = options.get_list('shred_drives')
41
42 # Set shred_drives to include our temp directory
43 options.set_list('shred_drives', [self.tempdir])
44
45 try:
46 # Test 1: No orphaned files initially
47 orphaned = detect_orphaned_wipe_files()
48 self.assertEqual(orphaned, [])
49
50 # Test 2: Create a file that matches criteria
51 # Must start with 'empty_', >100 chars, no extension, contain null bytes
52 long_suffix = 'a' * 120
53 orphan_name = 'empty_' + long_suffix
54 orphan_path = os.path.join(self.tempdir, orphan_name)
55 with open(orphan_path, 'wb') as f:
56 f.write(b'\x00' * 1000)
57
58 orphaned = detect_orphaned_wipe_files()
59 self.assertEqual(len(orphaned), 1)
60 self.assertEqual(orphaned[0], orphan_path)
61
62 # Test 3: File with extension should NOT be detected
63 with_ext_path = os.path.join(self.tempdir, orphan_name + '.txt')
64 with open(with_ext_path, 'wb') as f:
65 f.write(b'\x00' * 1000)
66
67 orphaned = detect_orphaned_wipe_files()
68 self.assertEqual(len(orphaned), 1) # Still just the original
69
70 # Test 4: Short filename should NOT be detected
71 short_name = 'empty_short'
72 short_path = os.path.join(self.tempdir, short_name)
73 with open(short_path, 'wb') as f:
74 f.write(b'\x00' * 1000)
75
76 orphaned = detect_orphaned_wipe_files()
77 self.assertEqual(len(orphaned), 1) # Still just the original
78
79 # Test 5: File without null bytes should NOT be detected
80 no_null_path = os.path.join(self.tempdir, 'empty_' + 'b' * 120)
81 with open(no_null_path, 'wb') as f:
82 f.write(b'x' * 1000)
83
84 orphaned = detect_orphaned_wipe_files()
85 self.assertEqual(len(orphaned), 1) # Still just the original
86
87 finally:
88 # Restore original shred_drives
89 if original_drives:
90 options.set_list('shred_drives', original_drives)
91
92 def test_sync(self):
93 """Unit test for sync()"""
94 sync()
95
96 def test_wipe_write(self):
97 """Unit test for wipe_write()"""
98
99 original = b'abcdefghij' * 12345
100
101 # overwrites the contents with zeros without truncating
102 filename = self.write_file('wipe_write', original)
103 wipe_write(filename).close()
104 with open(filename, 'rb') as f:
105 contents = f.read()
106 self.assertEqual(contents, b'\x00' * len(contents))
107 self.assertGreaterEqual(len(contents), len(original))
108
109 @common.skipIfWindows
110 def test_wipe_write_refuses_symlink(self):
111 """wipe_write() must not follow a symlink to overwrite its target"""
112 target = self.write_file('wipe_target', b'keepme' * 100)
113 link = os.path.join(self.tempdir, 'wipe_link')
114 os.symlink(target, link)
115 with self.assertRaises(OSError):
116 wipe_write(link)
117 with open(target, 'rb') as f:
118 self.assertEqual(f.read(), b'keepme' * 100)
119
120 def test_wipe_contents(self):
121 """Unit test for wipe_contents()"""
122
123 original = b'abcdefghij' * 12345
124
125 # truncates the file to zero bytes
126 filename = self.write_file('wipe_contents_truncate', original)
127 wipe_contents(filename)
128 self.assertEqual(os.path.getsize(filename), 0)
129
130 @common.skipUnlessWindows
131 def test_wipe_contents_windows_admin_reopen_refuses_symlink(self):
132 """wipe_contents() must not reopen a symlink after a successful wipe
133
134 On Windows when running as admin, a successful WindowsWipe.file_wipe()
135 is followed by a plain reopen to truncate the file to zero. That
136 reopen must not follow a symlink planted at the path in the meantime.
137 """
138 filename = self.write_file('wipe_contents_reopen', b'abc')
139 with mock.patch('bleachbit.Wipe.IsUserAnAdmin', return_value=True), \
140 mock.patch('bleachbit.WindowsWipe.file_wipe'), \
141 mock.patch('bleachbit.Wipe.os.path.islink',
142 side_effect=lambda p: p == filename):
143 with self.assertRaises(OSError):
144 wipe_contents(filename)
145
146 @common.skipUnlessWindows
147 def test_wipe_contents_windows_admin_locked_fallback_refuses_symlink(self):
148 """wipe_contents() must not truncate through a symlink in the locked-file fallback
149
150 When file_wipe() fails because the file is locked (winerror 32/33),
151 wipe_contents() falls back to a plain truncate. That fallback must
152 not follow a symlink planted at the path in the meantime.
153 """
154 filename = self.write_file('wipe_contents_locked_fallback', b'abc')
155 locked_error = pywintypes.error(32, 'CreateFile', 'locked')
156 with mock.patch('bleachbit.Wipe.IsUserAnAdmin', return_value=True), \
157 mock.patch('bleachbit.WindowsWipe.file_wipe',
158 side_effect=locked_error), \
159 mock.patch('bleachbit.Wipe.os.path.islink',
160 side_effect=lambda p: p == filename), \
161 mock.patch('bleachbit.FileUtilities.truncate_f') as mock_truncate_f:
162 with self.assertRaises(WindowsError):
163 wipe_contents(filename)
164 mock_truncate_f.assert_not_called()
165
166 @common.skipUnlessWindows
167 def test_wipe_contents_windows_admin_locked_fallback_still_works(self):
168 """The locked-file fallback still truncates a normal (non-symlink) file"""
169 filename = self.write_file('wipe_contents_locked_fallback_ok', b'abc')
170 locked_error = pywintypes.error(32, 'CreateFile', 'locked')
171 with mock.patch('bleachbit.Wipe.IsUserAnAdmin', return_value=True), \
172 mock.patch('bleachbit.WindowsWipe.file_wipe',
173 side_effect=locked_error):
174 with self.assertRaises(WindowsError):
175 wipe_contents(filename)
176 self.assertEqual(os.path.getsize(filename), 0)
177
178 def wipe_name_helper(self, filename):
179 """Helper for test_wipe_name()"""
180
181 self.assertExists(filename)
182
183 # test
184 newname = wipe_name(filename)
185 self.assertEqual(len(filename), len(newname))
186 self.assertNotExists(filename)
187 self.assertExists(newname)
188
189 # clean
190 os.remove(newname)
191 self.assertNotExists(newname)
192
193 def test_wipe_name(self):
194 """Unit test for wipe_name()"""
195
196 # create test file with moderately long name
197 filename = self.write_file('bleachbit-test-wipe' + '0' * 50)
198 self.wipe_name_helper(filename)
199
200 # create file with short name in temporary directory with long name
201 if bleachbit.IS_WINDOWS:
202 # In Windows, the maximum path length is 260 characters
203 # http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maxpath
204 dir0len = 100
205 dir1len = 5
206 else:
207 dir0len = 210
208 dir1len = 210
209 filelen = 10
210
211 dir0 = self.mkdtemp(prefix="0" * dir0len)
212 self.assertExists(dir0)
213
214 dir1 = self.mkdtemp(prefix="1" * dir1len, dir=dir0)
215 self.assertExists(dir1)
216
217 filename = self.write_file(os.path.join(dir1, '2' * filelen))
218 self.wipe_name_helper(filename)
219 self.assertExists(dir0)
220 self.assertExists(dir1)
221
222 # wipe a directory name
223 dir1new = wipe_name(dir1)
224 self.assertEqual(len(dir1), len(dir1new))
225 self.assertNotExists(dir1)
226 self.assertExists(dir1new)
227 os.rmdir(dir1new)
228
229 # wipe the directory
230 os.rmdir(dir0)
231 self.assertNotExists(dir0)
232
233 def test_wipe_name_when_basic_characters_exist(self):
234 """Unit test for wipe_name() when basic characters exist"""
235 testdir = self.mkdtemp()
236 filenames = []
237 # This tests that FILENAME_CHARS characters are valid for filenames.
238 for char in Wipe.FILENAME_CHARS:
239 if char == '.':
240 continue
241 filename = os.path.join(testdir, char)
242 self.write_file(filename)
243 self.assertExists(filename)
244 filenames.append(filename)
245
246 # Verify that FILENAME_CHARS contains uppercase letters on case-sensitive
247 # file systems, and that all test filenames are unique (case-insensitively)
248 # on case-insensitive file systems to avoid collisions.
249 if bleachbit.FS_CASE_SENSITIVE:
250 self.assertTrue(any(char.isupper()
251 for char in Wipe.FILENAME_CHARS))
252 else:
253 basenames = [os.path.basename(filename) for filename in filenames]
254 self.assertEqual(len(basenames), len(
255 set(name.lower() for name in basenames)))
256
257 filename = filenames[0]
258 newname = wipe_name(filename)
259 self.assertEqual(filename, newname)
260 self.assertExists(newname)
261
262 def test_wipe_name_rejects_windows_invalid_names(self):
263 """Unit test for wipe_name() with Windows-invalid names"""
264 filename = self.write_file('orig')
265 expected = os.path.join(self.tempdir, 'good')
266
267 bad_list = ['bad.', 'bad ', 'COM1', 'bad?']
268 with mock.patch.object(Wipe, 'IS_WINDOWS', True), \
269 mock.patch.object(
270 Wipe,
271 '__random_string',
272 side_effect=bad_list + ['good']):
273 newname = wipe_name(filename)
274
275 self.assertEqual(expected, newname)
276 self.assertNotExists(filename)
277 for bad_item in bad_list:
278 self.assertNotExists(os.path.join(self.tempdir, bad_item))
279 self.assertExists(newname)
280
281 @common.skipIfWindows
282 def test_wipe_name_allows_windows_reserved_names_on_linux(self):
283 """Unit test for wipe_name() with Windows-reserved names on Linux"""
284 filename = self.write_file('abc')
285 expected = os.path.join(self.tempdir, 'CON')
286
287 with mock.patch.object(Wipe, '__random_string', return_value='CON'):
288 newname = wipe_name(filename)
289
290 self.assertEqual(expected, newname)
291 self.assertNotExists(filename)
292 self.assertExists(newname)
293
294 def test_wipe_name_non_retryable_error(self):
295 """Give up early when rename() fails with non-retryable error"""
296 for errnum in (errno.EACCES, errno.EPERM, errno.EROFS):
297 with self.subTest(errnum=errnum):
298 filename = self.write_file(f'orig{errnum}')
299 expected = os.path.join(self.tempdir, f'fail{errnum}')
300 rename_error = OSError(errnum, os.strerror(errnum))
301
302 self.assertNotExists(expected)
303 with mock.patch.object(
304 Wipe, '__random_string',
305 return_value=f'fail{errnum}'), \
306 mock.patch.object(
307 Wipe.os, 'rename',
308 side_effect=rename_error) as rename_mock:
309 newname = wipe_name(filename)
310
311 self.assertEqual(filename, newname)
312 self.assertExists(filename)
313 self.assertNotExists(expected)
314 self.assertEqual(1, rename_mock.call_count)
315
316 @unittest.skipUnless(os.getenv('ALLTESTS') is not None,
317 'warning: skipping long test test_wipe_path() because'
318 ' environment variable ALLTESTS not set')
319 def test_wipe_path(self):
320 """Unit test for wipe_path()"""
321
322 for _ret in wipe_path(self.tempdir):
323 # no idle handler
324 pass
325
326 def test_wipe_path_fast(self):
327 """Unit test for wipe_path() with fast mode
328
329 This test runs three iterations of the generator and then
330 aborts. The idle clock is mocked forward on every check so
331 this doesn't depend on how fast the real disk/quota fills,
332 which varies a lot between CI runners.
333 """
334 counter = 0
335 with mock.patch('bleachbit.Wipe.time.time', side_effect=itertools.count(0, 3)):
336 for _i in wipe_path(self.tempdir, True):
337 counter += 1
338 if counter >= 3:
339 break
340 self.assertGreater(counter, 0)
341
342 def test_wipe_path_world_writable_warns(self):
343 """wipe_path() warns when the shred drive is world-writable"""
344 with mock.patch('bleachbit.Wipe.IS_POSIX', True), \
345 mock.patch('bleachbit.PathUtils.is_world_writable', return_value=True), \
346 self.assertLogs('bleachbit.Wipe', level='WARNING') as cm:
347 for _ret in wipe_path(self.tempdir, True):
348 break
349 self.assertTrue(any('world-writable' in m for m in cm.output))
350
351 def _make_mock_file(self, name='/tmp/empty_abc123'):
352 """Return a mock file object for wipe_path tests"""
353 mock_file = mock.Mock()
354 mock_file.name = name
355 mock_file.tell.return_value = 0
356 mock_file.fileno.return_value = -1
357 mock_file.write.return_value = 65536
358 mock_file.flush.return_value = None
359 mock_file.close.return_value = None
360 return mock_file
361
362 def _wipe_path_common_mocks(self, fs_type='ntfs'):
363 """Return an ExitStack with the common wipe_path mocks applied.
364
365 Each test can extend the returned stack with additional patches
366 via ``stack.enter_context(...)``.
367 """
368 stack = ExitStack()
369 stack.enter_context(mock.patch(
370 'bleachbit.Wipe.os.path.isdir', return_value=True))
371 stack.enter_context(mock.patch(
372 'bleachbit.FileUtilities.get_filesystem_type', return_value=(fs_type,)))
373 stack.enter_context(mock.patch(
374 'bleachbit.FileUtilities.free_space', return_value=0))
375 stack.enter_context(mock.patch('bleachbit.Wipe.sync'))
376 # There is no statvfs on Windows, so create it.
377 stack.enter_context(mock.patch(
378 'bleachbit.Wipe.os.statvfs', create=True))
379 stack.enter_context(mock.patch('bleachbit.Wipe.os.fsync'))
380 stack.delete_mock = stack.enter_context(
381 mock.patch('bleachbit.FileUtilities.delete'))
382 return stack
383
384 def test_wipe_path_not_directory(self):
385 """Non-directory path should return early"""
386 with mock.patch('bleachbit.FileUtilities.get_filesystem_type', return_value=('ntfs',)), \
387 mock.patch('bleachbit.Wipe.os.path.isdir', return_value=False):
388 results = list(wipe_path('/not-a-directory'))
389 self.assertEqual(results, [])
390
391 def test_wipe_path_fitrim(self):
392 """Test fitrim is called for ext4/btrfs but not other filesystems"""
393 for fs_type, should_call_fitrim in [('ext4', True), ('btrfs', True), ('ntfs', False)]:
394 with self.subTest(fs_type=fs_type):
395 mock_file = self._make_mock_file()
396 mock_file.write.side_effect = IOError(
397 errno.EFBIG, 'File too large')
398 with self._wipe_path_common_mocks(fs_type=fs_type) as stack:
399 mock_fitrim = stack.enter_context(
400 mock.patch('bleachbit.Wipe.fitrim'))
401 stack.enter_context(mock.patch(
402 'bleachbit.Wipe.tempfile.NamedTemporaryFile', return_value=mock_file))
403 list(wipe_path(self.tempdir))
404 if should_call_fitrim:
405 mock_fitrim.assert_called_once()
406 else:
407 mock_fitrim.assert_not_called()
408
409 def test_wipe_path_tempfile_enametoolong_retry(self):
410 """Temporary file creation retries with shorter name on ENAMETOOLONG"""
411 mock_file = self._make_mock_file()
412 mock_file.write.side_effect = IOError(errno.EFBIG, 'File too large')
413 ntf_mock = mock.Mock()
414 ntf_mock.side_effect = [
415 OSError(errno.ENAMETOOLONG, 'File name too long'),
416 mock_file
417 ]
418 with self._wipe_path_common_mocks() as stack:
419 stack.enter_context(mock.patch(
420 'bleachbit.Wipe.tempfile.NamedTemporaryFile', ntf_mock))
421 list(wipe_path(self.tempdir))
422 self.assertEqual(ntf_mock.call_count, 2)
423 first_suffix = ntf_mock.call_args_list[0][1]['suffix']
424 second_suffix = ntf_mock.call_args_list[1][1]['suffix']
425 self.assertEqual(len(first_suffix), 185)
426 self.assertEqual(len(second_suffix), 180)
427
428 def test_wipe_path_write_enospc(self):
429 """Write loop handles ENOSPC by reducing block size"""
430 mock_file = self._make_mock_file()
431 call_count = 0
432
433 def side_effect(data):
434 nonlocal call_count
435 call_count += 1
436 if call_count == 1 and len(data) == 65536:
437 raise IOError(errno.ENOSPC, 'No space left on device')
438 if call_count == 2:
439 return len(data)
440 raise IOError(errno.EFBIG, 'File too large')
441 mock_file.write.side_effect = side_effect
442 with self._wipe_path_common_mocks(), \
443 mock.patch('bleachbit.Wipe.tempfile.NamedTemporaryFile', return_value=mock_file):
444 list(wipe_path(self.tempdir))
445 self.assertGreaterEqual(mock_file.write.call_count, 2)
446 first_call_len = len(mock_file.write.call_args_list[0][0][0])
447 second_call_len = len(mock_file.write.call_args_list[1][0][0])
448 self.assertEqual(first_call_len, 65536)
449 self.assertEqual(second_call_len, 32768)
450
451 def test_wipe_path_write_persistent_edquot(self):
452 """Persistent EDQUOT (even at 1-byte blocks) stops the outer loop.
453
454 When every write fails with EDQUOT (errno 122, "Disk quota
455 exceeded"), the inner loop halves the block down to 1 byte and
456 then sets ``disk_full`` so the outer loop breaks instead of
457 spinning forever creating empty temp files.
458
459 This reproduces a scenario seen on on Linux with /tmp on a small tmpfs
460 using usrquota with a significant gap between available space and the
461 quota. Other processes (like other tests running in parallel with
462 pytest-xdist) failed when not being able to write to /tmp.
463
464 In this test, ``NamedTemporaryFile`` is allowed to create one file and
465 then raises EDQUOT. With the fix, ``disk_full`` breaks the outer loop
466 after the first file, so ``NamedTemporaryFile`` is called exactly once.
467 Without the fix, the outer loop would call it again.
468 """
469 mock_file = self._make_mock_file()
470 mock_file.write.side_effect = IOError(
471 errno.EDQUOT, 'Disk quota exceeded')
472 mock_file.tell.return_value = 0
473 ntf_calls = [0]
474
475 # ntf=NamedTemporaryFile
476 def ntf_side_effect(*_args, **_kwargs):
477 ntf_calls[0] += 1
478 if ntf_calls[0] == 1:
479 return mock_file
480 raise OSError(errno.EDQUOT, 'Disk quota exceeded')
481 with self._wipe_path_common_mocks() as stack:
482 # Simulate EDQUOT despite adequete free space
483 stack.enter_context(mock.patch(
484 'bleachbit.FileUtilities.free_space', return_value=196 * 1024 * 1024))
485 stack.enter_context(mock.patch(
486 'bleachbit.Wipe.tempfile.NamedTemporaryFile', side_effect=ntf_side_effect))
487 list(wipe_path(self.tempdir))
488 # With the fix, disk_full breaks the outer loop after the first file.
489 self.assertEqual(ntf_calls[0], 1)
490 # Block was halved down to 1 byte before giving up.
491 last_call_len = len(mock_file.write.call_args_list[-1][0][0])
492 self.assertEqual(last_call_len, 1)
493
494 def test_wipe_path_fsync_edquot(self):
495 """EDQUOT from fsync stops the outer loop."""
496 mock_file = self._make_mock_file()
497 mock_file.write.side_effect = IOError(errno.EFBIG, 'File too large')
498 ntf_mock = mock.Mock(side_effect=[
499 mock_file,
500 AssertionError('wipe_path created another temporary file')
501 ])
502 with self._wipe_path_common_mocks() as stack:
503 stack.enter_context(mock.patch(
504 'bleachbit.FileUtilities.free_space', return_value=196 * 1024 * 1024))
505 stack.enter_context(mock.patch(
506 'bleachbit.Wipe.tempfile.NamedTemporaryFile', ntf_mock))
507 fsync_mock = stack.enter_context(mock.patch(
508 'bleachbit.Wipe.os.fsync', side_effect=[
509 OSError(errno.EDQUOT, 'Disk quota exceeded'), None]))
510 list(wipe_path(self.tempdir))
511 self.assertEqual(fsync_mock.call_count, 2)
512 self.assertEqual(ntf_mock.call_count, 1)
513
514 def test_wipe_path_write_efbig(self):
515 """Write loop handles EFBIG by breaking"""
516 mock_file = self._make_mock_file()
517 mock_file.write.side_effect = IOError(errno.EFBIG, 'File too large')
518 with self._wipe_path_common_mocks(), \
519 mock.patch('bleachbit.Wipe.tempfile.NamedTemporaryFile', return_value=mock_file):
520 list(wipe_path(self.tempdir))
521 mock_file.write.assert_called_once()
522
523 def test_wipe_path_flush_enospc(self):
524 """Flush handles ENOSPC without error"""
525 mock_file = self._make_mock_file()
526 write_call_count = 0
527
528 def write_side_effect(data):
529 nonlocal write_call_count
530 write_call_count += 1
531 if write_call_count == 1:
532 return len(data)
533 raise IOError(errno.EFBIG, 'File too large')
534 mock_file.write.side_effect = write_side_effect
535 mock_file.flush.side_effect = IOError(
536 errno.ENOSPC, 'No space left on device')
537 with self._wipe_path_common_mocks(), \
538 mock.patch('bleachbit.Wipe.tempfile.NamedTemporaryFile', return_value=mock_file):
539 list(wipe_path(self.tempdir))
540 self.assertGreaterEqual(mock_file.flush.call_count, 1)
541
542 def test_wipe_path_idle_yields_eta(self):
543 """idle=True yields estimate completion tuples"""
544 mock_file = self._make_mock_file()
545 write_call_count = 0
546
547 def write_side_effect(data):
548 nonlocal write_call_count
549 write_call_count += 1
550 if write_call_count == 1:
551 return len(data)
552 raise IOError(errno.EFBIG, 'File too large')
553 mock_file.write.side_effect = write_side_effect
554
555 def time_side_effect():
556 if write_call_count == 0:
557 return 0.0
558 if write_call_count == 1:
559 return 3.0
560 return 4.0
561 with self._wipe_path_common_mocks() as stack:
562 stack.enter_context(mock.patch(
563 'bleachbit.Wipe.tempfile.NamedTemporaryFile', return_value=mock_file))
564 stack.enter_context(mock.patch(
565 'bleachbit.Wipe.time.time', side_effect=time_side_effect))
566 results = list(wipe_path(self.tempdir, idle=True))
567 self.assertGreater(len(results), 0)
568 for result in results:
569 self.assertIsInstance(result, tuple)
570 self.assertEqual(len(result), 3)
571
572 def test_wipe_path_cleanup_finally(self):
573 """Cleanup runs in finally even when truncate_f fails"""
574 mock_file = self._make_mock_file()
575 mock_file.write.side_effect = IOError(errno.EFBIG, 'File too large')
576 with self._wipe_path_common_mocks() as stack:
577 stack.enter_context(mock.patch(
578 'bleachbit.Wipe.tempfile.NamedTemporaryFile', return_value=mock_file))
579 stack.enter_context(mock.patch(
580 'bleachbit.FileUtilities.truncate_f', side_effect=RuntimeError('boom')))
581 list(wipe_path(self.tempdir))
582 mock_file.close.assert_called_once()
583 stack.delete_mock.assert_called_once_with(
584 mock_file.name, ignore_missing=True)