| 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 CLI |
| 10 |
""" |
| 11 |
|
| 12 |
# standard imports |
| 13 |
import copy |
| 14 |
import datetime |
| 15 |
import errno |
| 16 |
import io |
| 17 |
import locale |
| 18 |
import os |
| 19 |
import random |
| 20 |
import tempfile |
| 21 |
from unittest.mock import MagicMock, patch |
| 22 |
|
| 23 |
from tests.common import pytest |
| 24 |
|
| 25 |
# first party imports |
| 26 |
import bleachbit |
| 27 |
from bleachbit.CLI import ( |
| 28 |
CliCallback, |
| 29 |
args_to_operations, |
| 30 |
args_to_operations_list, |
| 31 |
cleaners_list, |
| 32 |
parse_cmd_line, |
| 33 |
preview_or_clean, |
| 34 |
process_cmd_line) |
| 35 |
from bleachbit.General import get_executable, run_external |
| 36 |
from bleachbit.GtkShim import gtk_may_be_available |
| 37 |
from bleachbit import FileUtilities, Options, IS_WINDOWS, IS_POSIX |
| 38 |
from tests import common |
| 39 |
|
| 40 |
RUN_EXTERNAL_TIMEOUT = 30 |
| 41 |
|
| 42 |
|
| 43 |
class CLITestCase(common.BleachbitTestCase): |
| 44 |
"""Test case for module CLI""" |
| 45 |
|
| 46 |
def setUp(self): |
| 47 |
super().setUp() |
| 48 |
Options.options.reset_overrides() |
| 49 |
Options.options.set_override("first_start", False) |
| 50 |
|
| 51 |
def _test_preview(self, args, redirect_stdout=True, env=None): |
| 52 |
"""Helper to test preview""" |
| 53 |
# Use devnull because in some cases the buffer will be too large, |
| 54 |
# and the other alternative, the screen, is not desirable. |
| 55 |
with open(os.devnull, 'w') as stdout: |
| 56 |
if not redirect_stdout: |
| 57 |
stdout = None |
| 58 |
output = run_external(args, stdout=stdout, |
| 59 |
env=env, timeout=RUN_EXTERNAL_TIMEOUT) |
| 60 |
self.assertEqual(output[0], 0, "Return code = %d, stderr='%s'" |
| 61 |
% (output[0], output[2])) |
| 62 |
pos = output[2].find('Traceback (most recent call last)') |
| 63 |
if pos > -1: |
| 64 |
print("Saw the following error when using args '%s':\n %s" % |
| 65 |
(args, output[2])) |
| 66 |
self.assertEqual( |
| 67 |
pos, -1, f"Traceback found in stderr when using args {args}:\n{output[2][pos:]}") |
| 68 |
|
| 69 |
def test_args_to_operations_list(self): |
| 70 |
"""Unit test for args_to_operations_list()""" |
| 71 |
# --preset |
| 72 |
Options.init_configuration() |
| 73 |
o = args_to_operations_list(True, False) |
| 74 |
self.assertEqual(o, []) |
| 75 |
Options.options.set_tree('system', 'tmp', True) |
| 76 |
o = args_to_operations_list(True, False) |
| 77 |
self.assertEqual(o, ['system.tmp']) |
| 78 |
|
| 79 |
# --all-but-warning |
| 80 |
o = args_to_operations_list(False, True) |
| 81 |
self.assertIsInstance(o, list) |
| 82 |
self.assertIn('google_chrome.cache', o) |
| 83 |
self.assertIn('system.tmp', o) |
| 84 |
gui_available = IS_WINDOWS or gtk_may_be_available() |
| 85 |
self.assertEqual(gui_available, 'system.clipboard' in o) |
| 86 |
self.assertNotIn('system.empty_space', o) |
| 87 |
self.assertNotIn('system.memory', o) |
| 88 |
|
| 89 |
def test_args_to_operations(self): |
| 90 |
"""Unit test for args_to_operations()""" |
| 91 |
# test explicit cleaners (without --preset or --all-but-warning) |
| 92 |
tests = ( |
| 93 |
(['adobe_reader.*'], [], |
| 94 |
{'adobe_reader': ['cache', 'mru', 'tmp']}), |
| 95 |
(['adobe_reader.mru'], [], {'adobe_reader': ['mru']}), |
| 96 |
(['adobe_reader.*'], ['adobe_reader.cache'], |
| 97 |
{'adobe_reader': ['mru', 'tmp']})) |
| 98 |
for test_args, excludes, expected in tests: |
| 99 |
o = args_to_operations(test_args, False, False, excludes) |
| 100 |
self.assertIsInstance(o, dict) |
| 101 |
self.assertEqual(o, expected) |
| 102 |
|
| 103 |
# Test failure on wildcard |
| 104 |
with self.assertRaises(SystemExit) as cm: |
| 105 |
args_to_operations( |
| 106 |
['adobe_reader.mru'], False, False, ['adobe_reader.*']) |
| 107 |
self.assertEqual(cm.exception.code, 1) |
| 108 |
|
| 109 |
def test_parse_cmd_line_except(self): |
| 110 |
"""Unit test for parse_cmd_line() --except handling""" |
| 111 |
tests = ( |
| 112 |
(['--clean', 'firefox.*', 'chromium.*', |
| 113 |
'--except', 'firefox.passwords,chromium.passwords'], |
| 114 |
['firefox.*', 'chromium.*'], |
| 115 |
['firefox.passwords', 'chromium.passwords']), |
| 116 |
(['--clean', 'firefox.*', 'chromium.*', |
| 117 |
'--except', 'firefox.passwords', |
| 118 |
'--except', 'chromium.passwords'], |
| 119 |
['firefox.*', 'chromium.*'], |
| 120 |
['firefox.passwords', 'chromium.passwords']), |
| 121 |
(['--clean', 'chromium.*', |
| 122 |
'--except', 'firefox.passwords', |
| 123 |
'firefox.*', |
| 124 |
'--except', 'chromium.passwords'], |
| 125 |
['chromium.*', 'firefox.*'], |
| 126 |
['firefox.passwords', 'chromium.passwords'])) |
| 127 |
for argv, expected_args, expected_excludes in tests: |
| 128 |
_parser, options, args, excludes = parse_cmd_line(argv) |
| 129 |
self.assertTrue(options.clean) |
| 130 |
self.assertEqual(expected_args, args) |
| 131 |
self.assertEqual(expected_excludes, excludes) |
| 132 |
|
| 133 |
def test_cleaners_list(self): |
| 134 |
"""Unit test for cleaners_list()""" |
| 135 |
for cleaner in cleaners_list(): |
| 136 |
self.assertIsString(cleaner) |
| 137 |
|
| 138 |
def test_debug_log(self): |
| 139 |
"""Unit test for --debug-log option""" |
| 140 |
|
| 141 |
# These texts are required in the log file. |
| 142 |
file_required_texts = [ |
| 143 |
'DEBUG - Debug log file initialized', |
| 144 |
'ERROR - Failed to clean', |
| 145 |
'KeyError', |
| 146 |
'doesnot' |
| 147 |
] |
| 148 |
|
| 149 |
# These texts are forbidden in stderr. |
| 150 |
stderror_forbidden_texts = [ |
| 151 |
'bleachbit.CLI', |
| 152 |
'bleachbit.CleanerML', |
| 153 |
'ERROR', |
| 154 |
'DEBUG', |
| 155 |
datetime.datetime.now().strftime('%Y-%m-%d') |
| 156 |
] |
| 157 |
|
| 158 |
for delimiter in (' ', '='): |
| 159 |
# delete_on_close=False is helpful but requires Python 3.12. |
| 160 |
with tempfile.NamedTemporaryFile(delete=False, dir=self.tempdir) as f: |
| 161 |
f.close() |
| 162 |
log_path = f.name |
| 163 |
|
| 164 |
# 'bleachbit.py' is used instead of '-m bleachbit.CLI' |
| 165 |
args = [get_executable(), 'bleachbit.py', '--preview', 'doesnot.exist', |
| 166 |
'--debug'] + f'--debug-log{delimiter}{log_path}'.split(delimiter) |
| 167 |
(rc, _stdout, stderr) = run_external( |
| 168 |
args, stdout=None, timeout=RUN_EXTERNAL_TIMEOUT) |
| 169 |
self.assertEqual(0, rc, f"rc={rc}, stderr={stderr}") |
| 170 |
self.assertExists(log_path) |
| 171 |
with open(log_path, 'r', encoding='utf-8') as log_file: |
| 172 |
log_content = log_file.read() |
| 173 |
|
| 174 |
self.assertEqual(1, stderr.count('Traceback')) |
| 175 |
self.assertEqual(1, log_content.count( |
| 176 |
'Traceback'), log_content) |
| 177 |
|
| 178 |
for stderr_forbidden_text in stderror_forbidden_texts: |
| 179 |
self.assertNotIn(stderr_forbidden_text, stderr, |
| 180 |
f"The text '{stderr_forbidden_text}' was found in stderr") |
| 181 |
|
| 182 |
for required_text in file_required_texts: |
| 183 |
self.assertIn(required_text, log_content, |
| 184 |
f"The text '{required_text}' was not found in the log file") |
| 185 |
os.remove(log_path) |
| 186 |
self.assertNotExists(log_path) |
| 187 |
|
| 188 |
@common.skipIfWindows |
| 189 |
def test_encoding(self): |
| 190 |
"""Unit test for encoding""" |
| 191 |
|
| 192 |
filename = self.write_file( |
| 193 |
'/tmp/bleachbit-test-cli-encoding-\xe4\xf6\xfc~') |
| 194 |
# not assertExists because it doesn't cope with invalid encodings |
| 195 |
self.assertTrue(os.path.exists(filename)) |
| 196 |
|
| 197 |
env = copy.deepcopy(os.environ) |
| 198 |
env['LANG'] = 'en_US' # not UTF-8 |
| 199 |
args = [get_executable(), '-m', 'bleachbit.CLI', '-p', 'system.tmp'] |
| 200 |
# If Python pipes stdout to file or devnull, the test may give |
| 201 |
# a false negative. It must print stdout to terminal. |
| 202 |
self._test_preview(args, redirect_stdout=False, env=env) |
| 203 |
|
| 204 |
os.remove(filename) |
| 205 |
self.assertNotExists(filename) |
| 206 |
|
| 207 |
def test_invalid_locale(self): |
| 208 |
"""Unit test for invalid locales""" |
| 209 |
original_locale = locale.getlocale(locale.LC_NUMERIC) |
| 210 |
old_lang = common.get_env('LANG') |
| 211 |
with common.set_temporary_env('LANG', 'blahfoo'): |
| 212 |
# tests are run from the parent directory |
| 213 |
args = [get_executable(), '-m', 'bleachbit.CLI', '--version'] |
| 214 |
output = run_external(args, timeout=RUN_EXTERNAL_TIMEOUT) |
| 215 |
self.assertNotEqual(output[1].find('Copyright'), -1, str(output)) |
| 216 |
self.assertEqual(common.get_env('LANG'), old_lang) |
| 217 |
self.assertEqual(locale.getlocale(locale.LC_NUMERIC), original_locale) |
| 218 |
|
| 219 |
def test_preview(self): |
| 220 |
"""Unit test for --preview option""" |
| 221 |
env = copy.deepcopy(os.environ) |
| 222 |
# the language and encoding affect the test results |
| 223 |
env['LANG'] = 'en_US.UTF-8' |
| 224 |
env['PYTHONIOENCODING'] = 'utf-8:backslashreplace' |
| 225 |
args_list = [] |
| 226 |
module = 'bleachbit.CLI' |
| 227 |
big_args = [get_executable(), '-m', module, '--preview', ] |
| 228 |
# The full list can take a long time and generally does not improve the testing, |
| 229 |
# so test a subset. |
| 230 |
full_cleaners_list = list(cleaners_list()) |
| 231 |
system_cleaners = [ |
| 232 |
c for c in full_cleaners_list if c.startswith('system.')] |
| 233 |
if 'system.clipboard' in system_cleaners: |
| 234 |
# Fix error on GitHub Actions |
| 235 |
# FIXME: do conditional removal |
| 236 |
system_cleaners.remove('system.clipboard') |
| 237 |
non_system_cleaners = [ |
| 238 |
c for c in full_cleaners_list |
| 239 |
# deepscan.* can be too slow |
| 240 |
if not c.startswith('system.') and not c.startswith('deepscan.')] |
| 241 |
sample_cleaners = random.sample(non_system_cleaners, 5) |
| 242 |
for cleaner in (system_cleaners + sample_cleaners): |
| 243 |
args_list.append( |
| 244 |
[get_executable(), '-m', module, '--preview', cleaner]) |
| 245 |
big_args.append(cleaner) |
| 246 |
args_list.append(big_args) |
| 247 |
for args in args_list: |
| 248 |
self._test_preview(args, env=env) |
| 249 |
|
| 250 |
def test_delete(self): |
| 251 |
"""Unit test for --delete option""" |
| 252 |
prefixes = [ |
| 253 |
'bleachbit-test-cli-delete', |
| 254 |
'\x8b\x8b-bad-encoding' |
| 255 |
] |
| 256 |
for prefix in prefixes: |
| 257 |
with self.subTest(prefix=prefix): |
| 258 |
filename = self.mkstemp(prefix=prefix) |
| 259 |
filename = os.path.normcase(filename) |
| 260 |
|
| 261 |
deleted_paths = [] |
| 262 |
crash = [False] |
| 263 |
|
| 264 |
def dummy_delete(path, shred=False, crash=crash, |
| 265 |
deleted_paths=deleted_paths): |
| 266 |
try: |
| 267 |
self.assertLExists(path) |
| 268 |
except AssertionError: |
| 269 |
# On busy systems, other temp files may disappear |
| 270 |
# between scan and delete, so flag a crash only for the |
| 271 |
# test file itself. |
| 272 |
if os.path.normcase(path) == os.path.normcase(filename): |
| 273 |
crash[0] = True |
| 274 |
deleted_paths.append(os.path.normcase(path)) |
| 275 |
|
| 276 |
with patch.object(FileUtilities, 'delete', side_effect=dummy_delete): |
| 277 |
FileUtilities.delete(filename) |
| 278 |
# File exists because delete() is mocked, so real |
| 279 |
# delete() was not called. |
| 280 |
self.assertExists(filename) |
| 281 |
operations = args_to_operations( |
| 282 |
['system.tmp'], False, False) |
| 283 |
preview_or_clean(operations, True, quiet=True) |
| 284 |
|
| 285 |
self.assertIn(filename, deleted_paths, |
| 286 |
f"{filename} not found deleted") |
| 287 |
os.remove(filename) |
| 288 |
self.assertNotExists(filename) |
| 289 |
self.assertFalse(crash[0], "Crash detected during deletion") |
| 290 |
|
| 291 |
@pytest.mark.no_xdist |
| 292 |
def test_append_text(self): |
| 293 |
"""Unit test for CliCallback.append_text() with special strings""" |
| 294 |
cb = CliCallback(quiet=False) |
| 295 |
for test_str in common.SPECIAL_TEST_STRINGS: |
| 296 |
# Test that append_text handles special strings without crashing |
| 297 |
cb.append_text(test_str + "\n") |
| 298 |
# Test with newlines stripped (as implementation does) |
| 299 |
cb.append_text(f"prefix{test_str}suffix\n") |
| 300 |
# Test tag parameter (ignored but should not crash) |
| 301 |
cb.append_text(test_str + "\n", _tag="test_tag") |
| 302 |
|
| 303 |
def test_append_text_writes_stdout(self): |
| 304 |
"""Unit test for CliCallback.append_text() normal output""" |
| 305 |
cb = CliCallback(quiet=False) |
| 306 |
with patch('sys.stdout', new_callable=io.StringIO) as mock_stdout: |
| 307 |
cb.append_text("hello\n") |
| 308 |
self.assertEqual("hello\n", mock_stdout.getvalue()) |
| 309 |
|
| 310 |
def _assert_append_text_closes_output(self, exception): |
| 311 |
"""Verify append_text ignores interrupted stdout.""" |
| 312 |
class ClosedStdout: |
| 313 |
def __init__(self, write_exception): |
| 314 |
self.write_exception = write_exception |
| 315 |
self.write_calls = 0 |
| 316 |
|
| 317 |
def write(self, _text): |
| 318 |
self.write_calls += 1 |
| 319 |
raise self.write_exception |
| 320 |
|
| 321 |
def flush(self): |
| 322 |
return None |
| 323 |
|
| 324 |
stdout = ClosedStdout(exception) |
| 325 |
cb = CliCallback(quiet=False) |
| 326 |
with patch('sys.stdout', stdout): |
| 327 |
cb.append_text("hello\n") |
| 328 |
cb.append_text("again\n") |
| 329 |
self.assertEqual(1, stdout.write_calls) |
| 330 |
|
| 331 |
def test_append_text_ignores_broken_pipe(self): |
| 332 |
"""Unit test for CliCallback.append_text() with a closed pipe""" |
| 333 |
self._assert_append_text_closes_output(BrokenPipeError()) |
| 334 |
|
| 335 |
def test_append_text_ignores_windows_invalid_argument(self): |
| 336 |
"""Unit test for CliCallback.append_text() after more.com exits""" |
| 337 |
self._assert_append_text_closes_output( |
| 338 |
OSError(errno.EINVAL, "Invalid argument")) |
| 339 |
|
| 340 |
def test_append_text_reraises_unrelated_oserror(self): |
| 341 |
"""Unit test for preserving unrelated stdout errors""" |
| 342 |
cb = CliCallback(quiet=False) |
| 343 |
with patch('sys.stdout') as mock_stdout: |
| 344 |
mock_stdout.write.side_effect = OSError(errno.EIO, "I/O error") |
| 345 |
with self.assertRaises(OSError) as cm: |
| 346 |
cb.append_text("hello\n") |
| 347 |
self.assertEqual(errno.EIO, cm.exception.errno) |
| 348 |
|
| 349 |
def test_return_text(self): |
| 350 |
"""Check for correct text in output""" |
| 351 |
# format of tests is: args, expected_output, clean_env, env |
| 352 |
|
| 353 |
tests = [ |
| 354 |
[['--help'], 'Usage: ', False, None], |
| 355 |
[['--version'], 'BleachBit version', True, None], |
| 356 |
[['--sysinfo'], 'sys.version', False, None] |
| 357 |
] |
| 358 |
if IS_POSIX: |
| 359 |
# GUI is not available with clean environment on POSIX. |
| 360 |
tests.append([['--help'], 'Usage: ', True, None]) |
| 361 |
# Force detection of Wayland |
| 362 |
wayland_env = os.environ.copy() |
| 363 |
wayland_env['XDG_SESSION_TYPE'] = 'wayland' |
| 364 |
tests.append([['--sysinfo'], 'sys.version', False, wayland_env]) |
| 365 |
|
| 366 |
for args, expected_output, clean_env, env in tests: |
| 367 |
launcher_output = {} |
| 368 |
for i, launcher in enumerate([['bleachbit.py'], ['-m', 'bleachbit.CLI']]): |
| 369 |
direct_args = [get_executable(),] + launcher + args |
| 370 |
output = run_external( |
| 371 |
direct_args, env=env, clean_env=clean_env, timeout=RUN_EXTERNAL_TIMEOUT) |
| 372 |
self.assertEqual(output[0], 0, output) |
| 373 |
self.assertIn(expected_output, output[1]) |
| 374 |
modified_output_str = output[1].replace( |
| 375 |
'CLI.py', 'bleachbit.py') |
| 376 |
launcher_output[i] = [line for line in modified_output_str.split( |
| 377 |
'\n') if not line.startswith("sys.argv")] |
| 378 |
self.assertEqual(launcher_output[0], launcher_output[1]) |
| 379 |
|
| 380 |
def test_process_cmd_line_mutually_exclusive(self): |
| 381 |
"""Unit test for process_cmd_line() with mutually exclusive commands""" |
| 382 |
with patch('sys.argv', ['bleachbit', '--preview', '--clean']): |
| 383 |
with self.assertRaises(SystemExit) as cm: |
| 384 |
process_cmd_line() |
| 385 |
self.assertEqual(cm.exception.code, 1) |
| 386 |
|
| 387 |
def test_process_cmd_line_version(self): |
| 388 |
"""Unit test for process_cmd_line() with --version""" |
| 389 |
with patch('sys.argv', ['bleachbit', '--version']): |
| 390 |
with patch('sys.stdout', new_callable=io.StringIO) as mock_stdout: |
| 391 |
with self.assertRaises(SystemExit) as cm: |
| 392 |
process_cmd_line() |
| 393 |
self.assertEqual(cm.exception.code, 0) |
| 394 |
self.assertIn('BleachBit version', mock_stdout.getvalue()) |
| 395 |
|
| 396 |
def test_process_cmd_line_list_cleaners(self): |
| 397 |
"""Unit test for process_cmd_line() with --list-cleaners""" |
| 398 |
with patch('bleachbit.CLI.list_cleaners') as mock_list: |
| 399 |
with patch('sys.argv', ['bleachbit', '--list-cleaners']): |
| 400 |
with self.assertRaises(SystemExit) as cm: |
| 401 |
process_cmd_line() |
| 402 |
self.assertEqual(cm.exception.code, 0) |
| 403 |
mock_list.assert_called_once() |
| 404 |
|
| 405 |
def test_process_cmd_line_pot(self): |
| 406 |
"""Unit test for process_cmd_line() with --pot""" |
| 407 |
with patch('bleachbit.CleanerML.create_pot') as mock_create_pot: |
| 408 |
with patch('sys.argv', ['bleachbit', '--pot']): |
| 409 |
with self.assertRaises(SystemExit) as cm: |
| 410 |
process_cmd_line() |
| 411 |
self.assertEqual(cm.exception.code, 0) |
| 412 |
mock_create_pot.assert_called_once() |
| 413 |
|
| 414 |
def test_process_cmd_line_wipe_empty_space_no_args(self): |
| 415 |
"""Unit test for process_cmd_line() --wipe-empty-space with no args""" |
| 416 |
with patch('sys.argv', ['bleachbit', '--wipe-empty-space']): |
| 417 |
with self.assertRaises(SystemExit) as cm: |
| 418 |
process_cmd_line() |
| 419 |
self.assertEqual(cm.exception.code, 1) |
| 420 |
|
| 421 |
def test_process_cmd_line_preview_no_operations(self): |
| 422 |
"""Unit test for process_cmd_line() --preview with no operations""" |
| 423 |
with patch('sys.argv', ['bleachbit', '--preview']): |
| 424 |
with self.assertRaises(SystemExit) as cm: |
| 425 |
process_cmd_line() |
| 426 |
self.assertEqual(cm.exception.code, 1) |
| 427 |
|
| 428 |
def test_process_cmd_line_overwrite_warning(self): |
| 429 |
"""Unit test for process_cmd_line() --overwrite warning with --preview""" |
| 430 |
with patch('bleachbit.CLI.preview_or_clean'): |
| 431 |
with patch('bleachbit.CLI.logger.warning') as mock_warning: |
| 432 |
with patch('sys.argv', ['bleachbit', '--preview', 'system.tmp', '--overwrite']): |
| 433 |
with self.assertRaises(SystemExit) as cm: |
| 434 |
process_cmd_line() |
| 435 |
self.assertEqual(cm.exception.code, 0) |
| 436 |
mock_warning.assert_called_once() |
| 437 |
|
| 438 |
def test_process_cmd_line_overwrite_no_warning_with_clean(self): |
| 439 |
"""Unit test for process_cmd_line() --overwrite without warning when used with --clean""" |
| 440 |
with patch('bleachbit.CLI.preview_or_clean'): |
| 441 |
with patch('bleachbit.CLI.logger.warning') as mock_warning: |
| 442 |
with patch('sys.argv', ['bleachbit', '--clean', 'system.tmp', '--overwrite']): |
| 443 |
with self.assertRaises(SystemExit) as cm: |
| 444 |
process_cmd_line() |
| 445 |
self.assertEqual(cm.exception.code, 0) |
| 446 |
mock_warning.assert_not_called() |
| 447 |
|
| 448 |
def test_process_cmd_line_sysinfo(self): |
| 449 |
"""Unit test for process_cmd_line() with --sysinfo""" |
| 450 |
with patch('bleachbit.CLI.SystemInformation.get_system_information', |
| 451 |
return_value='test sysinfo'): |
| 452 |
with patch('sys.stdout', new_callable=io.StringIO) as mock_stdout: |
| 453 |
with patch('sys.argv', ['bleachbit', '--sysinfo']): |
| 454 |
with self.assertRaises(SystemExit) as cm: |
| 455 |
process_cmd_line() |
| 456 |
self.assertEqual(cm.exception.code, 0) |
| 457 |
self.assertIn('test sysinfo', mock_stdout.getvalue()) |
| 458 |
|
| 459 |
def test_process_cmd_line_shred(self): |
| 460 |
"""Unit test for process_cmd_line() with --shred""" |
| 461 |
with patch.dict('bleachbit.CLI.backends', clear=True): |
| 462 |
with patch('bleachbit.CLI.create_simple_cleaner', return_value=MagicMock()): |
| 463 |
with patch('bleachbit.CLI.preview_or_clean') as mock_preview: |
| 464 |
with patch('sys.argv', ['bleachbit', '--shred', '/tmp/test-shred']): |
| 465 |
with self.assertRaises(SystemExit) as cm: |
| 466 |
process_cmd_line() |
| 467 |
self.assertEqual(cm.exception.code, 0) |
| 468 |
mock_preview.assert_called_once() |
| 469 |
|
| 470 |
def test_process_cmd_line_gui(self): |
| 471 |
"""Unit test for process_cmd_line() with --gui""" |
| 472 |
mock_gui_module = MagicMock() |
| 473 |
mock_app = MagicMock() |
| 474 |
mock_app.run.return_value = 0 |
| 475 |
mock_gui_module.Bleachbit.return_value = mock_app |
| 476 |
with patch.dict('sys.modules', {'bleachbit.GuiApplication': mock_gui_module}): |
| 477 |
with patch.object(bleachbit, 'GuiApplication', mock_gui_module, create=True): |
| 478 |
with patch('bleachbit.Bootstrap.check_wayland_and_root', return_value=False): |
| 479 |
with patch('bleachbit.CLI.IS_WINDOWS', False): |
| 480 |
with patch('sys.argv', ['bleachbit', '--gui']): |
| 481 |
with self.assertRaises(SystemExit) as cm: |
| 482 |
process_cmd_line() |
| 483 |
self.assertEqual(cm.exception.code, 0) |
| 484 |
mock_gui_module.Bleachbit.assert_called_once_with( |
| 485 |
uac=False, shred_paths=[], auto_exit=None) |
| 486 |
mock_app.run.assert_called_once() |
| 487 |
|
| 488 |
def test_process_cmd_line_no_command(self): |
| 489 |
"""Unit test for process_cmd_line() with no command""" |
| 490 |
# Reminder: When GUI is available and there are no arguments, then |
| 491 |
# process_cmd_line is not called. |
| 492 |
# process_cmd_line() is called when either GUI is not available or |
| 493 |
# there are arguments. |
| 494 |
with patch('sys.argv', ['bleachbit']): |
| 495 |
with patch('sys.stdout', new_callable=io.StringIO) as mock_stdout: |
| 496 |
process_cmd_line() |
| 497 |
self.assertIn('bleachbit', mock_stdout.getvalue()) |
| 498 |
|
| 499 |
def test_process_cmd_line_debug(self): |
| 500 |
"""Unit test for process_cmd_line() with --debug""" |
| 501 |
with patch('bleachbit.CLI.preview_or_clean'): |
| 502 |
with patch('sys.argv', ['bleachbit', '--debug', '--preview', 'system.tmp']): |
| 503 |
with self.assertRaises(SystemExit) as cm: |
| 504 |
process_cmd_line() |
| 505 |
self.assertEqual(cm.exception.code, 0) |
| 506 |
self.assertTrue(Options.options.has_override('debug')) |
| 507 |
|
| 508 |
def test_process_cmd_line_preset(self): |
| 509 |
"""Unit test for process_cmd_line() with --preset""" |
| 510 |
# Preset branch only calls set_root_log_level when debug is enabled. |
| 511 |
Options.options.set_override('debug', True) |
| 512 |
with patch('bleachbit.CLI.preview_or_clean'): |
| 513 |
with patch('bleachbit.CLI.set_root_log_level') as mock_set_level: |
| 514 |
with patch('sys.argv', ['bleachbit', '--preview', '--preset', 'system.tmp']): |
| 515 |
with self.assertRaises(SystemExit) as cm: |
| 516 |
process_cmd_line() |
| 517 |
self.assertEqual(cm.exception.code, 0) |
| 518 |
mock_set_level.assert_called_once() |
| 519 |
|
| 520 |
def test_process_cmd_line_debug_log(self): |
| 521 |
"""Unit test for process_cmd_line() with --debug-log""" |
| 522 |
with patch('bleachbit.CLI.preview_or_clean'): |
| 523 |
with patch('bleachbit.CLI.SystemInformation.get_system_information', |
| 524 |
return_value='test sysinfo'): |
| 525 |
with patch('bleachbit.CLI.logger.info') as mock_log_info: |
| 526 |
with patch('sys.argv', ['bleachbit', '--debug-log', '/tmp/test.log', |
| 527 |
'--preview', 'system.tmp']): |
| 528 |
with self.assertRaises(SystemExit) as cm: |
| 529 |
process_cmd_line() |
| 530 |
self.assertEqual(cm.exception.code, 0) |
| 531 |
mock_log_info.assert_any_call('test sysinfo') |
| 532 |
|
| 533 |
def test_process_cmd_line_option_overrides(self): |
| 534 |
"""Unit test for process_cmd_line() option overrides""" |
| 535 |
with patch('sys.argv', ['bleachbit', '--no-load-cleaners', |
| 536 |
'--no-delete-confirmation']): |
| 537 |
with patch('sys.stdout', new_callable=io.StringIO): |
| 538 |
process_cmd_line() |
| 539 |
self.assertFalse(Options.options.get('load_cleaners')) |
| 540 |
self.assertFalse(Options.options.get('delete_confirmation')) |
| 541 |
|
| 542 |
def test_shred(self): |
| 543 |
"""Unit test for --shred""" |
| 544 |
suffixes = ['', '.', '.txt'] |
| 545 |
dirs = ['.', self.tempdir] |
| 546 |
for dir_ in dirs: |
| 547 |
for suffix in suffixes: |
| 548 |
(fd, filename) = tempfile.mkstemp( |
| 549 |
prefix='bleachbit-test-cli-shred', suffix=suffix, dir=dir_) |
| 550 |
os.close(fd) |
| 551 |
if '.' == dir_: |
| 552 |
filename = os.path.basename(filename) |
| 553 |
# The CWD case is not covered by tearDownClass, so register |
| 554 |
# this cleanup. |
| 555 |
self.addCleanup( |
| 556 |
lambda f=filename: os.path.exists(f) and os.remove(f)) |
| 557 |
# not assertExists because something strange happens on Windows |
| 558 |
self.assertTrue(os.path.exists(filename)) |
| 559 |
args = [get_executable(), '-m', |
| 560 |
'bleachbit.CLI', '--shred', filename] |
| 561 |
output = run_external(args, timeout=RUN_EXTERNAL_TIMEOUT) |
| 562 |
self.assertEqual(output[0], 0) |
| 563 |
self.assertNotExists(filename) |
| 564 |
|
| 565 |
@common.also_with_sudo |
| 566 |
def test_sysinfo(self): |
| 567 |
"""Unit test for --sysinfo |
| 568 |
|
| 569 |
By not using `-m bleachbit.CLI`, this exercises `./bleachbit.py`. |
| 570 |
""" |
| 571 |
env_configs = [[]] |
| 572 |
if not IS_WINDOWS: |
| 573 |
env_configs.extend([ |
| 574 |
['env', '-i'], # No environment variables |
| 575 |
['env', '-i', 'XDG_SESSION_TYPE=wayland'] # Mimic Wayland |
| 576 |
]) |
| 577 |
for env_prefix in env_configs: |
| 578 |
args = env_prefix + [get_executable(), 'bleachbit.py', '--sysinfo'] |
| 579 |
output = run_external(args, timeout=RUN_EXTERNAL_TIMEOUT) |
| 580 |
if IS_POSIX and os.environ.get('USER') == 'root' and \ |
| 581 |
output[0] == 1: |
| 582 |
continue |
| 583 |
self.assertEqual(output[0], 0, output) |
| 584 |
self.assertIn('sys.version', output[1]) |
| 585 |
# FIXME: verify that there is not a message like |
| 586 |
# (bleachbit.py:1234): Gdk-CRITICAL **: 23:05:08.581: gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed |
| 587 |
|
| 588 |
@pytest.mark.xdist_group('gui') |
| 589 |
@common.skipUnlessWindows |
| 590 |
def test_gui_exit(self): |
| 591 |
"""Unit test for --gui --exit, only for Windows""" |
| 592 |
# When running tests without elevated privileges, then --no-uac shows |
| 593 |
# the UAC dialog, requiring user interaction. Also, the parent |
| 594 |
# closes immediately, but the child continues, causing test to fail. |
| 595 |
args = (get_executable(), '-m', |
| 596 |
'bleachbit.CLI', '--gui', '--exit', '--no-uac') |
| 597 |
(rc, _stdout, stderr) = run_external( |
| 598 |
args, timeout=RUN_EXTERNAL_TIMEOUT) |
| 599 |
self.assertNotIn('no such option', stderr) |
| 600 |
self.assertNotIn('Usage: CLI.py', stderr) |
| 601 |
self.assertEqual(rc, 0) |
| 602 |
# Is the application still running? |
| 603 |
opened_windows_titles = common.get_opened_windows_titles() |
| 604 |
self.assertNotIn('BleachBit', opened_windows_titles) |