Debian Codegraph @

tests/TestWinapp.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 cases for module Winapp
9 """
10
11 import os
12 import re
13 import shutil
14 import stat
15 import string
16 import time
17 from contextlib import suppress
18 from unittest import mock
19
20 from tests.common import pytest
21
22 from tests import common
23 import bleachbit
24 from bleachbit.Winapp import Winapp, detectos, detect_file, fnmatch_translate, list_winapp_files, section2option
25 from bleachbit.Windows import detect_registry_key, parse_windows_build
26 from bleachbit import IS_WINDOWS, logger
27 from bleachbit.FileUtilities import extended_path_undo
28 from bleachbit.PathUtils import path_startswith
29
30 if IS_WINDOWS:
31 import winreg
32
33
34 def _create_registry_keys(*key_paths):
35 """Create registry keys, ignoring errors if they already exist"""
36 if not IS_WINDOWS:
37 return
38 for key_path in key_paths:
39 with suppress(OSError):
40 hkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_path)
41 hkey.Close()
42
43
44 def _delete_registry_keys(*key_paths):
45 """Delete registry keys, ignoring errors if they don't exist"""
46 if not IS_WINDOWS:
47 return
48 for key_path in key_paths:
49 with suppress(OSError):
50 winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path)
51
52
53 KEYFULL = 'HKCU\\Software\\BleachBit\\DeleteThisKey'
54
55
56 def get_winapp2():
57 """Download and cache winapp2.ini. Return local filename."""
58 url = ("https://raw.githubusercontent.com/bleachbit/winapp2.ini"
59 "/refs/heads/master/Winapp2-BleachBit.ini")
60 tmpdir = common.get_volatile_dir()
61 fname = os.path.join(tmpdir, 'bleachbit_test_winapp2.ini')
62 if os.path.exists(fname):
63 age_seconds = time.time() - os.stat(fname)[stat.ST_MTIME]
64 if age_seconds > (24 * 36 * 36):
65 logger.info('deleting stale file %s ', fname)
66 os.remove(fname)
67 if not os.path.exists(fname):
68 from bleachbit.Network import download_url_to_fn
69 assert download_url_to_fn(url, fname)
70 assert os.path.exists(fname)
71 return fname
72
73
74 class WinappTestCase(common.BleachbitTestCase):
75 """Test cases for Winapp"""
76
77 ini_fn = None
78
79 def run_all(self, cleaner, really_delete, allow_volatile=False):
80 """Test all cleaner options, optionally tolerating volatile paths"""
81 volatile_dir = common.get_volatile_dir()
82
83 def is_volatile(path):
84 if not (allow_volatile and path):
85 return False
86 if IS_WINDOWS:
87 path = extended_path_undo(path)
88 return path_startswith(path, volatile_dir)
89
90 for (option_id, __name) in cleaner.get_options():
91 for cmd in cleaner.get_commands(option_id):
92 try:
93 for result in cmd.execute(really_delete):
94 common.validate_result(
95 self, result, really_delete,
96 allow_vanishing=is_volatile(result.get('path')))
97 except FileNotFoundError as e:
98 # Tolerate vanished files in the volatile temporary directory.
99 # FileNotFoundError may carry no filename (e.g. pywinerror -> OSError
100 # conversions); tolerate it when allow_volatile is set.
101 if not (allow_volatile and (e.filename is None or is_volatile(e.filename))):
102 raise
103 logger.debug('TOCTOU: file vanished: %s', e.filename)
104
105 def test_run_all_volatile(self):
106 """Allow paths in the volatile temporary directory to vanish"""
107 path = os.path.join(self.tempdir, 'vanished')
108 result = {'label': 'Delete', 'n_deleted': 1, 'n_special': 0,
109 'path': path, 'size': 0}
110 cmd = mock.Mock()
111 cmd.execute.return_value = iter((result,))
112 cleaner = mock.Mock()
113 cleaner.get_options.return_value = (('option', 'name'),)
114 cleaner.get_commands.return_value = (cmd,)
115 self.run_all(cleaner, False, allow_volatile=True)
116
117 cmd.execute.return_value = iter((result,))
118 with self.assertRaises(AssertionError):
119 self.run_all(cleaner, False)
120
121 cmd.execute.side_effect = FileNotFoundError(2, 'vanished', path)
122 self.run_all(cleaner, False, allow_volatile=True)
123
124 with self.assertRaises(FileNotFoundError):
125 self.run_all(cleaner, False)
126
127 # Non-volatile paths must not be tolerated even when allow_volatile is set.
128 non_volatile_path = (r'C:\bleachbit_nonexistent_test_path'
129 if IS_WINDOWS else '/bleachbit_nonexistent_test_path')
130 non_volatile_result = {'label': 'Delete', 'n_deleted': 1, 'n_special': 0,
131 'path': non_volatile_path, 'size': 0}
132 cmd.execute.side_effect = None
133 cmd.execute.return_value = iter((non_volatile_result,))
134 with self.assertRaises(AssertionError):
135 self.run_all(cleaner, False, allow_volatile=True)
136
137 cmd.execute.side_effect = FileNotFoundError(2, 'vanished', non_volatile_path)
138 with self.assertRaises(FileNotFoundError):
139 self.run_all(cleaner, False, allow_volatile=True)
140
141 # FileNotFoundError may carry no filename (e.g. pywinerror -> OSError
142 # conversions); tolerate it when allow_volatile is set.
143 cmd.execute.side_effect = FileNotFoundError(2, 'vanished')
144 self.run_all(cleaner, False, allow_volatile=True)
145
146 with self.assertRaises(FileNotFoundError):
147 self.run_all(cleaner, False)
148
149 @common.skipUnlessWindows
150 def test_remote(self):
151 """Test with downloaded file"""
152 try:
153 fname = get_winapp2()
154 except AssertionError as e:
155 self.skipTest(f'real network unavailable: {e}')
156 else:
157 winapps = Winapp(fname)
158 for cleaner in winapps.get_cleaners():
159 self.run_all(cleaner, False, allow_volatile=True)
160
161 def test_detectos(self):
162 """Test detectos function"""
163 # Tests are in the format (required_ver, mock, expected_return)
164 tests = (('5.1', '5.1', True),
165 ('5.1', '6.0', False),
166 ('6.0', '5.1', False),
167 # 5.1 is the maximum version
168 ('|5.1', '5.1', True),
169 ('|5.1', '6.0', False),
170 ('|5.1', '10.0', False),
171 # 10.0 is the maximum version
172 ('|10.0', '5.1', True),
173 ('|10.0', '10.0', True),
174 ('|10.0', '10.1', False),
175 # 6.1 is the minimum version
176 ('6.1|', '5.1', False),
177 ('6.1|', '6.0', False),
178 ('6.1|', '6.1', True),
179 ('6.1|', '6.2', True),
180 ('6.1|', '10.0', True),
181 ('6.2|', '5.1', False),
182 ('6.2|', '6.0', False),
183 ('6.2|', '6.1', False),
184 ('6.2|', '6.2', True),
185 # must be 6.2 or 6.3
186 ('6.2|6.3', '6.0', False),
187 ('6.2|6.3', '6.1', False),
188 ('6.2|6.3', '6.2', True),
189 ('6.2|6.3', '6.3', True),
190 ('6.2|6.3', '10.0', False),
191 # 10.0 is the minimum
192 ('10.0|', '5.1', False),
193 ('10.0|', '10.0', True))
194 for (req, mock_ver, expected_return) in tests:
195 mock_ver = parse_windows_build(mock_ver)
196 actual_return = detectos(req, mock_ver)
197 msg = (f'detectos({req}, {mock_ver})=={actual_return}'
198 f' instead of {expected_return}')
199 self.assertEqual(expected_return, actual_return, msg)
200
201 @common.skipUnlessWindows
202 def test_detect_file(self):
203 """Test detect_file function"""
204 tests = [('%windir%\\system32\\kernel32.dll', True),
205 ('%windir%\\system32', True),
206 ('%ProgramFiles%\\Internet Explorer', True),
207 ('%ProgramFiles%\\Internet Explorer\\', True),
208 ('%windir%\\doesnotexist', False),
209 ('%windir%\\system*', True),
210 ('%windir%\\*ystem32', True),
211 ('%windir%\\*ystem3*', True)]
212 # On 64-bit Windows, Winapp2.ini expands the %ProgramFiles% environment
213 # variable to also %ProgramW6432%, so test unique entries in
214 # %ProgramW6432%.
215 if os.getenv('ProgramW6432'):
216 dir_64 = os.listdir(os.getenv('ProgramFiles'))
217 dir_32 = os.listdir(os.getenv('ProgramW6432'))
218 dir_32_unique = set(dir_32) - set(dir_64)
219 if dir_32 and not dir_32_unique and bleachbit.ARCH_BITS == 32:
220 raise RuntimeError(
221 'Test expects objects in %ProgramW6432% not in %ProgramFiles%')
222 for pathname in dir_32_unique:
223 tests.append((f'%ProgramFiles%\\{pathname}', True))
224 else:
225 logger.info(
226 'skipping %ProgramW6432% tests because WoW64 not detected')
227 for pathname, expected_return in tests:
228 actual_return = detect_file(pathname)
229 msg = f'detect_file({pathname}) returned {actual_return}'
230 self.assertEqual(expected_return, actual_return, msg)
231
232 def setup_fake(self, f1_filename=None):
233 """Setup the test environment"""
234 subkey = 'Software\\BleachBit\\DeleteThisKey\\AndThisKey'
235
236 # put ampersand in directory name to test
237 # https://github.com/bleachbit/bleachbit/issues/308
238 dirname = self.mkdtemp(prefix='bleachbit-test-winapp&')
239 fname1 = self.write_file(os.path.join(
240 dirname, f1_filename or 'deleteme.log'), b'', 'wb')
241
242 dirname2 = self.mkdir(os.path.join(dirname, 'sub'))
243 fname2 = self.write_file(os.path.join(
244 dirname2, 'deleteme.log'), b'', 'wb')
245
246 fbak = self.write_file(os.path.join(
247 dirname, 'deleteme.bak'), b'', 'wb')
248
249 self.assertExists(fname1)
250 self.assertExists(fname2)
251 self.assertExists(fbak)
252
253 _create_registry_keys(subkey)
254
255 self.assertTrue(detect_registry_key(KEYFULL))
256 self.assertTrue(detect_registry_key(f'HKCU\\{subkey}'))
257
258 return dirname, fname1, fname2, fbak
259
260 def ini2cleaner(self, body, do_next=True):
261 """Write a minimal Winapp2.ini"""
262 with open(self.ini_fn, 'w', encoding='utf-8') as ini:
263 ini.write('[someapp]\nLangSecRef=3021\n' + body + '\n')
264 self.assertExists(self.ini_fn)
265 if do_next:
266 return next(Winapp(self.ini_fn).get_cleaners())
267 return Winapp(self.ini_fn).get_cleaners()
268
269 @common.skipUnlessWindows
270 @pytest.mark.xdist_group('winapp-registry')
271 def test_fake(self):
272 """Test with fake file"""
273
274 # reuse this path to store a winapp2.ini file in
275 self.ini_fn = self.mkstemp(suffix='.ini', prefix='winapp2')
276
277 # a set of tests
278 # this map explains what each position in the test tuple means
279 # 0=line to write directly to winapp2.ini
280 # 1=filename1 to place in fake environment (default=deleteme.log)
281 # 2=auto-hide before cleaning
282 # 3=dirname exists after cleaning
283 # 4=filename1 (.\deleteme.log) exists after cleaning
284 # 5=sub\deleteme.log exists after cleaning
285 # 6=.\deleteme.bak exists after cleaning
286 tests = [
287 # single file
288 ('FileKey1=%s|deleteme.log', None,
289 False, True, False, True, True),
290 # single file, case matching should be insensitive
291 ('FileKey1=%s|dEleteme.LOG', None,
292 False, True, False, True, True),
293 # special characters for XML
294 ('FileKey1=%s|special_chars_&-\'.txt', 'special_chars_&-\'.txt',
295 False, True, False, True, True),
296 # *.log
297 ('FileKey1=%s|*.LOG', None, False, True, False, True, True),
298 # semicolon separates different file types
299 ('FileKey1=%s|*.log;*.bak', None,
300 False, True, False, True, False),
301 # *.*
302 ('FileKey1=%s|*.*', None, False, True, False, True, False),
303 # recurse *.*
304 ('FileKey1=%s|*.*|RECURSE', None, False,
305 True, False, False, False),
306 # recurse *.log
307 ('FileKey1=%s|*.log|RECURSE', None, False,
308 True, False, False, True),
309 # remove self *.*, this removes the directory
310 ('FileKey1=%s|*.*|REMOVESELF', None,
311 False, False, False, False, False),
312 ]
313
314 # Add positive detection, where the detection believes the application is present,
315 # to all the tests, which are also positive.
316 new_tests = []
317 for test in tests:
318 for detect in (
319 "\nDetectFile=%%APPDATA%%\\Microsoft",
320 "\nSpecialDetect=DET_WINDOWS",
321 "\nDetectFile1=%%APPDATA%%\\Microsoft\nDetectFile2=%%APPDATA%%\\does_not_exist",
322 "\nDetectFile1=%%APPDATA%%\\does_not_exist\nDetectFile2=%%APPDATA%%\\Microsoft",
323 "\nDetect=HKCU\\Software\\Microsoft",
324 # Below checks that a space is OK in the registry key
325 "\nDetect=HKCU\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
326 # Below checks Detect# where one of two keys exist.
327 "\nDetect1=HKCU\\Software\\Microsoft\nDetect2=HKCU\\Software\\does_not_exist",
328 "\nDetect1=HKCU\\Software\\does_not_exist\nDetect2=HKCU\\Software\\Microsoft",
329 # Below checks Detect with DetectFile where one exists
330 "\nDetect=HKCU\\Software\\Microsoft\nDetectFile=%%APPDATA%%\\does_not_exist",
331 "\nDetect=HKCU\\Software\\does_not_exist\nDetectFile=%%APPDATA%%\\Microsoft"):
332 new_ini = test[0] + detect
333 new_test = [new_ini, ] + list(test[1:])
334 new_tests.append(new_test)
335 positive_tests = tests + new_tests
336
337 # execute positive tests
338 for test in positive_tests:
339 print('positive test: ', test)
340 self.assertEqual(len(test), 7)
341 (dirname, fname1, fname2, fbak) = self.setup_fake(test[1])
342 cleaner = self.ini2cleaner(test[0] % dirname)
343 self.assertEqual(test[2], cleaner.auto_hide())
344 self.run_all(cleaner, False)
345 self.run_all(cleaner, True)
346 self.assertCondExists(test[3], dirname)
347 self.assertCondExists(test[4], fname1)
348 self.assertCondExists(test[5], fname2)
349 self.assertCondExists(test[6], fbak)
350 shutil.rmtree(dirname, True)
351
352 # negative tests where the application detect believes the application
353 # is absent
354 for test in tests:
355 for detect in (
356 "\nDetectFile=c:\\does_not_exist",
357 "\nSpecialDetect=DET_SPACE_QUEST",
358 # special characters for XML
359 "\nDetectFile=c:\\does_not_exist_special_chars_&'",
360 "\nDetectFile1=c:\\does_not_exist1\nDetectFile2=c:\\does_not_exist2",
361 "\nDetect=HKCU\\Software\\does_not_exist",
362 "\nDetect=HKCU\\Software\\does_not_exist_&'",
363 "\nDetect1=HKCU\\Software\\does_not_exist1"
364 "\nDetect2=HKCU\\Software\\does_not_exist1"):
365 new_ini = test[0] + detect
366 test_full = [new_ini, ] + list(test[1:])
367 print('negative test', test_full)
368 # execute the test
369 (dirname, fname1, fname2, fbak) = self.setup_fake()
370 cleaner = self.ini2cleaner(test_full[0] % dirname, False)
371 self.assertRaises(StopIteration, cleaner.__next__)
372 shutil.rmtree(dirname, True)
373
374 # registry key, basic
375 (dirname, fname1, fname2, fbak) = self.setup_fake()
376 cleaner = self.ini2cleaner(f'RegKey1={KEYFULL}')
377 self.run_all(cleaner, False)
378 self.assertTrue(detect_registry_key(KEYFULL))
379 self.run_all(cleaner, True)
380 self.assertFalse(detect_registry_key(KEYFULL))
381 shutil.rmtree(dirname, True)
382
383 # check for parse error with ampersand
384 (dirname, fname1, fname2, fbak) = self.setup_fake()
385 cleaner = self.ini2cleaner(
386 'RegKey1=HKCU\\Software\\PeanutButter&Jelly')
387 self.run_all(cleaner, False)
388 self.run_all(cleaner, True)
389 shutil.rmtree(dirname, True)
390
391 @common.skipUnlessWindows
392 def test_excludekey(self):
393 """Test for ExcludeKey"""
394
395 # reuse this path to store a winapp2.ini file in
396 self.ini_fn = self.mkstemp(suffix='.ini', prefix='winapp2')
397
398 # Each tuple contains:
399 # [0] = Body of winapp2.ini configuration
400 # [1] = Whether .\deleteme.log should exist after cleaning (True=exists)
401 # [2] = Whether .\deleteme.bak should exist after cleaning (True=exists)
402 # [3] = Whether sub\deleteme.log should exist after cleaning (True=exists)
403 #
404 # Path notation:
405 # %(d)s - Literal test directory path without a trailing backslash
406 # %(d)s\\ - Literal directory with a trailing backslash
407 # %%bbtestdir%% - Literal environment variable that resolves to same test directory
408
409 tests = (
410 # delete everything in single directory (no children) without
411 # exclusions
412 ('FileKey1=%(d)s|deleteme.*', False, False, True),
413 # delete everything in single directory using environment variable
414 ('FileKey1=%%bbtestdir%%|deleteme.*', False, False, True),
415 # delete everything in parent and child directories without
416 # exclusions
417 ('FileKey1=%(d)s|deleteme.*|RECURSE', False, False, False),
418 # don't delete files containing the described file name
419 ('FileKey1=%(d)s|eteme.*|RECURSE', True, True, True),
420 # delete a pattern sub folder included
421 ('FileKey1=%(d)s|*eteme.*|RECURSE', False, False, False),
422 # delete a pattern sub folder not included
423 ('FileKey1=%(d)s|*eteme.*', False, False, True),
424 # exclude log delimited by pipe
425 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=FILE|%(d)s|deleteme.log',
426 True, False, True),
427 # trailing backslash should work the same as without
428 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=FILE|%(d)s\\|deleteme.log',
429 True, False, True),
430 # delete / exclude patterns with different complexity
431 ('FileKey1=%(d)s|*eteme.*\nExcludeKey1=FILE|%(d)s|deleteme.log',
432 True, False, True),
433 ('FileKey1=%(d)s|*eteme.*\nExcludeKey1=FILE|%(d)s\\|deleteme.log',
434 True, False, True),
435 ('FileKey1=%(d)s|*ete*.*\nExcludeKey1=PATH|%(d)s|*ete*.lo?',
436 True, False, True),
437 ('FileKey1=%(d)s|*eteme*\nExcludeKey1=PATH|%(d)s|*notexist.*',
438 False, False, True),
439 ('FileKey1=%(d)s|*eteme.log\nExcludeKey1=PATH|%(d)s|do*.log',
440 False, True, True),
441 # semicolon separates different file types
442 ('FileKey1=%(d)s|*.log;*.bak|RECURSE\nExcludeKey1=PATH|%(d)s|*.log',
443 True, False, True),
444 # exclude log without pipe delimiter
445 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=FILE|%(d)s\\deleteme.log',
446 True, False, True),
447 # exclude everything in folder
448 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=PATH|%(d)s|*.*',
449 True, True, True),
450 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=PATH|%(d)s\\|*.*',
451 True, True, True),
452 ('FileKey1=%(d)s|deleteme.*|RECURSE\nExcludeKey1=PATH|%(d)s|*.*',
453 True, True, True),
454 ('FileKey1=%(d)s|*.*|RECURSE\nExcludeKey1=PATH|%(d)s|*.*',
455 True, True, True),
456 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=PATH|%(d)s',
457 True, True, True),
458 # exclude everything in folder using environment variable
459 # use double %% to escape
460 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=PATH|%%bbtestdir%%|*.*',
461 True, True, True),
462 # exclude sub-folder
463 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=PATH|%(d)s\\sub',
464 False, False, True),
465 # exclude multiple file types that do not exist
466 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=PATH|%(d)s|*.exe;*.dll',
467 False, False, True),
468 # exclude multiple file types that do exist, so dlete nothing
469 ('FileKey1=%(d)s|deleteme.*\nExcludeKey1=PATH|%(d)s|*.bak;*.log',
470 True, True, True),
471 ('FileKey1=%(d)s|deleteme.*|RECURSE\nExcludeKey1=PATH|%(d)s|*.bak;*.log',
472 True, True, True),
473 # multiple ExcludeKey, neither of which should do anything
474 ('FileKey1=%(d)s|deleteme.*|RECURSE'
475 '\nExcludeKey1=PATH|c:\\doesnotexist|*.*'
476 '\nExcludeKey2=PATH|c:\\alsodoesnotexist\\|*.*',
477 False, False, False),
478 # multiple ExcludeKey, the first should work
479 ('FileKey1=%(d)s|deleteme.*|RECURSE'
480 '\nExcludeKey1=PATH|%(d)s|*.log'
481 '\nExcludeKey2=PATH|c:\\alsodoesnotexist\\|*.*',
482 True, False, True),
483 # multiple ExcludeKey, both should work
484 ('FileKey1=%(d)s|deleteme.*|RECURSE'
485 '\nExcludeKey1=PATH|%(d)s|*.log'
486 '\nExcludeKey2=PATH|%(d)s|*.bak',
487 True, True, True),
488 # glob should exclude the directory called 'sub'
489 ('FileKey1=%(d)s|*.*\nExcludeKey1=PATH|%(d)s\\s*',
490 False, False, True),
491 )
492
493 for test in tests:
494 msg = f'\nTest:\n{test[0]}'
495 # setup
496 (dirname, _fname1, _fname2, _fbak) = self.setup_fake()
497 self.assertExists(rf'{dirname}\deleteme.log', msg)
498 self.assertExists(rf'{dirname}\deleteme.bak', msg)
499 self.assertExists(rf'{dirname}\sub\deleteme.log', msg)
500 # set environment variable for testing
501 with common.set_temporary_env('bbtestdir', dirname):
502 self.assertExists(r'$bbtestdir\deleteme.log', msg)
503 # delete files
504 cleaner = self.ini2cleaner(test[0] % {'d': dirname})
505 self.run_all(cleaner, True)
506 # test
507 self.assertCondExists(test[1], rf'{dirname}\deleteme.log', msg)
508 self.assertCondExists(test[2], rf'{dirname}\deleteme.bak', msg)
509 self.assertCondExists(
510 test[3], rf'{dirname}\sub\deleteme.log', msg)
511
512 # cleanup
513 shutil.rmtree(dirname, True)
514
515 @common.skipUnlessWindows
516 def test_excludekey_star_dot_star_extensionless(self):
517 """Test ExcludeKey *.* on a file without an extension"""
518 self.ini_fn = self.mkstemp(suffix='.ini', prefix='winapp2')
519
520 def make_dir():
521 dirname = self.mkdtemp(prefix='bleachbit-test-winapp')
522 self.write_file(os.path.join(dirname, 'deleteme'), b'', 'wb')
523 self.write_file(os.path.join(dirname, 'deleteme.log'), b'', 'wb')
524 return dirname
525
526 # without the exclude, the FileKey deletes the extensionless file
527 dirname = make_dir()
528 cleaner = self.ini2cleaner(f'FileKey1={dirname}|deleteme*')
529 self.run_all(cleaner, True)
530 self.assertNotExists(rf'{dirname}\deleteme')
531 shutil.rmtree(dirname, True)
532
533 # *.* excludes the whole folder
534 dirname = make_dir()
535 body = (f'FileKey1={dirname}|deleteme*'
536 f'\nExcludeKey1=PATH|{dirname}|*.*')
537 cleaner = self.ini2cleaner(body)
538 self.run_all(cleaner, True)
539 self.assertExists(rf'{dirname}\deleteme')
540 self.assertExists(rf'{dirname}\deleteme.log')
541 shutil.rmtree(dirname, True)
542
543 def _verify_keys_state(self, expected_state):
544 """Verify registry keys match expected state (dict of key_path -> exists)"""
545 for key_path, should_exist in expected_state.items():
546 exists = detect_registry_key('HKCU\\' + key_path)
547 if should_exist:
548 self.assertTrue(exists, f'Key {key_path} should exist')
549 else:
550 self.assertFalse(exists, f'Key {key_path} should not exist')
551
552 @common.skipUnlessWindows
553 @pytest.mark.xdist_group('winapp-registry')
554 def test_excludekey_reg(self):
555 """Test for ExcludeKey with REG type to prevent registry key deletion"""
556
557 # reuse this path to store a winapp2.ini file in
558 self.ini_fn = self.mkstemp(suffix='.ini', prefix='winapp2')
559
560 test_key_parent = r'Software\BleachBitTest\ExcludeKey'
561 test_key_child0 = rf'{test_key_parent}\Child0'
562 test_key_child1 = rf'{test_key_parent}\Child1'
563 test_key_not_exc = f'{test_key_parent}_NotExcluded'
564
565 tests = (
566 # (exclude_key, parent_should_remain, child0_should_remain, child1_should_remain)
567 # Excluding a child key also implicitly protects the parent,
568 # since the parent must exist for the excluded child to persist.
569 (test_key_parent, True, True, True),
570 (test_key_child0, True, True, False),
571 (test_key_child1, True, False, True),
572 )
573
574 for exclude_key, parent_should_remain, child0_should_remain, child1_should_remain in tests:
575 with self.subTest(exclude_key=exclude_key):
576 try:
577 _create_registry_keys(
578 test_key_parent, test_key_child0,
579 test_key_child1, test_key_not_exc)
580 cleaner_ini = f'''RegKey1=HKCU\\{test_key_parent}
581 RegKey2=HKCU\\{test_key_child0}
582 RegKey3=HKCU\\{test_key_child1}
583 RegKey4=HKCU\\{test_key_not_exc}
584 ExcludeKey1=REG|HKCU\\{exclude_key}'''
585 cleaner = self.ini2cleaner(cleaner_ini)
586 self.run_all(cleaner, False)
587 self._verify_keys_state({
588 test_key_parent: True,
589 test_key_child0: True,
590 test_key_child1: True,
591 test_key_not_exc: True,
592 })
593 self.run_all(cleaner, True)
594 self._verify_keys_state({
595 test_key_parent: parent_should_remain,
596 test_key_child0: child0_should_remain,
597 test_key_child1: child1_should_remain,
598 test_key_not_exc: False,
599 })
600 finally:
601 _delete_registry_keys(
602 test_key_parent, test_key_child0,
603 test_key_child1, test_key_not_exc)
604
605 def test_regkey_action_kept(self):
606 """RegKey actions are kept wherever winapp2.ini lives"""
607 self.ini_fn = self.mkstemp(suffix='.ini', prefix='winapp2-trust')
608 with open(self.ini_fn, 'w', encoding='utf-8') as ini:
609 ini.write('[someapp]\nLangSecRef=3021\n'
610 'FileKey1=%Temp%|bleachbit-test-does-not-exist.tmp\n'
611 f'RegKey1={KEYFULL}\n')
612
613 cleaner = next(Winapp(self.ini_fn).get_cleaners())
614 actions = [a.__class__.__name__ for (_option_id, a) in cleaner.actions]
615 self.assertIn('Winreg', actions)
616 self.assertIn('Delete', actions)
617
618 def test_filekey_recurse_rejects_excessive_wildcards(self):
619 """A FileKey RECURSE pattern with too many wildcards is rejected (ReDoS defense)"""
620 self.ini_fn = self.mkstemp(suffix='.ini', prefix='winapp2-redos')
621 with open(self.ini_fn, 'w', encoding='utf-8') as ini:
622 ini.write('[someapp]\nLangSecRef=3021\n'
623 'FileKey1=%Temp%|' + '*a' * 11 + '|RECURSE\n')
624 winapp = Winapp(self.ini_fn)
625 self.assertEqual(winapp.errors, 1)
626
627 @common.skipIfWindows
628 def test_list_winapp_files_skips_world_writable(self):
629 """A world-writable winapp2.ini is ignored, like CleanerML XML"""
630 pcd = bleachbit.personal_cleaners_dir
631 bleachbit.personal_cleaners_dir = self.mkdtemp(
632 prefix='bleachbit-winapp-worldwritable')
633 try:
634 fn = os.path.join(bleachbit.personal_cleaners_dir, 'winapp2.ini')
635 self.write_file(fn, text='[test]\n')
636 os.chmod(fn, 0o666)
637 self.assertNotIn(fn, list(list_winapp_files()))
638 os.chmod(fn, 0o644)
639 self.assertIn(fn, list(list_winapp_files()))
640 finally:
641 bleachbit.personal_cleaners_dir = pcd
642
643 @common.skipIfWindows
644 def test_list_winapp_files_skips_world_writable_dir(self):
645 """A winapp2.ini in a world-writable directory is ignored"""
646 pcd = bleachbit.personal_cleaners_dir
647 wwdir = self.mkdtemp(prefix='bleachbit-winapp-wwdir')
648 bleachbit.personal_cleaners_dir = wwdir
649 try:
650 fn = os.path.join(wwdir, 'winapp2.ini')
651 self.write_file(fn, text='[test]\n')
652 os.chmod(fn, 0o644)
653 os.chmod(wwdir, 0o777)
654 self.assertNotIn(fn, list(list_winapp_files()))
655 os.chmod(wwdir, 0o755)
656 self.assertIn(fn, list(list_winapp_files()))
657 finally:
658 os.chmod(wwdir, 0o755)
659 bleachbit.personal_cleaners_dir = pcd
660
661 @common.skipUnlessWindows
662 def test_filekey_with_path_including_systemdrive(self):
663 """Test FileKey with path including SystemDrive"""
664 self.ini_fn = self.mkstemp(suffix='.ini', prefix='winapp2')
665 # lexists(r'C:filename') returns False
666 # FindFilesW(r'C:filename') throws an exception
667 # So assert that we use r'C:\filename'.
668 # We need this test because winapp2.ini supports such paths and
669 # giving r'C:filename' as argument to lexists or FindFilesW
670 # causes a hard to detect issue, which has been detected because
671 # lexists('C:filename') returns True when called through PyCharm.
672 # Also test_remote is supposed to run cleaners that contain
673 # such paths but it doesn't assert if those cleaners actually
674 # clean their targets.
675
676 filename = os.path.join('C:\\', 'deleteme.txt')
677 try:
678 common.touch_file(filename)
679 except PermissionError:
680 self.skipTest('Permission denied: run as administrator')
681
682 with mock.patch('os.path.lexists') as mock_lexists:
683 cleaner = self.ini2cleaner('FileKey1=%SystemDrive%|deleteme.txt')
684 self.run_all(cleaner, True)
685 mock_lexists.assert_any_call(r'C:\deleteme.txt')
686
687 self.assertNotExists(filename)
688
689 @common.skipUnlessWindows
690 def test_removeself(self):
691 """Test for the removeself option"""
692
693 # indexes for test
694 # position 0: FileKey statement
695 # position 1: whether the file `dir_c\subdir\foo.log` should exist
696 # after operation is complete
697 # position 2: path of top-folder which should have been deleted
698 d = self.tempdir
699 tests = (
700 # Refer to directory directly (i.e., without a glob).
701 (rf'FileKey1={d}\dir_c|*.*|REMOVESELF',
702 False, rf'{d}\dir_c'),
703 # Refer to file that exists. This is invalid, so nothing happens.
704 (rf'FileKey1={d}\dir_c\submarine_sandwich.log|*.*|REMOVESELF',
705 True, ''),
706 (rf'FileKey1={d}\dir_c\submarine*|*.*|REMOVESELF',
707 True, ''),
708 # Refer to path that does not exist, so nothing happens.
709 (rf'FileKey1={d}\dir_c\doesnotexist.log|*.*|REMOVESELF',
710 True, ''),
711 # Refer by glob to both a file and directory (which both start with `sub`).
712 # This should affect only the directory.
713 (rf'FileKey1={d}\dir_a\sub*|*.*|REMOVESELF',
714 True, rf'{d}\dir_a\subdir'),
715 # glob in middle of directory path with whole directory entry
716 (rf'FileKey1={d}\*c\subdir|*.*|REMOVESELF',
717 False, rf'{d}\dir_c\subdir'),
718 (rf'FileKey1={d}\*doesnotexist\subdir|*.*|REMOVESELF',
719 True, ''),
720 # glob at end of path
721 (rf'FileKey1={d}\dir_c\sub*|*.*|REMOVESELF',
722 False, rf'{d}\dir_c\subdir'),
723 (rf'FileKey1={d}\dir_c\doesnotexist*|*.*|REMOVESELF',
724 True, '')
725 )
726
727 self.ini_fn = self.mkstemp(suffix='.ini', prefix='winapp2')
728
729 for filekey, c_log_expected, top_log_expected in tests:
730 for letter in ('a', 'b', 'c'):
731 # Make three directories, each with a `foo.log` file.
732 fn = os.path.join(self.tempdir, 'dir_' +
733 letter, 'subdir', 'foo.log')
734 common.touch_file(fn)
735
736 # In dir_a, place a file one level up from `foo.log`.
737 # Notice the glob `dir_a\sub*` will match both a directory and file.
738 fn2 = os.path.join(self.tempdir, 'dir_a', 'submarine_sandwich.log')
739 common.touch_file(fn2)
740
741 cleaner = self.ini2cleaner(filekey)
742 self.assertExists(fn, filekey)
743 self.assertExists(fn2, filekey)
744 if top_log_expected:
745 self.assertExists(top_log_expected, filekey)
746 self.run_all(cleaner, True)
747 if c_log_expected:
748 self.assertExists(fn, filekey)
749 else:
750 self.assertNotExists(fn, filekey)
751 if top_log_expected != '':
752 self.assertNotExists(top_log_expected, filekey)
753 self.assertExists(fn2, filekey)
754 if top_log_expected:
755 self.assertNotExists(top_log_expected, filekey)
756
757 def test_section2option(self):
758 """Test for section2option()"""
759 tests = ((' FOO2 ', 'foo2'),
760 ('A - B (C)', 'a_b_c'))
761 for test in tests:
762 self.assertEqual(section2option(test[0]), test[1])
763
764 def test_fnmatch_translate(self):
765 """Test that fnmatch_translate strips the end anchor and matches patterns"""
766 regex = fnmatch_translate('*.log')
767 self.assertFalse(regex.endswith(r'\z'))
768 self.assertFalse(regex.endswith(r'\Z'))
769 self.assertFalse(regex.endswith(r'\Z(?ms)'))
770 self.assertFalse(regex.endswith(r'$'))
771 self.assertNotEqual(regex, '*.log')
772
773 cases = (
774 ('*.log', 'deleteme.log', True),
775 ('*.log', 'deleteme.bak', False),
776 ('deleteme.*', 'deleteme.log', True),
777 ('deleteme.*', 'deleteme.bak', True),
778 ('deleteme.*', 'other.log', False),
779 (r'C:\dir', r'C:\dir\file.txt', True),
780 (r'C:\dir', r'C:\other\file.txt', False),
781 )
782 for pattern, text, expected in cases:
783 msg = f'pattern={pattern!r} string={text!r}'
784 self.assertEqual(
785 bool(re.search(fnmatch_translate(pattern), text)),
786 expected,
787 msg)
788
789 def test_fnmatch_translate_rejects_excessive_wildcards(self):
790 """A pattern with too many wildcards is rejected (ReDoS defense)"""
791 fnmatch_translate('*a*a*a*a*a*a*a*a*a*a') # 10 wildcards: allowed
792 self.assertRaises(
793 ValueError, fnmatch_translate, '*a*a*a*a*a*a*a*a*a*a*') # 11: rejected
794
795 def test_section_not_found(self):
796 """Test a section that is found"""
797 tmp_ini_fn = self.write_file(
798 'section_not_found.ini',
799 r"""[Initech TPS Reports *]
800 LangSecRef=3023
801 DetectFile=%CommonAppData%\Initech\TPSReports
802 FileKey1=%CommonAppData%\Initech\TPSReports\Logs|*.*""",
803 mode='w')
804
805 with mock.patch.object(Winapp, 'detect', return_value=True) as mock_detect:
806 winapps = Winapp(tmp_ini_fn)
807 cleaner_list = list(winapps.get_cleaners())
808 self.assertEqual(len(cleaner_list), 1)
809 self.assertEqual(cleaner_list[0].get_name(), 'Multimedia')
810 this_option = list(cleaner_list[0].get_options())[0]
811 self.assertEqual(this_option[0], 'initech_tps_reports')
812 self.assertEqual(this_option[1], 'Initech TPS Reports')
813 mock_detect.assert_called()
814
815 def test_many_patterns(self):
816 """Test a cleaner like Steam Installers and related performance improvement
817
818 https://github.com/bleachbit/bleachbit/issues/325
819 """
820
821 # set up environment
822 file_count = 1000
823 dir_count = 10
824 print(f'Making {file_count} files in each of {dir_count} directories.')
825 for i_d in range(1, dir_count + 1):
826 sub_dir = self.mkdir(os.path.join(self.tempdir, f'dir{i_d}'))
827 for i_f in range(1, file_count + 1):
828 self.write_file(os.path.join(sub_dir, f'file{i_f}'))
829
830 self.ini_fn = self.mkstemp(suffix='.ini', prefix='winapp2')
831
832 searches = ';'.join(
833 [f'*.{letter}' for letter in string.ascii_letters[0:26]])
834 cleaner = self.ini2cleaner(
835 f'FileKey1={self.tempdir}|{searches}|RECURSE')
836
837 # preview
838 t0 = time.time()
839 self.run_all(cleaner, False)
840 t1 = time.time()
841 print(f'Elapsed time in preview: {t1 - t0:.4f} seconds ')
842
843 # delete
844 self.run_all(cleaner, True)