| 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 |
Common code for unit tests |
| 10 |
""" |
| 11 |
|
| 12 |
import contextlib |
| 13 |
import os |
| 14 |
import re |
| 15 |
import shutil |
| 16 |
import sys |
| 17 |
import tempfile |
| 18 |
import time |
| 19 |
import unittest |
| 20 |
import warnings |
| 21 |
from pathlib import Path |
| 22 |
from unittest import mock |
| 23 |
|
| 24 |
try: |
| 25 |
import pytest |
| 26 |
except ImportError: # pytest is optional for plain unittest discovery |
| 27 |
class _MarkShimMeta(type): |
| 28 |
"""Metaclass so any @pytest.mark.<name> is a no-op decorator. |
| 29 |
|
| 30 |
Supports both forms: ``@pytest.mark.foo`` (no parens) and |
| 31 |
``@pytest.mark.foo(...)`` (with parens). |
| 32 |
""" |
| 33 |
def __getattr__(cls, _name): |
| 34 |
def decorator(func=None, *_args, **_kwargs): |
| 35 |
if callable(func): |
| 36 |
# Used as @pytest.mark.foo without parentheses. |
| 37 |
return func |
| 38 |
# Used as @pytest.mark.foo(...) with parentheses. |
| 39 |
return lambda f: f |
| 40 |
return decorator |
| 41 |
|
| 42 |
class _PytestShim: |
| 43 |
"""No-op stand-in so @pytest.mark.* decorators work under unittest.""" |
| 44 |
class mark(metaclass=_MarkShimMeta): |
| 45 |
pass |
| 46 |
pytest = _PytestShim() |
| 47 |
|
| 48 |
import bleachbit |
| 49 |
from bleachbit import logger |
| 50 |
|
| 51 |
if bleachbit.IS_WINDOWS: |
| 52 |
import winreg |
| 53 |
import win32gui |
| 54 |
from bleachbit import Windows |
| 55 |
import bleachbit.Options |
| 56 |
from bleachbit.Bootstrap import bootstrap |
| 57 |
from bleachbit.FileUtilities import ( |
| 58 |
children_in_directory, |
| 59 |
extended_path, |
| 60 |
is_hard_link, |
| 61 |
is_normal_directory, |
| 62 |
) |
| 63 |
from bleachbit.General import gc_collect, sudo_mode |
| 64 |
|
| 65 |
# /etc/locale.alias may list the qaa-qtz range, which is reserved for |
| 66 |
# private use rather than a concrete locale. Skip it if present. |
| 67 |
SKIP_ALIAS_CODES = {'qaa-qtz', 'it_CARES'} |
| 68 |
|
| 69 |
|
| 70 |
def _supports_stdout_char(char: str) -> bool: |
| 71 |
"""Return True if sys.stdout can encode the given character.""" |
| 72 |
encoding = ( |
| 73 |
getattr(bleachbit, 'stdout_encoding', None) |
| 74 |
or getattr(sys.stdout, 'encoding', None) |
| 75 |
or sys.getdefaultencoding() |
| 76 |
) |
| 77 |
try: |
| 78 |
char.encode(encoding) |
| 79 |
except (UnicodeEncodeError, LookupError): |
| 80 |
return False |
| 81 |
return True |
| 82 |
|
| 83 |
|
| 84 |
@contextlib.contextmanager |
| 85 |
def mock_missing_package(*package_names, clear_prefixes=()): |
| 86 |
"""Context manager that simulates missing optional packages. |
| 87 |
|
| 88 |
Saves and restores sys.modules around the block. Removes all |
| 89 |
modules matching any of *package_names* or *clear_prefixes* from |
| 90 |
sys.modules, then patches each package_name as None to prevent |
| 91 |
re-import. |
| 92 |
|
| 93 |
Args: |
| 94 |
*package_names: Package names to make unavailable |
| 95 |
(e.g. 'requests', 'psutil'). These are both evicted from |
| 96 |
sys.modules and patched as None. |
| 97 |
clear_prefixes: Additional module prefixes to evict from |
| 98 |
sys.modules (e.g. 'bleachbit.Network') so they are |
| 99 |
re-imported inside the block. Not patched as None. |
| 100 |
""" |
| 101 |
saved_modules = dict(sys.modules) |
| 102 |
all_prefixes = list(package_names) + list(clear_prefixes) |
| 103 |
for mod in list(sys.modules.keys()): |
| 104 |
if any(mod.startswith(p) for p in all_prefixes): |
| 105 |
del sys.modules[mod] |
| 106 |
try: |
| 107 |
patch_dict = {name: None for name in package_names} |
| 108 |
with mock.patch.dict('sys.modules', patch_dict): |
| 109 |
yield |
| 110 |
finally: |
| 111 |
for mod in list(sys.modules.keys()): |
| 112 |
if mod not in saved_modules: |
| 113 |
del sys.modules[mod] |
| 114 |
for mod, mod_obj in saved_modules.items(): |
| 115 |
if mod not in sys.modules: |
| 116 |
sys.modules[mod] = mod_obj |
| 117 |
# Re-importing a submodule also rebinds it as an attribute on its |
| 118 |
# parent package (e.g. bleachbit.Network on the bleachbit package). |
| 119 |
# sys.modules restore alone leaves that attribute stale, so a later |
| 120 |
# mock.patch('bleachbit.Network...') would hit the orphaned module. |
| 121 |
for mod, mod_obj in saved_modules.items(): |
| 122 |
if '.' not in mod: |
| 123 |
continue |
| 124 |
parent_name, _, attr = mod.rpartition('.') |
| 125 |
parent = sys.modules.get(parent_name) |
| 126 |
if parent is not None and getattr(parent, attr, None) is not mod_obj: |
| 127 |
setattr(parent, attr, mod_obj) |
| 128 |
|
| 129 |
|
| 130 |
@contextlib.contextmanager |
| 131 |
def capture_glib_exceptions(): |
| 132 |
"""Capture exceptions swallowed by GLib virtual method/signal handlers. |
| 133 |
|
| 134 |
PyGObject catches exceptions raised inside GObject virtual method |
| 135 |
overrides (e.g. ``do_activate``) and signal callbacks, then logs them |
| 136 |
via ``sys.excepthook`` without propagating to the Python caller. This |
| 137 |
context manager installs a custom ``sys.excepthook`` that collects such |
| 138 |
exceptions so they can be re-raised after GTK event processing. |
| 139 |
|
| 140 |
Yields a list of ``(exc_type, exc_value, exc_tb)`` tuples. |
| 141 |
""" |
| 142 |
captured = [] |
| 143 |
original_excepthook = sys.excepthook |
| 144 |
|
| 145 |
def _capturing_excepthook(exc_type, exc_value, exc_tb): |
| 146 |
captured.append((exc_type, exc_value, exc_tb)) |
| 147 |
original_excepthook(exc_type, exc_value, exc_tb) |
| 148 |
|
| 149 |
sys.excepthook = _capturing_excepthook |
| 150 |
try: |
| 151 |
yield captured |
| 152 |
finally: |
| 153 |
sys.excepthook = original_excepthook |
| 154 |
|
| 155 |
|
| 156 |
@contextlib.contextmanager |
| 157 |
def set_temporary_env(env_var, env_value): |
| 158 |
""" |
| 159 |
Temporarily overrides an environment variable. |
| 160 |
""" |
| 161 |
# Save the original value so we can restore it later |
| 162 |
original_value = os.environ.get(env_var) |
| 163 |
|
| 164 |
if env_value is None: |
| 165 |
os.environ.pop(env_var, None) |
| 166 |
else: |
| 167 |
os.environ[env_var] = str(env_value) |
| 168 |
try: |
| 169 |
yield |
| 170 |
finally: |
| 171 |
# Restore the original state |
| 172 |
if original_value is None: |
| 173 |
# If the environment variable wasn't set originally, remove it |
| 174 |
os.environ.pop(env_var, None) |
| 175 |
else: |
| 176 |
os.environ[env_var] = original_value |
| 177 |
|
| 178 |
|
| 179 |
def get_volatile_dir(): |
| 180 |
"""Return the volatile system temporary directory for TOCTOU tolerance. |
| 181 |
|
| 182 |
Use tempfile.gettempdir() instead of a hardcoded '/tmp' (POSIX) or |
| 183 |
'%temp%' (Windows) so custom TMPDIR/TMP/TEMP environments work. |
| 184 |
gettempdir() prefers TMP over TEMP on Windows while winapp '%Temp%' |
| 185 |
expands to TEMP, but conftest.py sets both identically, so the |
| 186 |
difference is theoretical. |
| 187 |
""" |
| 188 |
volatile_dir = tempfile.gettempdir().rstrip('/\\') |
| 189 |
if not volatile_dir: |
| 190 |
# TMPDIR=/ would rstrip to an empty prefix that matches every path |
| 191 |
volatile_dir = os.sep |
| 192 |
return volatile_dir |
| 193 |
|
| 194 |
|
| 195 |
class BleachbitTestCase(unittest.TestCase): |
| 196 |
"""TestCase class with several convenience methods and asserts""" |
| 197 |
_patchers = [] |
| 198 |
|
| 199 |
@classmethod |
| 200 |
def setUpClass(cls): |
| 201 |
"""Do common setup for the test case |
| 202 |
|
| 203 |
* Create a temporary directory for the testcase. |
| 204 |
* Treat warnings as errors. |
| 205 |
This is also set by environment variable in `Makefile` and |
| 206 |
the CI workflow. |
| 207 |
* Patch options paths. |
| 208 |
""" |
| 209 |
bootstrap() |
| 210 |
warnings.simplefilter("error") |
| 211 |
cls._install_py314_asyncio_filters() |
| 212 |
cls.tempdir = tempfile.mkdtemp(prefix=cls.__name__) |
| 213 |
if 'BLEACHBIT_TEST_OPTIONS_DIR' not in os.environ: |
| 214 |
cls._patch_options_paths() |
| 215 |
bleachbit.Options.options.reset_overrides() |
| 216 |
bleachbit.Options.options.set_override("first_start", False) |
| 217 |
|
| 218 |
@staticmethod |
| 219 |
def _install_py314_asyncio_filters(): |
| 220 |
"""Ignore asyncio event-loop-policy deprecation warnings on Python 3.14+. |
| 221 |
|
| 222 |
PyGObject calls ``asyncio.get_event_loop_policy()`` (deprecated in |
| 223 |
Python 3.14, removed in 3.16) from inside ``Gtk.main_iteration_do()``. |
| 224 |
The warning must be suppressed in the *current* warnings-filter scope |
| 225 |
rather than inside a per-call ``catch_warnings()`` in ``refresh_gui()``: |
| 226 |
``test_shred_paths`` runs a background ``GtkWorkerThread`` whose own |
| 227 |
``catch_warnings()`` (inside PyGObject/asyncio) can race with the main |
| 228 |
thread's ``catch_warnings()``, causing the ignore filter to be applied |
| 229 |
to the wrong filter-list copy and silently dropped. Installing the |
| 230 |
filter in the active scope (``setUpClass``/``setUp``) makes it visible |
| 231 |
to every copy of the filter list, including the worker thread's. |
| 232 |
""" |
| 233 |
if sys.version_info >= (3, 14): |
| 234 |
warnings.filterwarnings( |
| 235 |
"ignore", |
| 236 |
message=r".*asyncio\.get_event_loop_policy.*", |
| 237 |
category=DeprecationWarning, |
| 238 |
) |
| 239 |
warnings.filterwarnings( |
| 240 |
"ignore", |
| 241 |
message=r".*asyncio\.AbstractEventLoopPolicy.*", |
| 242 |
category=DeprecationWarning, |
| 243 |
) |
| 244 |
|
| 245 |
@classmethod |
| 246 |
def _patch_options_paths(cls): |
| 247 |
to_patch = [('bleachbit.options_dir', cls.tempdir), |
| 248 |
('bleachbit.options_file', os.path.join( |
| 249 |
cls.tempdir, "bleachbit.ini")), |
| 250 |
('bleachbit.personal_cleaners_dir', os.path.join(cls.tempdir, "cleaners"))] |
| 251 |
for target, source in to_patch: |
| 252 |
patcher = mock.patch(target, source) |
| 253 |
patcher.start() |
| 254 |
cls._patchers.append(patcher) |
| 255 |
|
| 256 |
bleachbit.Options.options.restore() |
| 257 |
|
| 258 |
@classmethod |
| 259 |
def tearDownClass(cls): |
| 260 |
"""Do common teardown for the test case |
| 261 |
|
| 262 |
* Collect garbage. |
| 263 |
* Remove the temporary directory. |
| 264 |
* Restore options paths. |
| 265 |
""" |
| 266 |
bleachbit.Options.options.reset_overrides() |
| 267 |
# Cancel any pending deferred flush (Options.__schedule_flush) |
| 268 |
# so its background timer does not recreate bleachbit.ini inside |
| 269 |
# tempdir while rmtree is mid-way through deleting it. |
| 270 |
bleachbit.Options.options.cancel_pending_flush() |
| 271 |
gc_collect() |
| 272 |
# Stop patching the options paths before rmtree to avoid a |
| 273 |
# potential flush into cls.tempdir while rmtree() is running |
| 274 |
# to avoid OSError [Errno 66] Directory not empty. |
| 275 |
if 'BLEACHBIT_TEST_OPTIONS_DIR' not in os.environ: |
| 276 |
cls._stop_patch_options_paths() |
| 277 |
# On Windows, a file may be temporarily locked, so retry. |
| 278 |
# On macOS/Linux, a deferred flush or filesystem race may briefly |
| 279 |
# make the directory non-empty, so retry on OSError too. |
| 280 |
for attempt in range(5): |
| 281 |
try: |
| 282 |
if os.path.exists(cls.tempdir): |
| 283 |
shutil.rmtree(cls.tempdir) |
| 284 |
break |
| 285 |
except OSError: |
| 286 |
# Log what is left so we can diagnose races. |
| 287 |
try: |
| 288 |
remaining = os.listdir(cls.tempdir) |
| 289 |
except OSError: |
| 290 |
remaining = ['<listdir failed>'] |
| 291 |
logger.warning( |
| 292 |
'tearDownClass: rmtree(%s) failed (attempt %d): %s; ' |
| 293 |
'remaining entries: %r', |
| 294 |
cls.tempdir, attempt + 1, sys.exc_info()[1], remaining) |
| 295 |
if attempt < 4: |
| 296 |
time.sleep(1) |
| 297 |
else: |
| 298 |
raise |
| 299 |
|
| 300 |
@classmethod |
| 301 |
def _stop_patch_options_paths(cls): |
| 302 |
for patcher in cls._patchers: |
| 303 |
patcher.stop() |
| 304 |
|
| 305 |
def run(self, result=None): |
| 306 |
"""Run the test case with conditional timer message""" |
| 307 |
start = time.perf_counter() |
| 308 |
outcome = super().run(result) |
| 309 |
duration = time.perf_counter() - start |
| 310 |
threshold = os.getenv('BLEACHBIT_SLOW_TEST_THRESHOLD') # in seconds |
| 311 |
if threshold: |
| 312 |
threshold = float(threshold) |
| 313 |
if not threshold or threshold < 0: |
| 314 |
threshold = 30.0 |
| 315 |
if duration >= threshold: |
| 316 |
test_id = f"{self.__class__.__name__}.{self._testMethodName}" |
| 317 |
prefix = "🐌 " if _supports_stdout_char("🐌") else "" |
| 318 |
print(f"{prefix}SLOW TEST: {test_id} ({duration:.1f}s)", flush=True) |
| 319 |
return outcome |
| 320 |
|
| 321 |
def setUp(self): |
| 322 |
"""Call before each test method""" |
| 323 |
basedir = os.path.join(os.path.dirname(__file__), '..') |
| 324 |
os.chdir(basedir) |
| 325 |
self._options_file_snapshot = None |
| 326 |
if os.path.exists(bleachbit.options_file): |
| 327 |
with open(bleachbit.options_file, 'rb') as f: |
| 328 |
self._options_file_snapshot = f.read() |
| 329 |
# Re-install the asyncio deprecation filters for this test's |
| 330 |
# catch_warnings() scope (setUpClass ran in a different scope). |
| 331 |
self._install_py314_asyncio_filters() |
| 332 |
|
| 333 |
def tearDown(self): |
| 334 |
"""Call after each test method; restore options file, reload Options""" |
| 335 |
# Restore the working directory in case a test chdir'd into |
| 336 |
# self.tempdir (e.g., test_assertExists_relative_path) to avoid |
| 337 |
# WinError 32 in rmtree() in tearDownClass. |
| 338 |
basedir = os.path.join(os.path.dirname(__file__), '..') |
| 339 |
os.chdir(basedir) |
| 340 |
# Cancel first: a deferred flush holds bleachbit.ini open, which |
| 341 |
# fails the remove below with WinError 32. Cancelling takes the |
| 342 |
# flush lock, so it also waits out a flush already running. |
| 343 |
bleachbit.Options.options.cancel_pending_flush() |
| 344 |
self._restore_options_file() |
| 345 |
bleachbit.Options.options.restore() |
| 346 |
# cancel the flush timer restore() re-arms when the file has no |
| 347 |
# matching version, else it fires during a later test |
| 348 |
bleachbit.Options.options.cancel_pending_flush() |
| 349 |
|
| 350 |
def _restore_options_file(self): |
| 351 |
"""Put bleachbit.ini back the way setUp() found it. |
| 352 |
|
| 353 |
Retries because on Windows a test subprocess can briefly hold |
| 354 |
the file open. |
| 355 |
""" |
| 356 |
for attempt in range(5): |
| 357 |
try: |
| 358 |
if self._options_file_snapshot is not None: |
| 359 |
os.makedirs(os.path.dirname( |
| 360 |
bleachbit.options_file), exist_ok=True) |
| 361 |
with open(bleachbit.options_file, 'wb') as f: |
| 362 |
f.write(self._options_file_snapshot) |
| 363 |
elif os.path.exists(bleachbit.options_file): |
| 364 |
os.remove(bleachbit.options_file) |
| 365 |
return |
| 366 |
except PermissionError: |
| 367 |
logger.warning('tearDown: restoring %s failed (attempt %d): %s', |
| 368 |
bleachbit.options_file, attempt + 1, |
| 369 |
sys.exc_info()[1]) |
| 370 |
if attempt == 4: |
| 371 |
raise |
| 372 |
time.sleep(0.5) |
| 373 |
|
| 374 |
# |
| 375 |
# type asserts |
| 376 |
# |
| 377 |
|
| 378 |
def assertIsInteger(self, obj, msg=''): |
| 379 |
self.assertIsInstance(obj, int, msg) |
| 380 |
|
| 381 |
def assertIsString(self, obj, msg=''): |
| 382 |
self.assertIsInstance(obj, str, msg) |
| 383 |
|
| 384 |
def assertIsBytes(self, obj, msg=''): |
| 385 |
self.assertIsInstance(obj, bytes, msg) |
| 386 |
|
| 387 |
def assertIsLanguageCode(self, lang_id): |
| 388 |
self.assertIsInstance(lang_id, str) |
| 389 |
if lang_id in ('C', 'C.UTF-8', 'C.utf8', 'POSIX'): |
| 390 |
return |
| 391 |
self.assertGreaterEqual(len(lang_id), 2) |
| 392 |
pattern = r'^[a-z]{2,3}([_-]([A-Z][A-Za-z]{1,3}|[0-9]{3}))?(\.[a-zA-Z][a-zA-Z0-9-]+)?(@\w+)?$' |
| 393 |
self.assertTrue(re.match(pattern, lang_id), |
| 394 |
f'Invalid language code format: {lang_id}') |
| 395 |
|
| 396 |
@staticmethod |
| 397 |
def check_exists(func, path): |
| 398 |
try: |
| 399 |
func(path) |
| 400 |
return True |
| 401 |
except PermissionError: |
| 402 |
# Python 3.4: on Windows os.path.[l]exists may return False when access is denied: |
| 403 |
# https://bugs.python.org/issue28075 |
| 404 |
return True |
| 405 |
except Exception: |
| 406 |
return False |
| 407 |
|
| 408 |
# |
| 409 |
# file asserts |
| 410 |
# |
| 411 |
@staticmethod |
| 412 |
def _assert_path(path): |
| 413 |
"""Normalize a path for existence checks in unit tests.""" |
| 414 |
# TestMakefile.py uses relative path without an environment variable. |
| 415 |
# TestWinapp.py uses variable "$bbtestdir" |
| 416 |
# However, do not expand paths that are already absolute or Path objects. |
| 417 |
if isinstance(path, Path): |
| 418 |
return str(path) |
| 419 |
assert isinstance( |
| 420 |
path, str), f'path must be a string or Path, not {type(path)}' |
| 421 |
if not os.path.isabs(path): |
| 422 |
path = os.path.expandvars(path) |
| 423 |
return path |
| 424 |
|
| 425 |
# Our assertion method names follow the convention in Python's unittest |
| 426 |
# pylint: disable-next=invalid-name |
| 427 |
def assertExists(self, path, msg='', func=os.stat): |
| 428 |
"""Check that a file, directory, or any path exists""" |
| 429 |
path = self._assert_path(path) |
| 430 |
if not self.check_exists(func, get_test_path(path)): |
| 431 |
raise AssertionError( |
| 432 |
'The file %s should exist, but it does not. %s' % (path, msg)) |
| 433 |
|
| 434 |
# pylint: disable-next=invalid-name |
| 435 |
def assertNotExists(self, path, msg='', func=os.stat): |
| 436 |
"""Check that a file, directory, or any path does not exist""" |
| 437 |
path = self._assert_path(path) |
| 438 |
if self.check_exists(func, get_test_path(path)): |
| 439 |
raise AssertionError( |
| 440 |
'The file %s should not exist, but it does. %s' % (path, msg)) |
| 441 |
|
| 442 |
# pylint: disable-next=invalid-name |
| 443 |
def assertLExists(self, path, msg=''): |
| 444 |
"""Check that a file, directory, or any path exists using lstat""" |
| 445 |
self.assertExists(path, msg, os.lstat) |
| 446 |
|
| 447 |
# pylint: disable-next=invalid-name |
| 448 |
def assertNotLExists(self, path, msg=''): |
| 449 |
"""Check that a file, directory, or any path does not exist using lstat""" |
| 450 |
self.assertNotExists(path, msg, os.lstat) |
| 451 |
|
| 452 |
def assertCondExists(self, cond, path, msg=''): |
| 453 |
if cond: |
| 454 |
self.assertExists(path, msg) |
| 455 |
else: |
| 456 |
self.assertNotExists(path, msg) |
| 457 |
|
| 458 |
def assertDirectoryCount(self, path, count, list_directories=True): |
| 459 |
"""Assert that a directory has a specific number of files |
| 460 |
|
| 461 |
- Counts recursively |
| 462 |
- Counts links |
| 463 |
- Does not recurse links |
| 464 |
|
| 465 |
""" |
| 466 |
object_list = list(children_in_directory(path, list_directories)) |
| 467 |
self.assertEqual(len(object_list), count, f"contains {len(object_list)} objects " |
| 468 |
f"such as {object_list[:2]}, expected {count}") |
| 469 |
|
| 470 |
# |
| 471 |
# file creation functions |
| 472 |
# |
| 473 |
def write_file(self, filename, contents=b'', mode='wb', encoding=None, text=None): |
| 474 |
"""Create a temporary file, optionally writing contents to it |
| 475 |
|
| 476 |
If `text` is given, it is written in text mode with utf-8 encoding, |
| 477 |
and `mode`/`encoding` are set automatically. `text` is mutually |
| 478 |
exclusive with `contents`. |
| 479 |
|
| 480 |
The temporary file is automatically deleted after testing. |
| 481 |
""" |
| 482 |
if text is not None: |
| 483 |
if contents != b'': |
| 484 |
raise ValueError( |
| 485 |
"write_file: `text` is exclusive to `contents`") |
| 486 |
contents = text |
| 487 |
mode = 'w' |
| 488 |
encoding = 'utf-8' |
| 489 |
if not encoding and mode == 'w': |
| 490 |
encoding = 'utf-8' |
| 491 |
if not os.path.isabs(filename): |
| 492 |
filename = os.path.join(self.tempdir, filename) |
| 493 |
with open(extended_path(filename), mode, encoding=encoding) as f: |
| 494 |
f.write(contents) |
| 495 |
assert (os.path.exists(extended_path(filename))) |
| 496 |
with open(extended_path(filename), 'rb' if 'b' in mode else 'r', encoding=encoding if 'b' not in mode else None) as f: |
| 497 |
written_contents = f.read() |
| 498 |
expected = contents if 'b' in mode else contents.encode( |
| 499 |
encoding) if encoding else contents |
| 500 |
actual = written_contents if 'b' in mode else written_contents.encode( |
| 501 |
encoding) if encoding else written_contents |
| 502 |
assert actual == expected, f"File contents mismatch: expected {expected!r}, got {actual!r}" |
| 503 |
return filename |
| 504 |
|
| 505 |
def mkdir(self, dirname): |
| 506 |
"""Create a directory with a given name |
| 507 |
|
| 508 |
If dirname is not absolute, it will be created in self.tempdir. |
| 509 |
|
| 510 |
Returns the path to the created directory. |
| 511 |
""" |
| 512 |
assert isinstance(dirname, str) |
| 513 |
if not os.path.isabs(dirname): |
| 514 |
dirname = os.path.join(self.tempdir, dirname) |
| 515 |
ext_dirname = extended_path(dirname) |
| 516 |
os.makedirs(ext_dirname, exist_ok=True) |
| 517 |
self.assertExists(ext_dirname) |
| 518 |
self.assertTrue(os.path.isdir(ext_dirname)) |
| 519 |
self.assertFalse(is_hard_link(ext_dirname)) |
| 520 |
self.assertTrue(is_normal_directory(ext_dirname)) |
| 521 |
self.assertFalse(os.path.isfile(ext_dirname)) |
| 522 |
if bleachbit.IS_WINDOWS: |
| 523 |
self.assertFalse(Windows.is_junction(ext_dirname)) |
| 524 |
return dirname |
| 525 |
|
| 526 |
def mkstemp(self, **kwargs): |
| 527 |
"""Create a temporary file |
| 528 |
|
| 529 |
If dir is not specified, it will be created in self.tempdir, and tempdir |
| 530 |
will be automatically deleted after testing. |
| 531 |
|
| 532 |
If prefix is not specified, it's defined by the test method name. |
| 533 |
""" |
| 534 |
if 'dir' not in kwargs: |
| 535 |
kwargs['dir'] = self.tempdir |
| 536 |
if 'prefix' not in kwargs: |
| 537 |
kwargs['prefix'] = f"{self.__class__.__name__}-{self._testMethodName}-" |
| 538 |
(fd, filename) = tempfile.mkstemp(**kwargs) |
| 539 |
os.close(fd) |
| 540 |
return filename |
| 541 |
|
| 542 |
def mkdtemp(self, **kwargs): |
| 543 |
"""Create a temporary directory |
| 544 |
|
| 545 |
If dir is not specified, it will be created in self.tempdir, and tempdir |
| 546 |
will be automatically deleted after testing. |
| 547 |
|
| 548 |
If prefix is not specified, it's defined by the test method name. |
| 549 |
""" |
| 550 |
if 'dir' not in kwargs: |
| 551 |
kwargs['dir'] = self.tempdir |
| 552 |
if 'prefix' not in kwargs: |
| 553 |
kwargs['prefix'] = f"{self.__class__.__name__}-{self._testMethodName}-" |
| 554 |
return tempfile.mkdtemp(**kwargs) |
| 555 |
|
| 556 |
|
| 557 |
def get_test_path(path): |
| 558 |
"""Normalize test paths for Windows""" |
| 559 |
if not bleachbit.IS_WINDOWS: |
| 560 |
return path |
| 561 |
path = os.path.normpath(path) |
| 562 |
# The \\?\ extended-length prefix applied by extended_path() requires |
| 563 |
# an absolute path: Windows treats "\\?\<relative>" as invalid and |
| 564 |
# reports it as non-existent. |
| 565 |
if not os.path.isabs(path): |
| 566 |
path = os.path.abspath(path) |
| 567 |
return extended_path(path) |
| 568 |
|
| 569 |
|
| 570 |
def get_env(key): |
| 571 |
"""Get an environment variable. If not set, returns None instead of KeyError.""" |
| 572 |
if not key in os.environ: |
| 573 |
return None |
| 574 |
return os.environ[key] |
| 575 |
|
| 576 |
|
| 577 |
def have_root(): |
| 578 |
"""Return true if we have root privileges on POSIX systems""" |
| 579 |
return sudo_mode() or os.getuid() == 0 |
| 580 |
|
| 581 |
|
| 582 |
def put_env(key, val): |
| 583 |
"""Put an environment variable. None removes the key |
| 584 |
|
| 585 |
Returns None |
| 586 |
""" |
| 587 |
if not val: |
| 588 |
if key in os.environ: |
| 589 |
del os.environ[key] |
| 590 |
else: |
| 591 |
os.environ[key] = val |
| 592 |
|
| 593 |
|
| 594 |
def skipIfWindows(f): |
| 595 |
"""Skip unit test if running on Windows""" |
| 596 |
return unittest.skipIf(bleachbit.IS_WINDOWS, 'running on Windows')(f) |
| 597 |
|
| 598 |
|
| 599 |
def skipUnlessDestructive(f): |
| 600 |
"""Skip unless destructive tests are allowed""" |
| 601 |
return unittest.skipUnless(os.getenv('DESTRUCTIVE_TESTS') == 'T', 'environment variable DESTRUCTIVE_TESTS not set to T')(f) |
| 602 |
|
| 603 |
|
| 604 |
def skipUnlessLinux(f): |
| 605 |
"""Skip unit test unless running on Linux""" |
| 606 |
return unittest.skipUnless(bleachbit.IS_LINUX, 'not running on Linux')(f) |
| 607 |
|
| 608 |
|
| 609 |
def skipUnlessMac(f): |
| 610 |
"""Skip unit test unless running on macOS""" |
| 611 |
return unittest.skipUnless(bleachbit.IS_MAC, 'not running on macOS')(f) |
| 612 |
|
| 613 |
|
| 614 |
def skipUnlessWindows(f): |
| 615 |
"""Skip unit test unless running on Windows""" |
| 616 |
return unittest.skipUnless(bleachbit.IS_WINDOWS, 'not running on Windows')(f) |
| 617 |
|
| 618 |
|
| 619 |
def also_with_sudo(test_func): |
| 620 |
""" |
| 621 |
Decorator to mark test methods that should be run both normally and with sudo. |
| 622 |
|
| 623 |
See also `tests/test_with_sudo.py`. |
| 624 |
""" |
| 625 |
test_func._also_with_sudo = True |
| 626 |
return test_func |
| 627 |
|
| 628 |
|
| 629 |
def touch_file(filename): |
| 630 |
"""Create an empty file""" |
| 631 |
dname = os.path.dirname(filename) |
| 632 |
if dname and not os.path.exists(dname): |
| 633 |
# Make the directory, if it does not exist. |
| 634 |
os.makedirs(dname) |
| 635 |
Path(filename).touch() |
| 636 |
assert os.path.exists(filename) |
| 637 |
assert not is_normal_directory(filename) |
| 638 |
|
| 639 |
|
| 640 |
def validate_result(self, result, really_delete=False, allow_vanishing=False): |
| 641 |
"""Validate the command returned valid results. |
| 642 |
|
| 643 |
Args: |
| 644 |
result: The result dictionary to validate. |
| 645 |
really_delete: Whether the operation actually deleted files. |
| 646 |
allow_vanishing: When True, allows for files that may disappear between |
| 647 |
discovery and validation (e.g., /tmp on a busy system) |
| 648 |
""" |
| 649 |
self.assertIsInstance(result, dict, "result is a %s" % type(result)) |
| 650 |
# label |
| 651 |
self.assertIsString(result['label']) |
| 652 |
self.assertGreater(len(result['label'].strip()), 0) |
| 653 |
# n_* |
| 654 |
self.assertIsInteger(result['n_deleted']) |
| 655 |
self.assertGreaterEqual(result['n_deleted'], 0) |
| 656 |
self.assertLessEqual(result['n_deleted'], 1) |
| 657 |
self.assertEqual(result['n_special'] + result['n_deleted'], 1) |
| 658 |
# size |
| 659 |
self.assertIsInstance(result['size'], (int, type( |
| 660 |
None),), "size is %s" % str(result['size'])) |
| 661 |
# path |
| 662 |
filename = result['path'] |
| 663 |
if not filename: |
| 664 |
# the process action, for example, does not have a filename |
| 665 |
return |
| 666 |
self.assertIsInstance(filename, (str, type(None)), |
| 667 |
"Filename is invalid: '%s' (type %s)" % (filename, type(filename))) |
| 668 |
if isinstance(filename, str) and not filename[0:2] == 'HK': |
| 669 |
if really_delete: |
| 670 |
self.assertNotLExists(filename) |
| 671 |
elif allow_vanishing: |
| 672 |
# Tolerate vanishing files during preview. |
| 673 |
if not os.path.lexists(filename): |
| 674 |
logger.debug('vanished %s', filename) |
| 675 |
else: |
| 676 |
# Do not tolerate vanishing during preview. |
| 677 |
self.assertLExists(filename) |
| 678 |
|
| 679 |
|
| 680 |
def get_winregistry_value(key, subkey): |
| 681 |
try: |
| 682 |
with winreg.OpenKey(key, subkey) as hkey: |
| 683 |
return winreg.QueryValue(hkey, None) |
| 684 |
except FileNotFoundError: |
| 685 |
return None |
| 686 |
|
| 687 |
|
| 688 |
def get_opened_windows_titles(): |
| 689 |
""" |
| 690 |
Get the titles of all opened windows. |
| 691 |
|
| 692 |
Returns: |
| 693 |
list: A list of window titles. |
| 694 |
""" |
| 695 |
opened_windows_titles = [] |
| 696 |
|
| 697 |
def enumerate_opened_windows_titles(hwnd, _ctx): |
| 698 |
text = win32gui.GetWindowText(hwnd) |
| 699 |
if win32gui.IsWindowVisible(hwnd) and text: |
| 700 |
opened_windows_titles.append(text) |
| 701 |
|
| 702 |
win32gui.EnumWindows(enumerate_opened_windows_titles, None) |
| 703 |
return opened_windows_titles |
| 704 |
|
| 705 |
|
| 706 |
# Common test strings for filename testing across different test modules |
| 707 |
# https://github.com/bleachbit/bleachbit/issues/1709 |
| 708 |
_SPECIAL_TEST_STRINGS = [ |
| 709 |
'.prefixandsuffix', # simple |
| 710 |
"x".zfill(150), # long |
| 711 |
' begins_with_space', |
| 712 |
"''", # quotation mark |
| 713 |
"~`!@#$%^&()-_+=x", # non-alphanumeric characters |
| 714 |
"[]{};'.,x", # non-alphanumeric characters |
| 715 |
'abcdefgh', # simple Unicode |
| 716 |
'J\xf8rgen Scandinavian', |
| 717 |
'\u2014em-dash', # LP#1454030 |
| 718 |
"עִבְרִית", # Hebrew |
| 719 |
"アメリカ", # Katakana |
| 720 |
"ÄäǞǟËëḦḧÏïḮḯÖöȪȫṎṏT̈ẗÜüǕǖǗǘǙǚǛǜṲṳṺṻẄẅẌẍŸÿ", # umlauts |
| 721 |
'sigil-should$not-change', |
| 722 |
'issue_1709_\udcd6', # GitHub issue 1709 |
| 723 |
'invalid_unicode_surrogate_\udce9', |
| 724 |
'multi_surrogate_\udcd6\udcd7\udcd8', |
| 725 |
'fire_emoji_\U0001F525', |
| 726 |
'ascii.bak', |
| 727 |
'äöüßÄÖÜ.bak', |
| 728 |
"עִבְרִית.bak", |
| 729 |
'ɡælɪk.bak' |
| 730 |
] |
| 731 |
|
| 732 |
|
| 733 |
def _has_surrogate(s): |
| 734 |
"""Return True if the string contains a lone UTF-16 surrogate.""" |
| 735 |
return any('\ud800' <= c <= '\udfff' for c in s) |
| 736 |
|
| 737 |
|
| 738 |
# macOS APFS/HFS+ rejects lone UTF-16 surrogates in filenames with |
| 739 |
# OSError "Illegal byte sequence", so exclude those strings on macOS. |
| 740 |
SPECIAL_TEST_STRINGS = [ |
| 741 |
s for s in _SPECIAL_TEST_STRINGS |
| 742 |
if not (bleachbit.IS_MAC and _has_surrogate(s)) |
| 743 |
] |
| 744 |
del _SPECIAL_TEST_STRINGS, _has_surrogate |
| 745 |
|
| 746 |
# Additional strings for POSIX systems. |
| 747 |
# Windows doesn't allow or requires special handling for these characters. |
| 748 |
POSIX_SPECIAL_TEST_STRINGS = [ |
| 749 |
'"*', |
| 750 |
'\t\\', |
| 751 |
':?<>|', |
| 752 |
' ', |
| 753 |
'endspace ', |
| 754 |
'endperiod.' # Windows filenames cannot end with space or period |
| 755 |
] |