Debian Codegraph @

tests/TestCleanerML.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 CleanerML
9 """
10
11 # standard imports
12 import os
13 import shutil
14 import sys
15 from unittest import mock
16
17 # first party imports
18 import bleachbit
19 from tests import common
20 from bleachbit import Cleaner
21 from bleachbit.CleanerML import (
22 CleanerML,
23 boolstr_to_bool,
24 create_pot,
25 default_vars,
26 list_cleanerml_files,
27 load_cleaners,
28 pot_fragment)
29
30
31 class CleanerMLTestCase(common.BleachbitTestCase):
32 """Test cases for CleanerML"""
33
34 def run_all(self, xmlcleaner, really_delete):
35 """Helper function to execute all options in a cleaner"""
36 for (option_id, __name) in xmlcleaner.cleaner.get_options():
37 for cmd in xmlcleaner.cleaner.get_commands(option_id):
38 for result in cmd.execute(really_delete):
39 common.validate_result(self, result, really_delete)
40
41 def _get_xmlcleaner(self):
42 """Helper for CleanerML*()"""
43 xmlcleaner = CleanerML("doc/example_cleaner.xml")
44 self.assertIsInstance(xmlcleaner, CleanerML)
45 self.assertIsInstance(xmlcleaner.cleaner, Cleaner.Cleaner)
46 return xmlcleaner
47
48 def test_CleanerML(self):
49 """Unit test for class CleanerML"""
50 xmlcleaner = self._get_xmlcleaner()
51 # preview
52 self.run_all(xmlcleaner, False)
53
54 @common.skipUnlessDestructive
55 def test_CleanerML_destructive(self):
56 """Unit test the destructive parts of class CleanerML"""
57 xmlcleaner = self._get_xmlcleaner()
58 # really delete
59 self.run_all(xmlcleaner, True)
60
61 def test_boolstr_to_bool(self):
62 """Unit test for boolstr_to_bool()"""
63 tests = [('True', True),
64 ('False', False)]
65
66 for (arg, output) in tests:
67 self.assertEqual(boolstr_to_bool(arg), output)
68 self.assertEqual(boolstr_to_bool(arg.lower()), output)
69 self.assertEqual(boolstr_to_bool(arg.upper()), output)
70
71 def test_create_pot(self):
72 """Unit test for create_pot()"""
73 os.chdir('po')
74 try:
75 create_pot()
76 finally:
77 os.chdir('..')
78
79 def test_default_vars_windows_system(self):
80 """Unit test WindowsSystem in default_vars()"""
81 env = {
82 'WinDir': r'C:\Windows',
83 'ProgramFiles': r'C:\Program Files (x86)',
84 'ProgramW6432': r'C:\Program Files',
85 }
86 with mock.patch('bleachbit.CleanerML.IS_WINDOWS', True), \
87 mock.patch.dict(os.environ, env, clear=True), \
88 mock.patch('bleachbit.Windows.ARCH_BITS', 32):
89 variables = default_vars()
90 self.assertEqual(
91 [r'C:\Windows\Sysnative', r'C:\Windows\SysWOW64'],
92 variables['WindowsSystem'])
93
94 def test_list_cleanerml_files(self):
95 """Unit test for list_cleanerml_files()"""
96 for pathname in list_cleanerml_files():
97 self.assertExists(pathname)
98
99 @common.skipIfWindows
100 def test_list_cleanerml_files_vanished(self):
101 """list_cleanerml_files() skips a cleaner deleted after listdir()
102
103 The world-writable check is POSIX only, so this race does not exist
104 on Windows.
105 """
106 dirname = self.mkdtemp(prefix='bleachbit-cleanerml-vanished')
107 real_fn = os.path.join(dirname, 'real.xml')
108 self.write_file(real_fn, contents=b'<cleaner id="test"/>')
109 os.chmod(real_fn, 0o600)
110 ghost_fn = os.path.join(dirname, 'ghost.xml')
111 with mock.patch('bleachbit.CleanerML.listdir',
112 return_value=iter([ghost_fn, real_fn])):
113 self.assertEqual(list(list_cleanerml_files()), [real_fn])
114
115 def test_load_cleaners(self):
116 """Unit test for load_cleaners()"""
117 # normal
118 list(load_cleaners())
119
120 # should catch exception with invalid XML
121 pcd = bleachbit.personal_cleaners_dir
122 bleachbit.personal_cleaners_dir = self.mkdtemp(
123 prefix='bleachbit-cleanerml-load')
124 self.write_file(os.path.join(bleachbit.personal_cleaners_dir, 'invalid.xml'),
125 contents=b'<xml><broken>')
126 list(load_cleaners())
127 shutil.rmtree(bleachbit.personal_cleaners_dir)
128 bleachbit.personal_cleaners_dir = pcd
129
130 def test_load_cleaners_invalid_utf8(self):
131 """Unit test for load_cleaners() with invalid UTF-8 encoding"""
132 pcd = bleachbit.personal_cleaners_dir
133 bleachbit.personal_cleaners_dir = self.mkdtemp(
134 prefix='bleachbit-cleanerml-utf8')
135 self.write_file(os.path.join(bleachbit.personal_cleaners_dir, 'broken_encoding.xml'),
136 contents=b'<cleaner id="poison">\n\xff\xfe\xfd Broken\n')
137 list(load_cleaners())
138 shutil.rmtree(bleachbit.personal_cleaners_dir)
139 bleachbit.personal_cleaners_dir = pcd
140
141 def test_untrusted_process_action(self):
142 """A process action is ignored for an untrusted cleaner"""
143 xml_str = (
144 '<?xml version="1.0" encoding="UTF-8"?>\n'
145 '<cleaner id="test_untrusted">\n'
146 ' <label>Test</label>\n'
147 ' <description>Test</description>\n'
148 ' <option id="opt">\n'
149 ' <label>Opt</label>\n'
150 ' <description>Opt</description>\n'
151 ' <action command="delete" search="file" path="test-does-not-exist"/>\n'
152 ' <action command="process" cmd="calc.exe"/>\n'
153 ' </option>\n'
154 '</cleaner>\n')
155 fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-trust'),
156 'planted.xml')
157 self.write_file(fn, text=xml_str)
158
159 def action_classes(cleaner):
160 return [a.__class__.__name__ for (_option_id, a) in cleaner.actions]
161
162 self.assertIn('Process', action_classes(
163 CleanerML(fn, trusted=True).cleaner))
164
165 # The delete action stays; only the process action is dropped
166 untrusted = action_classes(CleanerML(fn, trusted=False).cleaner)
167 self.assertNotIn('Process', untrusted)
168 self.assertIn('Delete', untrusted)
169
170 def test_untrusted_winreg_action_allowed(self):
171 """A winreg action is kept even for an untrusted cleaner"""
172 xml_str = (
173 '<?xml version="1.0" encoding="UTF-8"?>\n'
174 '<cleaner id="test_untrusted_winreg">\n'
175 ' <label>Test</label>\n'
176 ' <description>Test</description>\n'
177 ' <option id="opt">\n'
178 ' <label>Opt</label>\n'
179 ' <description>Opt</description>\n'
180 ' <action command="delete" search="file" path="test-does-not-exist"/>\n'
181 ' <action command="winreg" path="HKCU\\Software\\BleachBitTest"/>\n'
182 ' </option>\n'
183 '</cleaner>\n')
184 fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-trust'),
185 'planted_winreg.xml')
186 self.write_file(fn, text=xml_str)
187
188 def action_classes(cleaner):
189 return [a.__class__.__name__ for (_option_id, a) in cleaner.actions]
190
191 for trusted in (True, False):
192 actions = action_classes(CleanerML(fn, trusted=trusted).cleaner)
193 self.assertIn('Winreg', actions)
194 self.assertIn('Delete', actions)
195
196 def test_untrusted_actions_warn_once_per_file(self):
197 """Ignored actions are summarized in one warning, not one per action"""
198 actions = '\n'.join(
199 f' <action command="process" cmd="calc{i}.exe"/>'
200 for i in range(10))
201 xml_str = (
202 '<?xml version="1.0" encoding="UTF-8"?>\n'
203 '<cleaner id="test_untrusted_many">\n'
204 ' <label>Test</label>\n'
205 ' <description>Test</description>\n'
206 ' <option id="opt">\n'
207 ' <label>Opt</label>\n'
208 ' <description>Opt</description>\n'
209 f'{actions}\n'
210 ' </option>\n'
211 '</cleaner>\n')
212 fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-trust-log'),
213 'planted_many.xml')
214 self.write_file(fn, text=xml_str)
215
216 with self.assertLogs('bleachbit.CleanerML', level='WARNING') as cm:
217 CleanerML(fn, trusted=False)
218 self.assertEqual(len(cm.output), 1)
219 self.assertIn("'process'", cm.output[0])
220
221 def test_is_trusted_cleaner(self):
222 """Files shipped next to the application are trusted"""
223 from bleachbit.CleanerML import is_trusted_cleaner
224 system_dir = bleachbit.system_cleaners_dir
225 self.assertTrue(is_trusted_cleaner(
226 os.path.join(system_dir, 'example.xml')))
227 self.assertFalse(is_trusted_cleaner(
228 os.path.join(bleachbit.personal_cleaners_dir, 'example.xml')))
229
230 def test_is_trusted_cleaner_portable(self):
231 """In portable mode the personal cleaners dir is the local one"""
232 from bleachbit.CleanerML import is_trusted_cleaner
233 app_dir = self.mkdtemp(prefix='bleachbit-portable')
234 cleaners_dir = os.path.join(app_dir, 'cleaners')
235 with mock.patch.multiple(
236 'bleachbit',
237 local_cleaners_dir=cleaners_dir,
238 personal_cleaners_dir=cleaners_dir,
239 system_cleaners_dir=os.path.join(app_dir, 'share', 'cleaners')):
240 self.assertTrue(is_trusted_cleaner(
241 os.path.join(cleaners_dir, 'winapp2.ini')))
242 self.assertFalse(is_trusted_cleaner(
243 os.path.join(app_dir, 'elsewhere', 'winapp2.ini')))
244
245 def test_rejects_dtd(self):
246 """A CleanerML file with a DTD is rejected (entity-expansion defense)"""
247 xml_str = (
248 '<?xml version="1.0"?>\n'
249 '<!DOCTYPE cleaner [ <!ENTITY x "y"> ]>\n'
250 '<cleaner id="dtd_test">\n'
251 ' <label>Test</label>\n'
252 ' <description>Test</description>\n'
253 '</cleaner>\n')
254 fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-dtd'),
255 'dtd.xml')
256 self.write_file(fn, text=xml_str)
257 xmlcleaner = CleanerML(fn)
258 self.assertFalse(xmlcleaner.cleaner.is_usable())
259
260 def test_nvalid_utf8(self):
261 """Test CleanerML() with invalid UTF-8 encoding
262
263 It should fail gracefully.
264 """
265 fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-utf8'),
266 'broken.xml')
267 self.write_file(fn, contents=b'<cleaner id="poison">\n\xff\xfe\xfd\n')
268 xmlcleaner = CleanerML(fn)
269 self.assertIsInstance(xmlcleaner, CleanerML)
270 self.assertFalse(xmlcleaner.cleaner.is_usable())
271
272 def test_utf8_non_ascii(self):
273 """Test CleanerML() with UTF-8 non-ASCII text
274
275 It should load successfully.
276 """
277 xml_str = """<?xml version="1.0" encoding="UTF-8"?>
278 <cleaner id="test_utf8">
279 <label>Test</label>
280 <!-- 中文注释 -->
281 <option id="opt">
282 <label>测试标签</label>
283 <description>测试描述</description>
284 <action search="file" command="delete" path="C:\\中文路径\\file.txt"/>
285 </option>
286 </cleaner>
287 """
288 fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-utf8'),
289 'utf8.xml')
290 self.write_file(fn, contents=xml_str.encode('utf-8'))
291 xmlcleaner = CleanerML(fn)
292 self.assertIsInstance(xmlcleaner, CleanerML)
293 self.assertTrue(xmlcleaner.cleaner.is_usable())
294 self.assertEqual('测试标签', xmlcleaner.cleaner.options['opt'][0])
295 self.assertEqual('测试描述',
296 xmlcleaner.cleaner.options['opt'][1])
297 commands = list(xmlcleaner.cleaner.get_commands('opt'))
298 self.assertEqual(0, len(commands))
299
300 def test_os_match(self):
301 """Unit test for os_match"""
302 xmlcleaner = CleanerML("doc/example_cleaner.xml")
303
304 # blank always matches
305 self.assertTrue(xmlcleaner.os_match(""))
306
307 # as Linux
308 self.assertFalse(xmlcleaner.os_match('windows', 'linux'))
309 self.assertTrue(xmlcleaner.os_match('linux', 'linux'))
310 self.assertTrue(xmlcleaner.os_match('unix', 'linux'))
311
312 # as Windows
313 self.assertFalse(xmlcleaner.os_match('linux', 'win32'))
314 self.assertFalse(xmlcleaner.os_match('unix', 'win32'))
315 self.assertTrue(xmlcleaner.os_match('windows', 'win32'))
316
317 # as macOS (canonical name)
318 self.assertTrue(xmlcleaner.os_match('macos', 'darwin'))
319 self.assertTrue(xmlcleaner.os_match('bsd', 'darwin'))
320 self.assertTrue(xmlcleaner.os_match('unix', 'darwin'))
321 self.assertFalse(xmlcleaner.os_match('linux', 'darwin'))
322 self.assertFalse(xmlcleaner.os_match('windows', 'darwin'))
323
324 # "darwin" is accepted as a deprecated alias for "macos"
325 with self.assertLogs('bleachbit.General', level='WARNING'):
326 self.assertTrue(xmlcleaner.os_match('darwin', 'darwin'))
327
328 # as unknown operating system
329 with self.assertRaises(RuntimeError):
330 xmlcleaner.os_match('linux', 'hal9000')
331
332 def test_option_os_filter(self):
333 """Unit test for <option os="..."> filtering
334
335 An option with an os attribute that does not match the current
336 platform should not be registered on the cleaner.
337 """
338 xml_str = f"""<?xml version="1.0" encoding="UTF-8"?>
339 <cleaner id="test_option_os">
340 <label>Test</label>
341 <option id="always">
342 <label>Always</label>
343 <description>Delete the files</description>
344 <action search="file" command="delete" path="{self.tempdir}/always.log"/>
345 </option>
346 <option id="windows_only" os="windows">
347 <label>Windows only</label>
348 <description>Delete the files</description>
349 <action search="file" command="delete" path="{self.tempdir}/windows.log"/>
350 </option>
351 <option id="linux_only" os="linux">
352 <label>Linux only</label>
353 <description>Delete the files</description>
354 <action search="file" command="delete" path="{self.tempdir}/linux.log"/>
355 </option>
356 <option id="mac_only" os="macos">
357 <label>macOS only</label>
358 <description>Delete the files</description>
359 <action search="file" command="delete" path="{self.tempdir}/mac.log"/>
360 </option>
361 </cleaner>
362 """
363 cml_path = os.path.join(self.tempdir, 'test_option_os.xml')
364 self.write_file(cml_path, xml_str.encode(sys.getdefaultencoding()))
365
366 xmlc = CleanerML(cml_path)
367 # The unfiltered option is always present.
368 self.assertIn('always', xmlc.cleaner.options)
369 # The remaining options are conditionally available.
370 if bleachbit.IS_LINUX:
371 self.assertNotIn('mac_only', xmlc.cleaner.options)
372 self.assertNotIn('windows_only', xmlc.cleaner.options)
373 self.assertIn('linux_only', xmlc.cleaner.options)
374 elif bleachbit.IS_WINDOWS:
375 self.assertIn('windows_only', xmlc.cleaner.options)
376 self.assertNotIn('linux_only', xmlc.cleaner.options)
377 self.assertNotIn('mac_only', xmlc.cleaner.options)
378 elif bleachbit.IS_MAC:
379 self.assertNotIn('windows_only', xmlc.cleaner.options)
380 self.assertNotIn('linux_only', xmlc.cleaner.options)
381 self.assertIn('mac_only', xmlc.cleaner.options)
382
383 def test_pot_fragment(self):
384 """Unit test for pot_fragment()"""
385 self.assertIsString(pot_fragment("Foo", 'bar.xml'))
386
387 def test_var(self):
388 """Test the <var> element"""
389 xml_str = r"""
390 <cleaner id="testvar">
391 <label>cleaner label</label>
392 <description>cleaner description</description>
393 <var name="basepath">
394 <value>%%LocalAppData%%\FooDoesNotExist</value>
395 <value>~/.config/FooDoesNotExist</value>
396 <value>{tempdir}/a</value>
397 <value>{tempdir}/b</value>
398 </var>
399 <option id="option1">
400 <label>option1 label</label>
401 <description>option1 description</description>
402 <action search="file" command="delete" path="$$basepath$$/test.log" />
403 </option>
404 </cleaner>
405 """.format(**{'tempdir': self.tempdir})
406 # write XML cleaner
407 cml_path = os.path.join(self.tempdir, 'test.xml')
408 self.write_file(cml_path, xml_str.encode(sys.getdefaultencoding()))
409
410 # create two canaries
411 test_log_path_a = os.path.join(self.tempdir, 'a', 'test.log')
412 test_log_path_b = os.path.join(self.tempdir, 'b', 'test.log')
413 common.touch_file(test_log_path_a)
414 common.touch_file(test_log_path_b)
415 self.assertExists(test_log_path_a)
416 self.assertExists(test_log_path_b)
417
418 # parse XML to XML cleaner instance
419 xmlc = CleanerML(cml_path)
420 self.assertIsInstance(xmlc, CleanerML)
421 self.assertIsInstance(xmlc.cleaner, Cleaner.Cleaner)
422 self.assertTrue(xmlc.cleaner.is_usable())
423
424 # run preview
425 self.run_all(xmlc, False)
426 self.assertExists(test_log_path_a)
427 self.assertExists(test_log_path_b)
428
429 # really delete
430 self.run_all(xmlc, True)
431 self.assertNotExists(test_log_path_a)
432 self.assertNotExists(test_log_path_b)