Debian Codegraph @

tests/TestAction.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (c) 2008-2026 Andrew Ziem.
3 #
4 # This work is licensed under the terms of the GNU GPL, version 3 or
5 # later. See the COPYING file in the top-level directory.
6
7
8 """
9 Test cases for module Action
10 """
11
12 # standard imports
13 import logging
14 import os
15 import shutil
16 import sys
17 import tempfile
18 import time
19 import unittest
20 import xml.parsers.expat
21 from unittest import mock
22 from xml.dom.minidom import parseString
23 from xml.sax.saxutils import quoteattr
24
25 # first party imports
26 from bleachbit import IS_WINDOWS, IS_POSIX, IS_LINUX, FS_CASE_SENSITIVE, logger
27 from bleachbit.Action import ActionProvider, Command, Delete, has_glob, expand_multi_var
28 from bleachbit.CleanerML import CleanerML
29 from tests import common
30 from tests.TestFileUtilities import ini_helper
31 from tests.TestFileUtilities import json_helper
32
33
34 def _action_str_to_commands(action_str):
35 """Parse <action> and return commands"""
36 dom = parseString(action_str)
37 action_node = dom.childNodes[0]
38 delete = Delete(action_node)
39 yield from delete.get_commands()
40
41
42 def _action_str_to_results(action_str):
43 """Parse <action> and return list of results
44
45 It lists the files, but it does not really delete them.
46 """
47 return [next(cmd.execute(False)) for cmd in _action_str_to_commands(action_str)]
48
49
50 def benchmark_filter(filter_type):
51 """Measure how fast listing files is with and without filter"""
52 n_files = 100000
53 logger.info('benchmark of %d files', n_files)
54
55 # make a directory with many files
56 dirname = tempfile.mkdtemp(prefix='bleachbit-action-bench')
57 for x in range(0, n_files):
58 common.touch_file(os.path.join(dirname, str(x)))
59
60 # scan directory
61 start = time.time()
62 filter_code = ''
63 if 'regex' == filter_type:
64 # This regex matches everything, so the "no filter" and regex
65 # are comparable
66 filter_code = 'regex="."'
67 action_str = f'<action command="delete" search="glob" path="{dirname}/*" {filter_code} />'
68 _action_str_to_results(action_str)
69 end = time.time()
70 elapsed_seconds = end - start
71 rate = n_files / elapsed_seconds
72 logger.info('filter %s: elapsed: %.2f seconds, %.2f files/second',
73 filter_type, elapsed_seconds, rate)
74
75 # clean up
76 shutil.rmtree(dirname)
77
78 return rate
79
80
81 def dir_is_empty(dirname):
82 """Check whether a directory is empty"""
83 return not os.listdir(dirname)
84
85
86 class ActionTestCase(common.BleachbitTestCase):
87
88 """Test cases for Action"""
89
90 _TEST_PROCESS_CMD = 'cmd.exe /c dir' if IS_WINDOWS else 'dir'
91 _TEST_PROCESS_SIMPLE = '<action command="process" cmd={cmd} />'
92
93 def _test_action_str(self, action_str, expect_exists=True):
94 """Parse <action> and test it"""
95 try:
96 dom = parseString(action_str)
97 except xml.parsers.expat.ExpatError as e:
98 self.fail(f"parse error: {action_str}: {e}")
99 action_node = dom.childNodes[0]
100 command = action_node.getAttribute('command')
101 filename = action_node.getAttribute('path')
102 search = action_node.getAttribute('search')
103 provider = None
104 for actionplugin in ActionProvider.plugins:
105 if actionplugin.action_key == command:
106 provider = actionplugin(action_node)
107 self.assertNotEqual(provider, None)
108 for cmd in provider.get_commands():
109 self.assertIsInstance(
110 cmd, (Command.Delete, Command.Ini, Command.Json, Command.Function))
111 if 'process' != command and not has_glob(filename) and expect_exists:
112 # process does not have a filename
113 self.assertLExists(filename)
114 # preview
115 result = next(cmd.execute(really_delete=False))
116 common.validate_result(self, result)
117 self.assertNotEqual('/', result['path'])
118 # delete
119 next(cmd.execute(really_delete=True))
120 if 'delete' == command:
121 self.assertNotLExists(cmd.path)
122 elif 'truncate' == command:
123 self.assertLExists(filename)
124 os.remove(filename)
125 self.assertNotLExists(filename)
126 elif command in 'process':
127 pass
128 elif command in ('ini', 'json'):
129 self.assertLExists(filename)
130 else:
131 raise RuntimeError(f'Unknown command {command}')
132 if 'walk.all' == search:
133 if expect_exists:
134 self.assertTrue(dir_is_empty(
135 filename), f'directory not empty after walk.all: {filename}')
136
137 def test_delete(self):
138 """Unit test for class Delete"""
139 paths = ['~']
140 if IS_WINDOWS:
141 # Python 2.6 and later supports %foo%
142 paths.append('%USERPROFILE%')
143 # Python 2.5 and later supports $foo
144 paths.append('${USERPROFILE}')
145 paths.append('$USERPROFILE')
146 elif IS_POSIX:
147 paths.append('$HOME')
148 for path in paths:
149 for mode in ('delete', 'truncate', 'delete_forward'):
150 expanded = os.path.expanduser(os.path.expandvars(path))
151 filename = self.mkstemp(
152 dir=expanded, prefix='bleachbit-action-delete')
153 command = mode
154 if 'delete_forward' == mode:
155 # forward slash needs to be normalized on Windows
156 if IS_WINDOWS:
157 command = 'delete'
158 filename = filename.replace('\\', '/')
159 else:
160 # test not needed on this OS
161 os.remove(filename)
162 continue
163 action_str = f'<action command="{command}" search="file" path="{filename}" />'
164 self._test_action_str(action_str)
165 self.assertNotExists(filename)
166
167 def test_delete_special_filenames(self):
168 """Unit test for deleting special filenames"""
169 tests = [
170 'normal',
171 'space in name',
172 'sigil$should-not-be-expanded',
173 ]
174 for test in tests:
175 pathname = self.write_file(test)
176 action_str = f'<action command="delete" search="file" path="{pathname}" />'
177 self._test_action_str(action_str)
178 self.assertNotExists(pathname)
179
180 def test_expand_multi_var(self):
181 """Unit test for the function expand_multi_var"""
182 # each test is a tuple in format (input_str, vars, expected)
183 tests = (
184 # no variables
185 ('/var/foo1', None, ('/var/foo1',)),
186 # unknown variable
187 ('/var/foo2$$bar$$', None, ('/var/foo2$$bar$$',)),
188 # unused variable
189 ('/var/foo3_$$bar$$', {'baz': ('a',)}, ('/var/foo3_$$bar$$',)),
190 # used variable with one value
191 ('/var/foo4_$$bar$$', {'bar': ('a',)}, ('/var/foo4_a',)),
192 # used variable with two values
193 ('/var/foo5_$$bar$$', {'bar': ('a', 'b')},
194 ('/var/foo5_a', '/var/foo5_b')),
195 # the system is case sensitive
196 ('/var/foo6_$$BAR$$', {'bar': ('a',)}, ('/var/foo6_$$BAR$$',)),
197 ('/var/foo7_$$bar$$', {'BAR': ('a',)}, ('/var/foo7_$$bar$$',)),
198 # Windows-style
199 (r'c:\temp\foo8_$$bar$$', {'bar': ('a',)}, (r'c:\temp\foo8_a',)),
200 (r'$$basepath$$\file9.log', {'basepath': (
201 r'c:\temp',)}, (r'c:\temp\file9.log',)),
202 # two variables with one value each
203 ('/var/foo10_$$foo$$_$$bar$$',
204 {'foo': 'a', 'bar': 'b'}, ('/var/foo10_a_b',)),
205 # two variables with 1 and 2 values, respectively
206 ('/var/foo10_$$foo$$_$$bar$$',
207 {'foo': 'a', 'bar': ('b', 'c')}, ('/var/foo10_a_b', '/var/foo10_a_c')),
208
209 )
210
211 for test in tests:
212 input_str = test[0]
213 variables = test[1]
214 expected = test[2]
215 actual = expand_multi_var(input_str, variables)
216 self.assertSequenceEqual(actual, expected)
217
218 def test_windows_system_var(self):
219 """Unit test for expanding %WindowsSystem% in action paths."""
220 action_xml = (
221 r'<action command="delete" search="file" '
222 r'path="%WindowsSystem%\foo.log"/>'
223 )
224 action_node = parseString(action_xml).childNodes[0]
225 expanded = [r'C:\Windows\Sysnative\foo.log',
226 r'C:\Windows\SysWOW64\foo.log']
227 with mock.patch('bleachbit.Action.IS_WINDOWS', True), \
228 mock.patch('bleachbit.Action.Windows', create=True) as mock_windows:
229 mock_windows.expand_windows_system_vars.return_value = expanded
230 action = Delete(action_node)
231 self.assertEqual(expanded, action.paths)
232 mock_windows.expand_windows_system_vars.assert_called_once_with(
233 r'%WindowsSystem%\foo.log')
234
235 def test_has_glob(self):
236 """Unit test for function has_glob()"""
237 tests = ((r'c:\windows\*.log', True),
238 (r'c:\windows\temp.log', False),
239 (r'c:\windows\temp?.log', True),
240 (r'c:\windows\temp[abc].log', True))
241 for (test_input, test_expected) in tests:
242 test_actual = has_glob(test_input)
243 test_msg = f'test input: {test_input}, expected: {test_expected}, actual: {test_actual}'
244 self.assertEqual(test_actual, test_expected, test_msg)
245
246 def test_ini(self):
247 """Unit test for class Ini"""
248 def execute_ini(path, section, parameter):
249 effective_parameter = ""
250 if parameter is not None:
251 effective_parameter = f'parameter="{parameter}"'
252 action_str = (
253 '<action command="ini" search="file" '
254 f'path="{path}" section="{section}" {effective_parameter} />'
255 )
256 self._test_action_str(action_str)
257
258 ini_helper(self, execute_ini)
259
260 def test_json(self):
261 """Unit test for class Json"""
262 def execute_json(path, address):
263 action_str = (
264 '<action command="json" search="file" '
265 f'path="{path}" address="{address}" />'
266 )
267 self._test_action_str(action_str)
268
269 json_helper(self, execute_json)
270
271 def test_process(self):
272 """Unit test for process action"""
273 tests = [ActionTestCase._TEST_PROCESS_SIMPLE,
274 '<action command="process" cmd={cmd} wait="{wait}" />',
275 ]
276
277 if IS_WINDOWS:
278 cmds = [
279 'ping /?',
280 '%windir%\\System32\\ping.exe /?',
281 '"%windir%\\System32\\ping.exe" /?',
282 ]
283 else:
284 ls_flag = '-l'
285 cmds = ['ls', f'ls {ls_flag}', f'/bin/ls {ls_flag}', '/bin/ls']
286 for cmd in cmds:
287 cmd_qa = quoteattr(cmd)
288 for wait in ('true', 't', 'false', 'f', 'no', 'n'):
289 for test in tests:
290 self._test_action_str(test.format(cmd=cmd_qa, wait=wait))
291
292 def test_process_with_space(self):
293 """Test process action with space in command"""
294 # This is a regression test for a bug where spaces in commands were not handled correctly
295 delete_me = self.write_file('delete me.txt')
296 if IS_WINDOWS:
297 cmd = f'cmd /c del "{delete_me}"'
298 else:
299 delete_me_escaped = delete_me.replace(" ", "\\ ")
300 cmd = f'rm {delete_me_escaped}'
301 cmd_qa = quoteattr(cmd)
302 action_str = f'<action command="process" cmd={cmd_qa} wait="true" />'
303 self._test_action_str(action_str)
304 self.assertNotExists(delete_me)
305
306 def test_process_space(self):
307 """Unit test for process action with space in path
308
309 https://github.com/bleachbit/bleachbit/pull/871
310 """
311 fn = os.path.join(self.tempdir, 'file with space.txt')
312 common.touch_file(fn)
313 if IS_WINDOWS:
314 cmd = f'cmd /c del &quot;{fn}&quot;'
315 else:
316 fn_for_cmd = fn.replace(" ", "\\ ")
317 cmd = f'rm {fn_for_cmd}'
318 action_str = f'<action command="process" wait="true" cmd="{cmd}" />'
319 self._test_action_str(action_str)
320 self.assertNotExists(fn)
321
322 def test_process_unicode_stderr(self):
323 """
324 Test what happens when we have return code != 0 and unicode string in stderr.
325
326 In other words we test the case when we have an error and a non-ascii language setting.
327 """
328 with mock.patch('bleachbit.Action.General.run_external', return_value=(11, '', 'Уникод, който чупи кода!')):
329 # If exception occurs in logger `handleError` is called.
330 with mock.patch.object(logging.Handler, 'handleError') as MockHandleError:
331 try:
332 # When GtkLoggerHandler is used the exceptions are raised directly
333 # and handleError is not called
334 self._test_action_str(
335 ActionTestCase._TEST_PROCESS_SIMPLE.format(cmd=quoteattr(ActionTestCase._TEST_PROCESS_CMD)))
336 except UnicodeDecodeError:
337 self.fail(
338 "test_process_unicode_stderr() raised UnicodeDecodeError unexpectedly!")
339 else:
340 MockHandleError.assert_not_called()
341
342 def test_regex(self):
343 """Unit test for regex option"""
344 with mock.patch('glob.iglob', lambda x: ['/tmp/foo1', '/tmp/foo2', '/tmp/bar1']), \
345 mock.patch('bleachbit.FileUtilities.getsize', lambda x: 1):
346 # should match three files using no regexes
347 action_str = '<action command="delete" search="glob" path="/tmp/foo*" />'
348 results = _action_str_to_results(action_str)
349 self.assertEqual(len(results), 3)
350
351 # should match second file using positive regex
352 action_str = '<action command="delete" search="glob" path="/tmp/foo*" regex="^foo2$"/>'
353 results = _action_str_to_results(action_str)
354 self.assertEqual(len(results), 1)
355 self.assertEqual(results[0]['path'], '/tmp/foo2')
356
357 # On case-insensitive filesystems (Windows, macOS) the regex
358 # should match case-insensitively.
359 action_str = '<action command="delete" search="glob" path="/tmp/foo*" regex="^FOO2$"/>'
360 results = _action_str_to_results(action_str)
361 if FS_CASE_SENSITIVE:
362 self.assertEqual(len(results), 0)
363 else:
364 self.assertEqual(len(results), 1)
365 self.assertEqual(results[0]['path'], '/tmp/foo2')
366
367 # should match second file using negative regex
368 action_str = (
369 '<action command="delete" search="glob" '
370 'path="/tmp/foo*" nregex="^(foo1|bar1)$"/>'
371 )
372 results = _action_str_to_results(action_str)
373 self.assertEqual(len(results), 1)
374 self.assertEqual(results[0]['path'], '/tmp/foo2')
375
376 # should match second file using both regexes
377 action_str = (
378 '<action command="delete" search="glob" '
379 'path="/tmp/foo*" regex="^f" nregex="1$"/>'
380 )
381 results = _action_str_to_results(action_str)
382 self.assertEqual(len(results), 1)
383 self.assertEqual(results[0]['path'], '/tmp/foo2')
384
385 # should match nothing using positive regex
386 action_str = (
387 '<action command="delete" search="glob" '
388 'path="/tmp/foo*" regex="^bar$"/>'
389 )
390 results = _action_str_to_results(action_str)
391 self.assertEqual(len(results), 0)
392
393 # should match nothing using negative regex
394 action_str = (
395 '<action command="delete" search="glob" '
396 'path="/tmp/foo*" nregex="."/>'
397 )
398 results = _action_str_to_results(action_str)
399 self.assertEqual(len(results), 0)
400
401 # should give an error
402 action_str = (
403 '<action command="delete" search="invalid" '
404 'path="/tmp/foo*" regex="^bar$"/>'
405 )
406 self.assertRaises(
407 RuntimeError, lambda: _action_str_to_results(action_str))
408
409 def test_search_glob(self):
410 """Unit test for search=glob"""
411
412 fname = 'abcdefg'
413 pathname = self.write_file(fname)
414 tests = (pathname,
415 os.path.join(self.tempdir, 'abc*'),
416 os.path.join(self.tempdir, '*efg'),
417 os.path.join(self.tempdir, 'a*c*e*g'),
418 os.path.join(self.tempdir, 'a?cdefg'),
419 os.path.join(self.tempdir, 'a?????g'),
420 os.path.join(self.tempdir, '[a-z]b?d*'))
421 for test in tests:
422 with self.subTest(test=test):
423 pathname = self.write_file(fname)
424 self.assertExists(pathname)
425 action_str = (
426 '<action command="delete" search="glob" '
427 f'path="{test}" />'
428 )
429 self._test_action_str(action_str)
430 self.assertNotExists(pathname)
431
432 def test_wholeregex(self):
433 """Unit test for wholeregex filter"""
434 with mock.patch('glob.iglob', lambda x: ['/tmp/foo1', '/tmp/foo2', '/tmp/bar1']), \
435 mock.patch('bleachbit.FileUtilities.getsize', lambda x: 1):
436 # should match three files using no regexes
437 action_str = (
438 '<action command="delete" search="glob" '
439 'path="/tmp/foo*" />'
440 )
441 results = _action_str_to_results(action_str)
442 self.assertEqual(len(results), 3)
443
444 # should match two files using wholeregex
445 action_str = (
446 '<action command="delete" search="glob" '
447 'path="/tmp/foo*" wholeregex="^/tmp/foo.*$"/>'
448 )
449 results = _action_str_to_results(action_str)
450 self.assertEqual(len(results), 2)
451 self.assertEqual(results[0]['path'], '/tmp/foo1')
452
453 # should match third file using nwholeregex
454 action_str = (
455 '<action command="delete" search="glob" '
456 'path="/tmp/foo*" nwholeregex="^/tmp/foo.*$"/>'
457 )
458 results = _action_str_to_results(action_str)
459 self.assertEqual(len(results), 1)
460 self.assertEqual(results[0]['path'], '/tmp/bar1')
461
462 def test_type(self):
463 """Unit test for type attribute"""
464 dirname = self.mkdtemp(prefix='bleachbit-action-type')
465 filename = os.path.join(dirname, 'file')
466
467 # this should not delete anything
468 common.touch_file(filename)
469 action_str = f'<action command="delete" search="file" type="d" path="{filename}" />'
470 self._test_action_str(action_str)
471 self.assertExists(filename)
472
473 # should delete file
474 action_str = f'<action command="delete" search="file" type="f" path="{filename}" />'
475 self._test_action_str(action_str)
476 self.assertNotExists(filename)
477
478 # should delete file
479 common.touch_file(filename)
480 action_str = f'<action command="delete" search="file" path="{filename}" />'
481 self._test_action_str(action_str)
482 self.assertNotExists(filename)
483
484 # should not delete anything
485 action_str = f'<action command="delete" search="file" type="f" path="{dirname}" />'
486 self._test_action_str(action_str)
487 self.assertExists(dirname)
488
489 # should delete directory
490 action_str = f'<action command="delete" search="file" type="d" path="{dirname}" />'
491 self._test_action_str(action_str)
492 self.assertNotExists(dirname)
493
494 def test_walk_all_top(self):
495 """Unit test for walk.all and walk.top"""
496
497 variants = ('all', 'top')
498 for variant in variants:
499 dirname = self.mkdtemp(prefix=f'bleachbit-walk-{variant}')
500
501 # this sub-directory should be deleted
502 subdir = os.path.join(dirname, 'sub')
503 os.mkdir(subdir)
504 self.assertExists(subdir)
505
506 # this file should be deleted too
507 filename = os.path.join(subdir, 'file')
508 common.touch_file(filename)
509
510 action_str = f'<action command="delete" search="walk.{variant}" path="{dirname}" />'
511 self._test_action_str(action_str)
512 self.assertNotExists(subdir)
513 if variant == 'all':
514 self.assertExists(dirname)
515 os.rmdir(dirname)
516 elif variant == 'top':
517 self.assertNotExists(dirname)
518
519 # If the path does not exist, it should be silently ignored.
520 # The top directory no long exists, so just replay it.
521 self._test_action_str(action_str, False)
522
523 def test_walk_files(self):
524 """Unit test for walk.files"""
525 path = r'$WINDIR\system32' if IS_WINDOWS else '/var'
526
527 action_str = f'<action command="delete" search="walk.files" path="{path}" />'
528 results = 0
529 for cmd in _action_str_to_commands(action_str):
530 result = next(cmd.execute(False))
531 common.validate_result(self, result)
532 path = result['path']
533 self.assertFalse(os.path.isdir(path), f'{path} is a directory')
534 results += 1
535 self.assertGreater(results, 0)
536
537 def test_walk_files_cache_survives_early_abandon(self):
538 """An abandoned walk.files generator must not poison the cache"""
539 dirname = self.mkdtemp(prefix='bleachbit-walk-cache')
540 filenames = [os.path.join(dirname, f'file{i}') for i in range(3)]
541 for filename in filenames:
542 common.touch_file(filename)
543
544 action_str = f'<action command="delete" search="walk.files" path="{dirname}" />'
545
546 # Abandon after the first result, like Cleaner.auto_hide() does
547 commands = _action_str_to_commands(action_str)
548 next(commands)
549 del commands
550
551 # A fresh walk of the same path must still see every file
552 results = [next(cmd.execute(False))['path']
553 for cmd in _action_str_to_commands(action_str)]
554 self.assertEqual(sorted(results), sorted(filenames))
555
556 def test_package_manager_missing(self):
557 """Unit test for when package manager is not installed"""
558 with mock.patch('bleachbit.Language.setup_translation', return_value=None), \
559 mock.patch('bleachbit.FileUtilities.exe_exists', return_value=False), \
560 mock.patch('bleachbit.Unix.exe_exists', return_value=False):
561 # APT is excluded because it includes walk.all.
562 for cleaner_name in ['snap', 'pacman', 'yum', 'dnf']:
563 # Reset run_external mock for each test.
564 with self.subTest(cleaner_name=cleaner_name), mock.patch('bleachbit.General.run_external') as mock_run_external:
565 cleaner = CleanerML(
566 f'cleaners/{cleaner_name}.xml').get_cleaner()
567 # Cleaner remains usable because the action is registered, but it should auto-hide.
568 self.assertEqual(IS_LINUX, cleaner.is_usable())
569 self.assertTrue(cleaner.auto_hide())
570 mock_run_external.assert_not_called()
571
572
573 def main():
574 """Main function"""
575 if 1 < len(sys.argv) and 'benchmark' == sys.argv[1]:
576 for this_filter in ['none', 'regex']:
577 rates = []
578 iterations = 1
579 if 3 == len(sys.argv):
580 iterations = int(sys.argv[2])
581 for _x in range(0, iterations):
582 rate = benchmark_filter(this_filter)
583 rates.append(rate)
584 # combine all the rates for easy copy and paste into R for analysis
585 print(
586 f'rates for filter {this_filter}={",".join([str(rate) for rate in rates])}')
587 sys.exit()
588 unittest.main()
589
590
591 if __name__ == '__main__':
592 main()