# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (c) 2008-2026 Andrew Ziem.
#
# This work is licensed under the terms of the GNU GPL, version 3 or
# later. See the COPYING file in the top-level directory.
"""
Test cases for module CleanerML
"""
# standard imports
import os
import shutil
import sys
from unittest import mock
# first party imports
import bleachbit
from tests import common
from bleachbit import Cleaner
from bleachbit.CleanerML import (
CleanerML,
boolstr_to_bool,
create_pot,
default_vars,
list_cleanerml_files,
load_cleaners,
pot_fragment)
class CleanerMLTestCase(common.BleachbitTestCase):
"""Test cases for CleanerML"""
def run_all(self, xmlcleaner, really_delete):
"""Helper function to execute all options in a cleaner"""
for (option_id, __name) in xmlcleaner.cleaner.get_options():
for cmd in xmlcleaner.cleaner.get_commands(option_id):
for result in cmd.execute(really_delete):
common.validate_result(self, result, really_delete)
def _get_xmlcleaner(self):
"""Helper for CleanerML*()"""
xmlcleaner = CleanerML("doc/example_cleaner.xml")
self.assertIsInstance(xmlcleaner, CleanerML)
self.assertIsInstance(xmlcleaner.cleaner, Cleaner.Cleaner)
return xmlcleaner
def test_CleanerML(self):
"""Unit test for class CleanerML"""
xmlcleaner = self._get_xmlcleaner()
# preview
self.run_all(xmlcleaner, False)
@common.skipUnlessDestructive
def test_CleanerML_destructive(self):
"""Unit test the destructive parts of class CleanerML"""
xmlcleaner = self._get_xmlcleaner()
# really delete
self.run_all(xmlcleaner, True)
def test_boolstr_to_bool(self):
"""Unit test for boolstr_to_bool()"""
tests = [('True', True),
('False', False)]
for (arg, output) in tests:
self.assertEqual(boolstr_to_bool(arg), output)
self.assertEqual(boolstr_to_bool(arg.lower()), output)
self.assertEqual(boolstr_to_bool(arg.upper()), output)
def test_create_pot(self):
"""Unit test for create_pot()"""
os.chdir('po')
try:
create_pot()
finally:
os.chdir('..')
def test_default_vars_windows_system(self):
"""Unit test WindowsSystem in default_vars()"""
env = {
'WinDir': r'C:\Windows',
'ProgramFiles': r'C:\Program Files (x86)',
'ProgramW6432': r'C:\Program Files',
}
with mock.patch('bleachbit.CleanerML.IS_WINDOWS', True), \
mock.patch.dict(os.environ, env, clear=True), \
mock.patch('bleachbit.Windows.ARCH_BITS', 32):
variables = default_vars()
self.assertEqual(
[r'C:\Windows\Sysnative', r'C:\Windows\SysWOW64'],
variables['WindowsSystem'])
def test_list_cleanerml_files(self):
"""Unit test for list_cleanerml_files()"""
for pathname in list_cleanerml_files():
self.assertExists(pathname)
@common.skipIfWindows
def test_list_cleanerml_files_vanished(self):
"""list_cleanerml_files() skips a cleaner deleted after listdir()
The world-writable check is POSIX only, so this race does not exist
on Windows.
"""
dirname = self.mkdtemp(prefix='bleachbit-cleanerml-vanished')
real_fn = os.path.join(dirname, 'real.xml')
self.write_file(real_fn, contents=b'')
os.chmod(real_fn, 0o600)
ghost_fn = os.path.join(dirname, 'ghost.xml')
with mock.patch('bleachbit.CleanerML.listdir',
return_value=iter([ghost_fn, real_fn])):
self.assertEqual(list(list_cleanerml_files()), [real_fn])
def test_load_cleaners(self):
"""Unit test for load_cleaners()"""
# normal
list(load_cleaners())
# should catch exception with invalid XML
pcd = bleachbit.personal_cleaners_dir
bleachbit.personal_cleaners_dir = self.mkdtemp(
prefix='bleachbit-cleanerml-load')
self.write_file(os.path.join(bleachbit.personal_cleaners_dir, 'invalid.xml'),
contents=b'')
list(load_cleaners())
shutil.rmtree(bleachbit.personal_cleaners_dir)
bleachbit.personal_cleaners_dir = pcd
def test_load_cleaners_invalid_utf8(self):
"""Unit test for load_cleaners() with invalid UTF-8 encoding"""
pcd = bleachbit.personal_cleaners_dir
bleachbit.personal_cleaners_dir = self.mkdtemp(
prefix='bleachbit-cleanerml-utf8')
self.write_file(os.path.join(bleachbit.personal_cleaners_dir, 'broken_encoding.xml'),
contents=b'\n\xff\xfe\xfd Broken\n')
list(load_cleaners())
shutil.rmtree(bleachbit.personal_cleaners_dir)
bleachbit.personal_cleaners_dir = pcd
def test_untrusted_process_action(self):
"""A process action is ignored for an untrusted cleaner"""
xml_str = (
'\n'
'\n'
' \n'
' Test\n'
' \n'
'\n')
fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-trust'),
'planted.xml')
self.write_file(fn, text=xml_str)
def action_classes(cleaner):
return [a.__class__.__name__ for (_option_id, a) in cleaner.actions]
self.assertIn('Process', action_classes(
CleanerML(fn, trusted=True).cleaner))
# The delete action stays; only the process action is dropped
untrusted = action_classes(CleanerML(fn, trusted=False).cleaner)
self.assertNotIn('Process', untrusted)
self.assertIn('Delete', untrusted)
def test_untrusted_winreg_action_allowed(self):
"""A winreg action is kept even for an untrusted cleaner"""
xml_str = (
'\n'
'\n'
' \n'
' Test\n'
' \n'
'\n')
fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-trust'),
'planted_winreg.xml')
self.write_file(fn, text=xml_str)
def action_classes(cleaner):
return [a.__class__.__name__ for (_option_id, a) in cleaner.actions]
for trusted in (True, False):
actions = action_classes(CleanerML(fn, trusted=trusted).cleaner)
self.assertIn('Winreg', actions)
self.assertIn('Delete', actions)
def test_untrusted_actions_warn_once_per_file(self):
"""Ignored actions are summarized in one warning, not one per action"""
actions = '\n'.join(
f' '
for i in range(10))
xml_str = (
'\n'
'\n'
' \n'
' Test\n'
' \n'
'\n')
fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-trust-log'),
'planted_many.xml')
self.write_file(fn, text=xml_str)
with self.assertLogs('bleachbit.CleanerML', level='WARNING') as cm:
CleanerML(fn, trusted=False)
self.assertEqual(len(cm.output), 1)
self.assertIn("'process'", cm.output[0])
def test_is_trusted_cleaner(self):
"""Files shipped next to the application are trusted"""
from bleachbit.CleanerML import is_trusted_cleaner
system_dir = bleachbit.system_cleaners_dir
self.assertTrue(is_trusted_cleaner(
os.path.join(system_dir, 'example.xml')))
self.assertFalse(is_trusted_cleaner(
os.path.join(bleachbit.personal_cleaners_dir, 'example.xml')))
def test_is_trusted_cleaner_portable(self):
"""In portable mode the personal cleaners dir is the local one"""
from bleachbit.CleanerML import is_trusted_cleaner
app_dir = self.mkdtemp(prefix='bleachbit-portable')
cleaners_dir = os.path.join(app_dir, 'cleaners')
with mock.patch.multiple(
'bleachbit',
local_cleaners_dir=cleaners_dir,
personal_cleaners_dir=cleaners_dir,
system_cleaners_dir=os.path.join(app_dir, 'share', 'cleaners')):
self.assertTrue(is_trusted_cleaner(
os.path.join(cleaners_dir, 'winapp2.ini')))
self.assertFalse(is_trusted_cleaner(
os.path.join(app_dir, 'elsewhere', 'winapp2.ini')))
def test_rejects_dtd(self):
"""A CleanerML file with a DTD is rejected (entity-expansion defense)"""
xml_str = (
'\n'
' ]>\n'
'\n'
' \n'
' Test\n'
'\n')
fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-dtd'),
'dtd.xml')
self.write_file(fn, text=xml_str)
xmlcleaner = CleanerML(fn)
self.assertFalse(xmlcleaner.cleaner.is_usable())
def test_nvalid_utf8(self):
"""Test CleanerML() with invalid UTF-8 encoding
It should fail gracefully.
"""
fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-utf8'),
'broken.xml')
self.write_file(fn, contents=b'\n\xff\xfe\xfd\n')
xmlcleaner = CleanerML(fn)
self.assertIsInstance(xmlcleaner, CleanerML)
self.assertFalse(xmlcleaner.cleaner.is_usable())
def test_utf8_non_ascii(self):
"""Test CleanerML() with UTF-8 non-ASCII text
It should load successfully.
"""
xml_str = """
"""
fn = os.path.join(self.mkdtemp(prefix='bleachbit-cleanerml-utf8'),
'utf8.xml')
self.write_file(fn, contents=xml_str.encode('utf-8'))
xmlcleaner = CleanerML(fn)
self.assertIsInstance(xmlcleaner, CleanerML)
self.assertTrue(xmlcleaner.cleaner.is_usable())
self.assertEqual('测试标签', xmlcleaner.cleaner.options['opt'][0])
self.assertEqual('测试描述',
xmlcleaner.cleaner.options['opt'][1])
commands = list(xmlcleaner.cleaner.get_commands('opt'))
self.assertEqual(0, len(commands))
def test_os_match(self):
"""Unit test for os_match"""
xmlcleaner = CleanerML("doc/example_cleaner.xml")
# blank always matches
self.assertTrue(xmlcleaner.os_match(""))
# as Linux
self.assertFalse(xmlcleaner.os_match('windows', 'linux'))
self.assertTrue(xmlcleaner.os_match('linux', 'linux'))
self.assertTrue(xmlcleaner.os_match('unix', 'linux'))
# as Windows
self.assertFalse(xmlcleaner.os_match('linux', 'win32'))
self.assertFalse(xmlcleaner.os_match('unix', 'win32'))
self.assertTrue(xmlcleaner.os_match('windows', 'win32'))
# as macOS (canonical name)
self.assertTrue(xmlcleaner.os_match('macos', 'darwin'))
self.assertTrue(xmlcleaner.os_match('bsd', 'darwin'))
self.assertTrue(xmlcleaner.os_match('unix', 'darwin'))
self.assertFalse(xmlcleaner.os_match('linux', 'darwin'))
self.assertFalse(xmlcleaner.os_match('windows', 'darwin'))
# "darwin" is accepted as a deprecated alias for "macos"
with self.assertLogs('bleachbit.General', level='WARNING'):
self.assertTrue(xmlcleaner.os_match('darwin', 'darwin'))
# as unknown operating system
with self.assertRaises(RuntimeError):
xmlcleaner.os_match('linux', 'hal9000')
def test_option_os_filter(self):
"""Unit test for