| 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 case for module Options |
| 10 |
""" |
| 11 |
|
| 12 |
import errno |
| 13 |
import os |
| 14 |
import sys |
| 15 |
import threading |
| 16 |
from unittest import mock |
| 17 |
|
| 18 |
from tests.common import pytest |
| 19 |
|
| 20 |
from tests import common |
| 21 |
import bleachbit.Options |
| 22 |
from bleachbit import IS_WINDOWS |
| 23 |
from bleachbit.Options import ( |
| 24 |
_option_index, _option_sort_key, _section_sort_key) |
| 25 |
from bleachbit.Log import is_debugging_enabled_via_cli |
| 26 |
|
| 27 |
|
| 28 |
class FakeTimer: |
| 29 |
"""Fake timer to replace threading.Timer""" |
| 30 |
instances = [] |
| 31 |
|
| 32 |
def __init__(self, interval, function, args=(), kwargs=None): |
| 33 |
"""Init the fake timer""" |
| 34 |
self.interval = interval |
| 35 |
self.function = function |
| 36 |
self.args = args |
| 37 |
self.kwargs = kwargs or {} |
| 38 |
self.daemon = False |
| 39 |
self.started = False |
| 40 |
self.cancelled = False |
| 41 |
self.__class__.instances.append(self) |
| 42 |
|
| 43 |
def cancel(self): |
| 44 |
"""Cancel the fake timer.""" |
| 45 |
self.cancelled = True |
| 46 |
|
| 47 |
def fire(self): |
| 48 |
"""Fire the fake timer.""" |
| 49 |
if not self.cancelled: |
| 50 |
self.function(*self.args, **self.kwargs) |
| 51 |
|
| 52 |
def start(self): |
| 53 |
"""Start the fake timer.""" |
| 54 |
self.started = True |
| 55 |
|
| 56 |
|
| 57 |
class OptionsTestCase(common.BleachbitTestCase): |
| 58 |
"""Test case for class Options""" |
| 59 |
|
| 60 |
def _write_seed_options_file(self): |
| 61 |
"""Write a seed options file for testing""" |
| 62 |
with open(bleachbit.options_file, 'w', encoding='utf-8-sig') as handle: |
| 63 |
handle.write(f'''[bleachbit] |
| 64 |
version={bleachbit.APP_VERSION} |
| 65 |
shred=False |
| 66 |
check_online_updates=True |
| 67 |
[hashpath] |
| 68 |
[list/shred_drives] |
| 69 |
''') |
| 70 |
|
| 71 |
def test_option_index(self): |
| 72 |
"""Unit test for _option_index""" |
| 73 |
self.assertEqual(_option_index('0'), 0) |
| 74 |
self.assertEqual(_option_index('3'), 3) |
| 75 |
self.assertEqual(_option_index('1_type'), 1) |
| 76 |
self.assertEqual(_option_index('2_path'), 2) |
| 77 |
|
| 78 |
def _write_private_options_file(self, contents): |
| 79 |
"""Point options_file to a file of this test only and seed it |
| 80 |
|
| 81 |
This keeps the seed out of the options file shared by the whole |
| 82 |
test case. |
| 83 |
""" |
| 84 |
filename = os.path.join(self.tempdir, f'{self.id()}.ini') |
| 85 |
patcher = mock.patch('bleachbit.options_file', filename) |
| 86 |
patcher.start() |
| 87 |
self.addCleanup(patcher.stop) |
| 88 |
with open(filename, 'w', encoding='utf-8-sig') as handle: |
| 89 |
handle.write(contents) |
| 90 |
return filename |
| 91 |
|
| 92 |
@staticmethod |
| 93 |
def _section_keys(contents, section): |
| 94 |
"""Return the keys of one section of an ini file""" |
| 95 |
keys = [] |
| 96 |
in_section = False |
| 97 |
for line in contents.splitlines(): |
| 98 |
if line.startswith('['): |
| 99 |
in_section = line == f'[{section}]' |
| 100 |
elif in_section and '=' in line: |
| 101 |
keys.append(line.split('=')[0].strip()) |
| 102 |
return keys |
| 103 |
|
| 104 |
def test_option_sort_key(self): |
| 105 |
"""Unit test for _option_sort_key""" |
| 106 |
self.assertEqual( |
| 107 |
sorted(['10_path', '2_path', '1_path'], key=_option_sort_key), |
| 108 |
['1_path', '2_path', '10_path']) |
| 109 |
self.assertEqual( |
| 110 |
sorted(['shred', 'debug', 'Auto'], key=_option_sort_key), |
| 111 |
['Auto', 'debug', 'shred']) |
| 112 |
# numeric keys come before named keys |
| 113 |
self.assertEqual( |
| 114 |
sorted(['debug', '1'], key=_option_sort_key), ['1', 'debug']) |
| 115 |
|
| 116 |
def test_sorted_file(self): |
| 117 |
"""Test that the file is written with sections and keys sorted""" |
| 118 |
filename = self._write_private_options_file('''[tree] |
| 119 |
system.tmp = True |
| 120 |
firefox.cache = True |
| 121 |
[bleachbit] |
| 122 |
shred = False |
| 123 |
auto_hide = True |
| 124 |
''') |
| 125 |
o = bleachbit.Options.Options() |
| 126 |
o.set_list('sort_test', ['a'] * 11) |
| 127 |
o.close() |
| 128 |
with open(filename, 'r', encoding='utf-8-sig') as handle: |
| 129 |
contents = handle.read() |
| 130 |
|
| 131 |
sections = [line[1:-1] |
| 132 |
for line in contents.splitlines() if line.startswith('[')] |
| 133 |
self.assertIn('bleachbit', sections) |
| 134 |
self.assertIn('tree', sections) |
| 135 |
self.assertEqual(sections, sorted(sections, key=_section_sort_key)) |
| 136 |
|
| 137 |
for section in sections: |
| 138 |
keys = self._section_keys(contents, section) |
| 139 |
self.assertEqual(keys, sorted(keys, key=_option_sort_key), section) |
| 140 |
|
| 141 |
# a list must not be written as 1, 10, 2 |
| 142 |
self.assertEqual(self._section_keys(contents, 'list/sort_test'), |
| 143 |
[str(i) for i in range(11)]) |
| 144 |
|
| 145 |
def test_defaults_are_written(self): |
| 146 |
"""Test that untouched preferences are written to the file""" |
| 147 |
filename = self._write_private_options_file( |
| 148 |
'[bleachbit]\nshred = True\n') |
| 149 |
o = bleachbit.Options.Options() |
| 150 |
o.close() |
| 151 |
with open(filename, 'r', encoding='utf-8-sig') as handle: |
| 152 |
contents = handle.read() |
| 153 |
|
| 154 |
keys = self._section_keys(contents, 'bleachbit') |
| 155 |
for bkey in bleachbit.Options.boolean_keys: |
| 156 |
self.assertIn(bkey, keys) |
| 157 |
# an existing value must not be replaced by the default |
| 158 |
self.assertIn('shred = True', contents) |
| 159 |
|
| 160 |
o2 = bleachbit.Options.Options() |
| 161 |
try: |
| 162 |
self.assertTrue(o2.get('shred')) |
| 163 |
for bkey in bleachbit.Options.boolean_keys: |
| 164 |
self.assertIsInstance(o2.get(bkey), bool) |
| 165 |
finally: |
| 166 |
o2.close() |
| 167 |
|
| 168 |
def test_Options(self): |
| 169 |
"""Unit test for class Options""" |
| 170 |
o = bleachbit.Options.options |
| 171 |
value = o.get("check_online_updates") |
| 172 |
|
| 173 |
# toggle a boolean |
| 174 |
o.toggle('check_online_updates') |
| 175 |
self.assertEqual(not value, o.get("check_online_updates")) |
| 176 |
|
| 177 |
# restore original boolean |
| 178 |
o.set("check_online_updates", value) |
| 179 |
self.assertEqual(value, o.get("check_online_updates")) |
| 180 |
|
| 181 |
# test delayed commit |
| 182 |
shred = o.get("shred") |
| 183 |
o.set("shred", not shred) |
| 184 |
self.assertEqual(not shred, o.get("shred")) |
| 185 |
|
| 186 |
o.restore() # abandon uncommitted changes |
| 187 |
self.assertEqual(shred, o.get("shred")) |
| 188 |
|
| 189 |
o.set("shred", shred) |
| 190 |
o.close() # commit |
| 191 |
self.assertEqual(shred, o.get("shred")) |
| 192 |
|
| 193 |
# try a list |
| 194 |
list_values = ['a', 'b', 'c'] |
| 195 |
o.set_list("list_test", list_values) |
| 196 |
self.assertEqual(list_values, o.get_list("list_test")) |
| 197 |
|
| 198 |
# these should always be set |
| 199 |
for bkey in bleachbit.Options.boolean_keys: |
| 200 |
self.assertIsInstance(o.get(bkey), bool) |
| 201 |
|
| 202 |
# language |
| 203 |
value = o.get_language('en') |
| 204 |
self.assertIsInstance(value, bool) |
| 205 |
o.set_language('en', True) |
| 206 |
self.assertTrue(o.get_language('en')) |
| 207 |
o.set_language('en', False) |
| 208 |
self.assertFalse(o.get_language('en')) |
| 209 |
o.set_language('en', value) |
| 210 |
|
| 211 |
# tree |
| 212 |
o.set_tree("parent", "child", True) |
| 213 |
self.assertTrue(o.get_tree("parent", "child")) |
| 214 |
o.set_tree("parent", "child", False) |
| 215 |
self.assertFalse(o.get_tree("parent", "child")) |
| 216 |
o.config.remove_option("tree", "parent.child") |
| 217 |
self.assertFalse(o.get_tree("parent", "child")) |
| 218 |
|
| 219 |
def test_keep_list(self): |
| 220 |
"""Test for get_whitelist_paths() / set_whitelist_paths()""" |
| 221 |
o = bleachbit.Options.options |
| 222 |
# FIXME: finish renaming whitelist to keep list |
| 223 |
self.assertIsInstance(o.get_whitelist_paths(), list) |
| 224 |
keep_list = [('file', '/home/foo'), ('folder', '/home'), |
| 225 |
('file', '/home/unicode/кодирование')] |
| 226 |
old_keep_list = o.get_whitelist_paths() |
| 227 |
o.config.remove_section('whitelist/paths') |
| 228 |
self.assertIsInstance(o.get_whitelist_paths(), list) |
| 229 |
self.assertEqual(o.get_whitelist_paths(), []) |
| 230 |
o.set_whitelist_paths(keep_list) |
| 231 |
self.assertIsInstance(o.get_whitelist_paths(), list) |
| 232 |
self.assertEqual(set(keep_list), set(o.get_whitelist_paths())) |
| 233 |
o.set_whitelist_paths(old_keep_list) |
| 234 |
o.close() |
| 235 |
self.assertEqual(set(old_keep_list), set(o.get_whitelist_paths())) |
| 236 |
|
| 237 |
def test_init_configuration(self): |
| 238 |
"""Test for init_configuration()""" |
| 239 |
if os.path.exists(bleachbit.options_file): |
| 240 |
os.remove(bleachbit.options_file) |
| 241 |
self.assertNotExists(bleachbit.options_file) |
| 242 |
bleachbit.Options.init_configuration() |
| 243 |
self.assertExists(bleachbit.options_file) |
| 244 |
|
| 245 |
def test_open_config_write_refuses_symlink(self): |
| 246 |
"""The config write must not follow a symlink to another file""" |
| 247 |
filename = self.write_file('cfg_target', b'keepme') |
| 248 |
with mock.patch('bleachbit.FileUtilities.os.path.islink', |
| 249 |
side_effect=lambda p: p == filename): |
| 250 |
with self.assertRaises(OSError): |
| 251 |
# nested with() so a regression that returns a handle |
| 252 |
# instead of raising does not leak it |
| 253 |
with bleachbit.Options._open_config_write(filename): |
| 254 |
pass |
| 255 |
with open(filename, 'rb') as f: |
| 256 |
self.assertEqual(f.read(), b'keepme') |
| 257 |
|
| 258 |
def test_is_corrupt(self): |
| 259 |
"""Test is_corrupt()""" |
| 260 |
def _test_is_corrupt(contents, expect_is_corrupt): |
| 261 |
with open(bleachbit.options_file, 'w', encoding='utf-8-sig') as f: |
| 262 |
f.write(contents) |
| 263 |
o = bleachbit.Options.Options() |
| 264 |
try: |
| 265 |
self.assertEqual(o.is_corrupt(), expect_is_corrupt) |
| 266 |
finally: |
| 267 |
# cancel any real flush timer restore() may have scheduled |
| 268 |
o.cancel_pending_flush() |
| 269 |
|
| 270 |
# test blank |
| 271 |
_test_is_corrupt('', False) |
| 272 |
_test_is_corrupt('[bleachbit]\n', False) |
| 273 |
|
| 274 |
# test valid but non-standard boolean |
| 275 |
_test_is_corrupt('[bleachbit]\nshred=f\n', False) |
| 276 |
|
| 277 |
# test invalid boolean |
| 278 |
# https://github.com/bleachbit/bleachbit/issues/560#issuecomment-497361700 |
| 279 |
_test_is_corrupt("[bleachbit]\nshred=['True']\n", True) |
| 280 |
os.remove(bleachbit.options_file) |
| 281 |
|
| 282 |
def test_purge(self): |
| 283 |
"""Test purging""" |
| 284 |
# By default ConfigParser stores keys (the filenames) as lowercase. |
| 285 |
# This needs special consideration when combined with purging. |
| 286 |
o1 = bleachbit.Options.Options() |
| 287 |
pathname = self.write_file('foo.xml') |
| 288 |
myhash = '0ABCD' |
| 289 |
o1.set_hashpath(pathname, myhash) |
| 290 |
o1.close() |
| 291 |
self.assertEqual(myhash, o1.get_hashpath(pathname)) |
| 292 |
if IS_WINDOWS: |
| 293 |
# check case sensitivity |
| 294 |
self.assertEqual(myhash, o1.get_hashpath(pathname.upper())) |
| 295 |
|
| 296 |
# reopen |
| 297 |
o2 = bleachbit.Options.Options() |
| 298 |
# write something, which triggers the purge |
| 299 |
o2.set('dummypath', 'dummyvalue', 'hashpath') |
| 300 |
o2.commit() |
| 301 |
# verify the path was not purged |
| 302 |
self.assertTrue(os.path.exists(pathname)) |
| 303 |
self.assertEqual(myhash, o2.get_hashpath(pathname)) |
| 304 |
|
| 305 |
# delete the path |
| 306 |
os.remove(pathname) |
| 307 |
# close and reopen |
| 308 |
o2.close() |
| 309 |
o3 = bleachbit.Options.Options() |
| 310 |
# write something, which triggers the purge |
| 311 |
o3.set('dummypath', 'dummyvalue', 'hashpath') |
| 312 |
o3.commit() |
| 313 |
# verify the path was purged |
| 314 |
self.assertIsNone(o3.get_hashpath(pathname)) |
| 315 |
o3.close() |
| 316 |
|
| 317 |
def test_abbreviations(self): |
| 318 |
"""Test non-standard, abbreviated booleans T and F""" |
| 319 |
|
| 320 |
# set values |
| 321 |
o = bleachbit.Options.options |
| 322 |
if not o.config.has_section('test'): |
| 323 |
o.config.add_section('test') |
| 324 |
o.config.set('test', 'test_t_upper', 'T') |
| 325 |
o.config.set('test', 'test_f_upper', 'F') |
| 326 |
o.config.set('test', 'test_t_lower', 't') |
| 327 |
o.config.set('test', 'test_f_lower', 'f') |
| 328 |
|
| 329 |
# read |
| 330 |
self.assertEqual(o.config.getboolean('test', 'test_t_upper'), True) |
| 331 |
self.assertEqual(o.config.getboolean('test', 'test_t_lower'), True) |
| 332 |
self.assertEqual(o.config.getboolean('test', 'test_f_upper'), False) |
| 333 |
self.assertEqual(o.config.getboolean('test', 'test_f_lower'), False) |
| 334 |
|
| 335 |
def test_percent(self): |
| 336 |
"""Test that the percent sign can be used without quoting the string""" |
| 337 |
# https://github.com/bleachbit/bleachbit/issues/205 |
| 338 |
|
| 339 |
opt = bleachbit.Options.options.config |
| 340 |
if not opt.has_section('test'): |
| 341 |
opt.add_section('test') |
| 342 |
opt.set('test', 'filename', '/var/log/samba/log.%m') |
| 343 |
|
| 344 |
# read |
| 345 |
self.assertEqual(opt.get('test', 'filename'), '/var/log/samba/log.%m') |
| 346 |
|
| 347 |
def test_error_disk_full(self): |
| 348 |
"""Test graceful degradation when disk is full""" |
| 349 |
disk_full_error = OSError('No space left on device') |
| 350 |
disk_full_error.errno = errno.ENOSPC |
| 351 |
o = bleachbit.Options.Options() |
| 352 |
try: |
| 353 |
with mock.patch('builtins.open', side_effect=disk_full_error): |
| 354 |
with self.assertLogs(level='ERROR') as log_context: |
| 355 |
o.set('test_key', 'test_value') |
| 356 |
o.commit() |
| 357 |
self.assertIn('Disk was full', log_context.output[0]) |
| 358 |
self.assertIn(bleachbit.options_file, log_context.output[0]) |
| 359 |
self.assertEqual(o.get('test_key'), 'test_value') |
| 360 |
finally: |
| 361 |
# forced commit() failure above never clears dirty/cancels the timer |
| 362 |
o.cancel_pending_flush() |
| 363 |
|
| 364 |
def test_error_permission(self): |
| 365 |
"""Test graceful degradation with permission errors""" |
| 366 |
permission_error = PermissionError('Permission denied') |
| 367 |
permission_error.errno = errno.EACCES |
| 368 |
o = bleachbit.Options.Options() |
| 369 |
try: |
| 370 |
with mock.patch('builtins.open', side_effect=permission_error): |
| 371 |
with self.assertLogs(level='ERROR') as log_context: |
| 372 |
o.set('test_key', 'test_value') |
| 373 |
o.commit() |
| 374 |
self.assertIn('Permission denied', log_context.output[0]) |
| 375 |
self.assertIn(bleachbit.options_file, log_context.output[0]) |
| 376 |
self.assertEqual(o.get('test_key'), 'test_value') |
| 377 |
finally: |
| 378 |
o.cancel_pending_flush() |
| 379 |
|
| 380 |
def test_warning(self): |
| 381 |
"""Test warning preferences""" |
| 382 |
o = bleachbit.Options.options |
| 383 |
self.assertFalse(o.get_warning_preference('test_key')) |
| 384 |
o.remember_warning_preference('test_key') |
| 385 |
self.assertTrue(o.get_warning_preference('test_key')) |
| 386 |
o.close() |
| 387 |
|
| 388 |
def test_warning_keys_with_colons(self): |
| 389 |
"""Test restoring warning preferences with colons in keys""" |
| 390 |
with open(bleachbit.options_file, 'w', encoding='utf-8-sig') as handle: |
| 391 |
handle.write('''[bleachbit] |
| 392 |
[warnings] |
| 393 |
cleaner:google_chrome:passwords = True |
| 394 |
cleaner:microsoft_edge:passwords = True |
| 395 |
''') |
| 396 |
o = None |
| 397 |
try: |
| 398 |
if sys.version_info >= (3, 10): |
| 399 |
with self.assertNoLogs('bleachbit.Options', level='ERROR'): |
| 400 |
o = bleachbit.Options.Options() |
| 401 |
else: |
| 402 |
o = bleachbit.Options.Options() |
| 403 |
self.assertTrue(o.get_warning_preference( |
| 404 |
'cleaner:google_chrome:passwords')) |
| 405 |
self.assertTrue(o.get_warning_preference( |
| 406 |
'cleaner:microsoft_edge:passwords')) |
| 407 |
finally: |
| 408 |
if o is not None: |
| 409 |
o.close() |
| 410 |
|
| 411 |
def test_corrupt_warning_preferences_are_migrated(self): |
| 412 |
"""Test migration of warning preferences corrupted by colon parsing""" |
| 413 |
with open(bleachbit.options_file, 'w', encoding='utf-8-sig') as handle: |
| 414 |
handle.write('''[bleachbit] |
| 415 |
[warnings] |
| 416 |
cleaner = google_chrome:passwords = True |
| 417 |
protected_path = /tmp = True |
| 418 |
''') |
| 419 |
o = bleachbit.Options.Options() |
| 420 |
try: |
| 421 |
self.assertTrue(o.get_warning_preference( |
| 422 |
'cleaner:google_chrome:passwords')) |
| 423 |
self.assertTrue(o.get_warning_preference('protected_path:/tmp')) |
| 424 |
self.assertFalse(o.config.has_option('warnings', 'cleaner')) |
| 425 |
self.assertFalse(o.config.has_option('warnings', 'protected_path')) |
| 426 |
o.commit() |
| 427 |
finally: |
| 428 |
o.close() |
| 429 |
with open(bleachbit.options_file, 'r', encoding='utf-8-sig') as handle: |
| 430 |
contents = handle.read() |
| 431 |
self.assertIn('cleaner:google_chrome:passwords = True', contents) |
| 432 |
self.assertIn('protected_path:/tmp = True', contents) |
| 433 |
self.assertNotIn('cleaner = google_chrome:passwords = True', contents) |
| 434 |
self.assertNotIn('protected_path = /tmp = True', contents) |
| 435 |
|
| 436 |
def test_overrides(self): |
| 437 |
"""Test CLI override functionality""" |
| 438 |
o = bleachbit.Options.options |
| 439 |
|
| 440 |
debug_default = is_debugging_enabled_via_cli() |
| 441 |
|
| 442 |
# Check defaults which are assumed in later tests. |
| 443 |
self.assertFalse(o.get('shred')) |
| 444 |
self.assertEqual(o.get('debug'), debug_default) |
| 445 |
self.assertTrue(o.get('delete_confirmation')) |
| 446 |
|
| 447 |
# Test basic override |
| 448 |
o.set_override('shred', True) |
| 449 |
self.assertTrue(o.get('shred')) |
| 450 |
|
| 451 |
# Test that override takes precedence over get |
| 452 |
o.set('shred', False) |
| 453 |
self.assertTrue(o.get('shred')) # override should still return True |
| 454 |
|
| 455 |
# Test multiple overrides |
| 456 |
o.set_override('debug', True) |
| 457 |
o.set_override('delete_confirmation', False) |
| 458 |
self.assertTrue(o.get('debug')) |
| 459 |
self.assertFalse(o.get('delete_confirmation')) |
| 460 |
|
| 461 |
# Test that flush doesn't write overridden values |
| 462 |
# First set persistent values different from overrides |
| 463 |
o.set('shred', False) |
| 464 |
o.set('debug', False) |
| 465 |
o.set('delete_confirmation', True) |
| 466 |
o.commit() |
| 467 |
|
| 468 |
# Verify overrides still work after flush |
| 469 |
self.assertTrue(o.get('shred')) |
| 470 |
self.assertTrue(o.get('debug')) |
| 471 |
self.assertFalse(o.get('delete_confirmation')) |
| 472 |
|
| 473 |
# Create new instance to verify persistent values were written correctly |
| 474 |
o2 = bleachbit.Options.Options() |
| 475 |
self.assertFalse(o2.get('shred')) |
| 476 |
self.assertEqual(o2.get('debug'), debug_default) |
| 477 |
self.assertTrue(o2.get('delete_confirmation')) |
| 478 |
o2.close() |
| 479 |
|
| 480 |
def test_override_does_not_persist(self): |
| 481 |
"""Test that overrides don't persist after process restart""" |
| 482 |
o = bleachbit.Options.options |
| 483 |
|
| 484 |
# Set an override |
| 485 |
o.set_override('shred', True) |
| 486 |
self.assertTrue(o.get('shred')) |
| 487 |
|
| 488 |
# Create new instance (simulating process restart) |
| 489 |
o2 = bleachbit.Options.Options() |
| 490 |
# Override should not exist in new instance |
| 491 |
self.assertNotIn(('bleachbit', 'shred'), o2.overrides) |
| 492 |
o2.close() |
| 493 |
|
| 494 |
# Clean up |
| 495 |
o.reset_overrides() |
| 496 |
|
| 497 |
def test_override_with_sections(self): |
| 498 |
"""Test overrides work with different sections""" |
| 499 |
o = bleachbit.Options.options |
| 500 |
|
| 501 |
# Test override in non-default section |
| 502 |
if not o.config.has_section('test_section'): |
| 503 |
o.config.add_section('test_section') |
| 504 |
o.config.set('test_section', 'test_key', 'original_value') |
| 505 |
|
| 506 |
o.set_override('test_key', 'override_value', section='test_section') |
| 507 |
self.assertEqual( |
| 508 |
o.get('test_key', section='test_section'), 'override_value') |
| 509 |
|
| 510 |
# Verify flush doesn't write override |
| 511 |
o.commit() |
| 512 |
o2 = bleachbit.Options.Options() |
| 513 |
self.assertEqual( |
| 514 |
o2.get('test_key', section='test_section'), 'original_value') |
| 515 |
o2.close() |
| 516 |
|
| 517 |
# Clean up |
| 518 |
o.reset_overrides() |
| 519 |
if o.config.has_section('test_section'): |
| 520 |
o.config.remove_section('test_section') |
| 521 |
|
| 522 |
def test_flush_mechanisms_timer_and_close(self): |
| 523 |
"""Test that changes flush correctly via timer fire or explicit close().""" |
| 524 |
with mock.patch('bleachbit.Options.threading.Timer', FakeTimer): |
| 525 |
for commit_method in ['timer', 'close']: |
| 526 |
with self.subTest(commit=commit_method): |
| 527 |
self._write_seed_options_file() |
| 528 |
o = bleachbit.Options.Options() |
| 529 |
|
| 530 |
def assert_pending_changes_uncommitted(instance): |
| 531 |
self.assertFalse(instance.get('shred')) |
| 532 |
self.assertIsNone(instance.get_list('list_test')) |
| 533 |
self.assertEqual([], instance.get_whitelist_paths()) |
| 534 |
self.assertEqual([], instance.get_custom_paths()) |
| 535 |
self.assertFalse(instance.get_language('zz')) |
| 536 |
self.assertFalse(instance.get_tree('system', 'cache')) |
| 537 |
self.assertFalse( |
| 538 |
instance.get_warning_preference('warn_key')) |
| 539 |
|
| 540 |
# Ensure initial state has no pending changes |
| 541 |
assert_pending_changes_uncommitted(o) |
| 542 |
|
| 543 |
# Guard against premature flush |
| 544 |
with mock.patch('builtins.open', side_effect=AssertionError('unexpected flush')): |
| 545 |
o.set('shred', True) |
| 546 |
o.set_list('list_test', ['a', 'b']) |
| 547 |
o.set_whitelist_paths([('file', '/tmp/a')]) |
| 548 |
o.set_custom_paths([('folder', '/tmp/b')]) |
| 549 |
o.set_language('zz', True) |
| 550 |
o.set_tree('system', 'cache', True) |
| 551 |
o.remember_warning_preference('warn_key') |
| 552 |
|
| 553 |
pending_timer = FakeTimer.instances[-1] |
| 554 |
self.assertTrue(pending_timer.started) |
| 555 |
|
| 556 |
# Verify uncommitted changes are invisible to new instance |
| 557 |
o2 = bleachbit.Options.Options() |
| 558 |
assert_pending_changes_uncommitted(o2) |
| 559 |
o2.close() |
| 560 |
|
| 561 |
# Commit via the specific mechanism being tested |
| 562 |
if commit_method == 'timer': |
| 563 |
pending_timer.fire() |
| 564 |
else: |
| 565 |
o.close() |
| 566 |
|
| 567 |
# Verify all changes persisted |
| 568 |
o3 = bleachbit.Options.Options() |
| 569 |
self.assertTrue(o3.get('shred')) |
| 570 |
self.assertEqual(['a', 'b'], o3.get_list('list_test')) |
| 571 |
self.assertEqual([('file', '/tmp/a')], |
| 572 |
o3.get_whitelist_paths()) |
| 573 |
self.assertEqual([('folder', '/tmp/b')], |
| 574 |
o3.get_custom_paths()) |
| 575 |
self.assertTrue(o3.get_language('zz')) |
| 576 |
self.assertTrue(o3.get_tree('system', 'cache')) |
| 577 |
self.assertTrue(o3.get_warning_preference('warn_key')) |
| 578 |
o3.close() |
| 579 |
|
| 580 |
if commit_method == 'timer': |
| 581 |
o.close() |
| 582 |
|
| 583 |
def test_mutators_flush_atomically_with_lock(self): |
| 584 |
"""Test that mutating self.config and scheduling the flush is atomic""" |
| 585 |
self._write_seed_options_file() |
| 586 |
|
| 587 |
mutators = ( |
| 588 |
('set', lambda o: o.set('shred', 'RACE_PROBE')), |
| 589 |
('set_list', lambda o: o.set_list('race_list', ['x'])), |
| 590 |
('set_tree', lambda o: o.set_tree( |
| 591 |
'race_parent', 'race_child', True)), |
| 592 |
('remember_warning_preference', |
| 593 |
lambda o: o.remember_warning_preference('race_key')), |
| 594 |
) |
| 595 |
|
| 596 |
with mock.patch('bleachbit.Options.threading.Timer', FakeTimer): |
| 597 |
for name, mutate in mutators: |
| 598 |
with self.subTest(mutator=name): |
| 599 |
o = bleachbit.Options.Options() |
| 600 |
entered = threading.Event() |
| 601 |
finish = threading.Event() |
| 602 |
real_schedule_flush = o._Options__schedule_flush |
| 603 |
|
| 604 |
# blocks mid-flush so a concurrent lock probe can check who holds the lock |
| 605 |
def blocking_schedule_flush(): |
| 606 |
entered.set() |
| 607 |
finish.wait(timeout=5) |
| 608 |
real_schedule_flush() |
| 609 |
|
| 610 |
with mock.patch.object( |
| 611 |
o, '_Options__schedule_flush', |
| 612 |
side_effect=blocking_schedule_flush): |
| 613 |
t = threading.Thread( |
| 614 |
target=mutate, args=(o,)) |
| 615 |
t.start() |
| 616 |
self.assertTrue( |
| 617 |
entered.wait(timeout=5), |
| 618 |
f'{name}() never reached __schedule_flush') |
| 619 |
acquired = o._flush_lock.acquire(timeout=0.2) |
| 620 |
if acquired: |
| 621 |
o._flush_lock.release() |
| 622 |
finish.set() |
| 623 |
t.join(timeout=5) |
| 624 |
|
| 625 |
self.assertFalse( |
| 626 |
acquired, |
| 627 |
f'{name}() released _flush_lock between ' |
| 628 |
'mutating self.config and scheduling the ' |
| 629 |
'flush - a concurrent background flush could ' |
| 630 |
'observe and persist the change before ' |
| 631 |
'restore() gets a chance to discard it') |
| 632 |
# cancel_pending_flush(), not close(): probe values must never hit disk |
| 633 |
o.cancel_pending_flush() |
| 634 |
|
| 635 |
def test_restore_does_not_expose_partial_configuration(self): |
| 636 |
"""Test restore() keeps setters out until all sections are rebuilt.""" |
| 637 |
self._write_seed_options_file() |
| 638 |
o = bleachbit.Options.Options() |
| 639 |
entered_read = threading.Event() |
| 640 |
continue_restore = threading.Event() |
| 641 |
setter_finished = threading.Event() |
| 642 |
restore_errors = [] |
| 643 |
setter_errors = [] |
| 644 |
original_read_file = o.config.read_file |
| 645 |
|
| 646 |
def blocking_read_file(*args, **kwargs): |
| 647 |
entered_read.set() |
| 648 |
continue_restore.wait(timeout=5) |
| 649 |
return original_read_file(*args, **kwargs) |
| 650 |
|
| 651 |
def restore(): |
| 652 |
try: |
| 653 |
o.restore() |
| 654 |
except Exception as error: |
| 655 |
restore_errors.append(error) |
| 656 |
|
| 657 |
def set_option(): |
| 658 |
try: |
| 659 |
o.set('race_probe', 'True') |
| 660 |
except Exception as error: |
| 661 |
setter_errors.append(error) |
| 662 |
finally: |
| 663 |
setter_finished.set() |
| 664 |
|
| 665 |
restore_thread = threading.Thread(target=restore) |
| 666 |
setter_thread = threading.Thread(target=set_option) |
| 667 |
try: |
| 668 |
with mock.patch.object( |
| 669 |
o.config, 'read_file', side_effect=blocking_read_file): |
| 670 |
restore_thread.start() |
| 671 |
self.assertTrue(entered_read.wait(timeout=5)) |
| 672 |
setter_thread.start() |
| 673 |
|
| 674 |
self.assertFalse( |
| 675 |
setter_finished.wait(timeout=0.2), |
| 676 |
'set() ran while restore() had cleared self.config') |
| 677 |
|
| 678 |
continue_restore.set() |
| 679 |
restore_thread.join(timeout=5) |
| 680 |
setter_thread.join(timeout=5) |
| 681 |
|
| 682 |
self.assertFalse(restore_thread.is_alive()) |
| 683 |
self.assertFalse(setter_thread.is_alive()) |
| 684 |
self.assertEqual([], restore_errors) |
| 685 |
self.assertEqual([], setter_errors) |
| 686 |
self.assertTrue(o.get('race_probe')) |
| 687 |
finally: |
| 688 |
continue_restore.set() |
| 689 |
restore_thread.join(timeout=5) |
| 690 |
setter_thread.join(timeout=5) |
| 691 |
o.cancel_pending_flush() |
| 692 |
o.close() |
| 693 |
|
| 694 |
def test_close_unregisters_atexit_and_is_idempotent(self): |
| 695 |
"""Test close() unregisters its atexit callback and only flushes once.""" |
| 696 |
self._write_seed_options_file() |
| 697 |
with mock.patch('bleachbit.Options.atexit.unregister') as mock_unregister: |
| 698 |
o = bleachbit.Options.Options() |
| 699 |
with mock.patch.object(o, '_Options__flush') as mock_flush: |
| 700 |
o.close() |
| 701 |
o.close() |
| 702 |
|
| 703 |
mock_flush.assert_called_once_with(force=False) |
| 704 |
mock_unregister.assert_called_once() |
| 705 |
|
| 706 |
@pytest.mark.no_xdist |
| 707 |
def test_unicode_paths(self): |
| 708 |
"""Test that paths with various Unicode characters""" |
| 709 |
# On Linux, os.listdir() may return filenames with surrogate-escaped |
| 710 |
# bytes (e.g. invalid UTF-8 byte sequences decoded with |
| 711 |
# 'surrogateescape'). These contain unpaired surrogates (U+D800 to |
| 712 |
# U+DFFF) which cannot be encoded as UTF-8, causing UnicodeEncodeError |
| 713 |
# when ConfigParser writes the .ini file. |
| 714 |
# https://github.com/bleachbit/bleachbit/issues/2082 |
| 715 |
|
| 716 |
test_cases = [ |
| 717 |
('surrogate', '/tmp/invalid_unicode_surrogate_\udce9'), |
| 718 |
('cjk', '/tmp/中文日本語한국어'), |
| 719 |
('european', '/tmp/àéïöüñçß'), |
| 720 |
('cyrillic', '/tmp/кодирование'), |
| 721 |
('arabic', '/tmp/العربية'), |
| 722 |
('emoji', '/tmp/🎉🚀💻'), |
| 723 |
('mixed', '/tmp/mixed_中文_àéï_\udce9'), |
| 724 |
] |
| 725 |
|
| 726 |
def verify_paths(o, keep_list, custom_list): |
| 727 |
"""Helper to verify whitelist and custom paths""" |
| 728 |
o.set_whitelist_paths(keep_list) |
| 729 |
o.commit() |
| 730 |
self.assertEqual(keep_list, o.get_whitelist_paths()) |
| 731 |
|
| 732 |
o.set_custom_paths(custom_list) |
| 733 |
o.commit() |
| 734 |
self.assertEqual(custom_list, o.get_custom_paths()) |
| 735 |
|
| 736 |
# Verify round-trip: new instance reads from disk |
| 737 |
o2 = bleachbit.Options.Options() |
| 738 |
self.assertEqual(keep_list, o2.get_whitelist_paths()) |
| 739 |
self.assertEqual(custom_list, o2.get_custom_paths()) |
| 740 |
o2.close() |
| 741 |
|
| 742 |
o = bleachbit.Options.options |
| 743 |
for name, path in test_cases: |
| 744 |
with self.subTest(unicode_type=name): |
| 745 |
keep_list = [('file', path)] |
| 746 |
custom_list = [('folder', path)] |
| 747 |
verify_paths(o, keep_list, custom_list) |
| 748 |
|
| 749 |
o.close() |