| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (c) 2008-2026 Andrew Ziem. |
| 3 |
# |
| 4 |
# This work is licensed under the terms of the GNU GPL, version 3 or |
| 5 |
# later. See the COPYING file in the top-level directory. |
| 6 |
|
| 7 |
""" |
| 8 |
Test case for module Windows |
| 9 |
""" |
| 10 |
|
| 11 |
|
| 12 |
# standard imports |
| 13 |
import ctypes |
| 14 |
import itertools |
| 15 |
import os |
| 16 |
import platform |
| 17 |
import shutil |
| 18 |
import subprocess |
| 19 |
import tempfile |
| 20 |
import time |
| 21 |
from decimal import Decimal |
| 22 |
from pathlib import Path |
| 23 |
from unittest import mock |
| 24 |
from random import randint |
| 25 |
|
| 26 |
from tests.common import pytest |
| 27 |
|
| 28 |
# first party imports |
| 29 |
from tests import common |
| 30 |
|
| 31 |
import bleachbit |
| 32 |
from bleachbit import FileUtilities, General |
| 33 |
from bleachbit.Command import Delete, Function |
| 34 |
from bleachbit.FileUtilities import extended_path, extended_path_undo |
| 35 |
from bleachbit.Windows import ( |
| 36 |
delete_locked_file, |
| 37 |
delete_registry_key, |
| 38 |
delete_registry_value, |
| 39 |
delete_updates, |
| 40 |
is_service_running, |
| 41 |
run_net_service_command, |
| 42 |
detect_registry_key, |
| 43 |
empty_recycle_bin, |
| 44 |
flush_dns, |
| 45 |
get_clipboard_paths, |
| 46 |
get_fixed_drives, |
| 47 |
get_font_conf_file, |
| 48 |
get_known_folder_path, |
| 49 |
get_recycle_bin, |
| 50 |
get_windows_system_paths, |
| 51 |
get_windows_version, |
| 52 |
elevate_privileges, |
| 53 |
has_fontconfig_cache, |
| 54 |
is_junction, |
| 55 |
move_to_recycle_bin, |
| 56 |
parse_windows_build, |
| 57 |
path_on_network, |
| 58 |
set_environ, |
| 59 |
setup_environment, |
| 60 |
shell_change_notify, |
| 61 |
split_registry_key, |
| 62 |
read_registry_key, |
| 63 |
get_sid_token_48, |
| 64 |
is_ots_elevation, |
| 65 |
_add_command_line_parameters, |
| 66 |
get_splash_screen_delay_seconds, |
| 67 |
expand_windows_system_vars, |
| 68 |
SplashThread, |
| 69 |
) |
| 70 |
from bleachbit import logger |
| 71 |
|
| 72 |
|
| 73 |
class WindowsSystemPathsTestCase(common.BleachbitTestCase): |
| 74 |
"""Test Windows system directory expansion.""" |
| 75 |
|
| 76 |
def test_get_windows_system_paths_32_bit_os(self): |
| 77 |
"""Unit test get_windows_system_paths() for 32-bit Windows.""" |
| 78 |
env = { |
| 79 |
'WinDir': r'C:\Windows', |
| 80 |
'PROCESSOR_ARCHITECTURE': 'x86', |
| 81 |
} |
| 82 |
self.assertEqual( |
| 83 |
[r'C:\Windows\System32'], |
| 84 |
get_windows_system_paths(env, process_bits=32)) |
| 85 |
|
| 86 |
def test_get_windows_system_paths_64_bit_process(self): |
| 87 |
"""Unit test get_windows_system_paths() for 64-bit Python.""" |
| 88 |
env = { |
| 89 |
'WinDir': r'C:\Windows', |
| 90 |
'PROCESSOR_ARCHITECTURE': 'AMD64', |
| 91 |
} |
| 92 |
self.assertEqual( |
| 93 |
[r'C:\Windows\System32', r'C:\Windows\SysWOW64'], |
| 94 |
get_windows_system_paths(env, process_bits=64)) |
| 95 |
|
| 96 |
def test_get_windows_system_paths_wow64_process(self): |
| 97 |
"""Unit test get_windows_system_paths() for 32-bit Python on 64-bit Windows.""" |
| 98 |
env = { |
| 99 |
'WinDir': r'C:\Windows', |
| 100 |
'PROCESSOR_ARCHITECTURE': 'x86', |
| 101 |
'PROCESSOR_ARCHITEW6432': 'AMD64', |
| 102 |
} |
| 103 |
self.assertEqual( |
| 104 |
[r'C:\Windows\Sysnative', r'C:\Windows\SysWOW64'], |
| 105 |
get_windows_system_paths(env, process_bits=32)) |
| 106 |
|
| 107 |
def test_get_windows_system_paths(self): |
| 108 |
"""Test get_windows_system_paths() in general""" |
| 109 |
# Test with default environment |
| 110 |
ret = get_windows_system_paths() |
| 111 |
self.assertIsInstance(ret, list) |
| 112 |
for path in ret: |
| 113 |
self.assertTrue(os.path.isabs(path)) |
| 114 |
self.assertExists(path) |
| 115 |
|
| 116 |
def test_expand_windows_system_vars(self): |
| 117 |
"""Unit test expand_windows_system_vars().""" |
| 118 |
path_arg = r'%WindowsSystem%\LogFiles\*.log' |
| 119 |
# Without providing system paths |
| 120 |
paths = expand_windows_system_vars(path_arg) |
| 121 |
self.assertIsInstance(paths, list) |
| 122 |
# On 32-bit OS, it returns one. On 64-bit OS, it returns |
| 123 |
# 2 (regardless of bitness of the process). |
| 124 |
self.assertIn(len(paths), (1, 2)) |
| 125 |
# Provide system paths |
| 126 |
paths = expand_windows_system_vars( |
| 127 |
path_arg, |
| 128 |
[r'C:\Windows\Sysnative', r'C:\Windows\SysWOW64']) |
| 129 |
self.assertEqual( |
| 130 |
[r'C:\Windows\Sysnative\LogFiles\*.log', |
| 131 |
r'C:\Windows\SysWOW64\LogFiles\*.log'], |
| 132 |
paths) |
| 133 |
|
| 134 |
|
| 135 |
if bleachbit.IS_WINDOWS: |
| 136 |
import pywintypes |
| 137 |
import win32api |
| 138 |
import win32service |
| 139 |
import winreg |
| 140 |
from win32com.shell import shell |
| 141 |
|
| 142 |
from bleachbit import Windows |
| 143 |
|
| 144 |
|
| 145 |
def put_objects_into_recycle_bin(): |
| 146 |
"""Put a file and a folder into the recycle bin""" |
| 147 |
count = 0 |
| 148 |
# make a file and move it to the recycle bin |
| 149 |
tests = ['regular', 'unicode-emdash-u\u2014', |
| 150 |
'long' + 'x' * 100] + common.SPECIAL_TEST_STRINGS |
| 151 |
for test in tests: |
| 152 |
with tempfile.NamedTemporaryFile( |
| 153 |
prefix='bleachbit-recycle-file', suffix=test, delete=False) as f: |
| 154 |
filename = f.name |
| 155 |
# Write enough data to exceed the MFT resident threshold. |
| 156 |
f.write(b'x' * (1024 * 32)) |
| 157 |
move_to_recycle_bin(filename) |
| 158 |
count += 1 |
| 159 |
# make a folder and move it to the recycle bin |
| 160 |
dirname = tempfile.mkdtemp(prefix='bleachbit-recycle-folder') |
| 161 |
common.touch_file(os.path.join(dirname, 'file')) |
| 162 |
move_to_recycle_bin(dirname) |
| 163 |
count += 1 |
| 164 |
return count |
| 165 |
|
| 166 |
|
| 167 |
class WindowsLinksMixIn(): |
| 168 |
"""Mixin class for Windows link creation methods.""" |
| 169 |
|
| 170 |
def _create_win_dir_symlink(self, target, linkname): |
| 171 |
"""Create a directory symlink""" |
| 172 |
|
| 173 |
self.assertFalse(os.path.lexists(linkname), |
| 174 |
f'Link must not exist: {linkname}') |
| 175 |
self.assertTrue(os.path.isabs(target), |
| 176 |
f'Target must be absolute path: {target}') |
| 177 |
self.assertTrue(os.path.isabs(linkname), |
| 178 |
f'Link must be absolute path: {linkname}') |
| 179 |
self.assertExists(target) |
| 180 |
target_path = Path(target) |
| 181 |
self.assertTrue(target_path.is_dir(), |
| 182 |
f'Target must be an existing directory: {target}') |
| 183 |
|
| 184 |
kernel32 = ctypes.windll.kernel32 |
| 185 |
kernel32.CreateSymbolicLinkW.argtypes = [ |
| 186 |
ctypes.c_wchar_p, |
| 187 |
ctypes.c_wchar_p, |
| 188 |
ctypes.c_uint32, |
| 189 |
] |
| 190 |
kernel32.CreateSymbolicLinkW.restype = ctypes.c_ubyte |
| 191 |
result = kernel32.CreateSymbolicLinkW( |
| 192 |
linkname, target, 1) # SYMBOLIC_LINK_FLAG_DIRECTORY |
| 193 |
if result == 0: |
| 194 |
err = ctypes.GetLastError() |
| 195 |
raise OSError(err, ctypes.FormatError(err)) |
| 196 |
self.assertExists(linkname) |
| 197 |
link_path = Path(linkname) |
| 198 |
self.assertTrue(link_path.is_symlink()) |
| 199 |
self.assertTrue(link_path.is_dir()) |
| 200 |
self.assertFalse(Windows.is_junction(linkname)) |
| 201 |
self.assertFalse(FileUtilities.is_normal_directory(linkname)) |
| 202 |
|
| 203 |
def _create_win_file_symlink(self, target, linkname): |
| 204 |
"""Create a file symlink""" |
| 205 |
|
| 206 |
self.assertFalse(os.path.lexists(linkname), |
| 207 |
f'Link must not exist: {linkname}') |
| 208 |
self.assertTrue(os.path.isabs(target), |
| 209 |
f'Target must be absolute path: {target}') |
| 210 |
self.assertTrue(os.path.isabs(linkname), |
| 211 |
f'Link must be absolute path: {linkname}') |
| 212 |
self.assertExists(target) |
| 213 |
target_path = Path(target) |
| 214 |
self.assertTrue(target_path.is_file(), |
| 215 |
f'Target must be an existing file: {target}') |
| 216 |
|
| 217 |
kernel32 = ctypes.windll.kernel32 |
| 218 |
kernel32.CreateSymbolicLinkW.argtypes = [ |
| 219 |
ctypes.c_wchar_p, |
| 220 |
ctypes.c_wchar_p, |
| 221 |
ctypes.c_uint32, |
| 222 |
] |
| 223 |
kernel32.CreateSymbolicLinkW.restype = ctypes.c_ubyte |
| 224 |
result = kernel32.CreateSymbolicLinkW( |
| 225 |
linkname, target, 0) # SYMBOLIC_LINK_FLAG_FILE |
| 226 |
if result == 0: |
| 227 |
err = ctypes.GetLastError() |
| 228 |
raise OSError(err, ctypes.FormatError(err)) |
| 229 |
self.assertExists(linkname) |
| 230 |
link_path = Path(linkname) |
| 231 |
self.assertTrue(link_path.is_symlink()) |
| 232 |
self.assertTrue(link_path.is_file()) |
| 233 |
|
| 234 |
def _create_win_hard_link(self, target, linkname): |
| 235 |
"""Create a hard link to a file""" |
| 236 |
|
| 237 |
self.assertFalse(os.path.lexists(linkname), |
| 238 |
f'Link must not exist: {linkname}') |
| 239 |
self.assertTrue(os.path.isabs(target), |
| 240 |
f'Target must be absolute path: {target}') |
| 241 |
self.assertTrue(os.path.isabs(linkname), |
| 242 |
f'Link must be absolute path: {linkname}') |
| 243 |
self.assertExists(target) |
| 244 |
target_path = Path(target) |
| 245 |
self.assertTrue(target_path.is_file(), |
| 246 |
f'Target must be an existing file: {target}') |
| 247 |
kernel32 = ctypes.windll.kernel32 |
| 248 |
kernel32.CreateHardLinkW.argtypes = [ |
| 249 |
ctypes.c_wchar_p, |
| 250 |
ctypes.c_wchar_p, |
| 251 |
ctypes.c_void_p, |
| 252 |
] |
| 253 |
kernel32.CreateHardLinkW.restype = ctypes.c_bool |
| 254 |
result = kernel32.CreateHardLinkW(linkname, target, None) |
| 255 |
if not result: |
| 256 |
err = ctypes.GetLastError() |
| 257 |
raise OSError(err, ctypes.FormatError(err)) |
| 258 |
self.assertExists(linkname) |
| 259 |
link_path = Path(linkname) |
| 260 |
self.assertTrue(link_path.is_file()) |
| 261 |
self.assertFalse(link_path.is_symlink()) |
| 262 |
self.assertFalse(Windows.is_junction(linkname)) |
| 263 |
self.assertTrue(os.path.samefile(target, linkname)) |
| 264 |
self.assertFalse(FileUtilities.is_normal_directory(linkname)) |
| 265 |
|
| 266 |
def _create_win_junction(self, target, linkname): |
| 267 |
"""Create a directory junction using mklink /J.""" |
| 268 |
|
| 269 |
if os.path.lexists(linkname): |
| 270 |
raise OSError(f'Link already exists: {linkname}') |
| 271 |
self.assertTrue(os.path.isabs(target), |
| 272 |
f'Target must be absolute path: {target}') |
| 273 |
self.assertTrue(os.path.isabs(linkname), |
| 274 |
f'Link must be absolute path: {linkname}') |
| 275 |
self.assertExists(target) |
| 276 |
target_path = Path(target) |
| 277 |
self.assertTrue(target_path.is_dir(), |
| 278 |
f'Target must be an existing directory: {target}') |
| 279 |
cmd = ['cmd', '/c', 'mklink', '/J', |
| 280 |
extended_path(linkname), extended_path(target)] |
| 281 |
subprocess.check_call(cmd) |
| 282 |
self.assertExists(linkname) |
| 283 |
self.assertTrue(Windows.is_junction(linkname)) |
| 284 |
path = Path(linkname) |
| 285 |
self.assertTrue(path.is_dir()) |
| 286 |
self.assertTrue(path.is_junction()) |
| 287 |
|
| 288 |
|
| 289 |
@common.skipUnlessWindows |
| 290 |
class WindowsTestCase(common.BleachbitTestCase, WindowsLinksMixIn): |
| 291 |
|
| 292 |
"""Test case for module Windows""" |
| 293 |
|
| 294 |
def skipUnlessAdmin(self): |
| 295 |
if not shell.IsUserAnAdmin(): |
| 296 |
self.skipTest('requires administrator privileges') |
| 297 |
|
| 298 |
def test_flush_dns_uses_absolute_path(self): |
| 299 |
"""flush_dns runs an absolute ipconfig path, not a bare name""" |
| 300 |
with mock.patch('bleachbit.General.run_external', |
| 301 |
return_value=(0, '', '')) as mock_run: |
| 302 |
flush_dns() |
| 303 |
args = mock_run.call_args[0][0] |
| 304 |
self.assertTrue(os.path.isabs(args[0]), args[0]) |
| 305 |
self.assertTrue(args[0].lower().endswith('ipconfig.exe'), args[0]) |
| 306 |
self.assertEqual(args[1], '/flushdns') |
| 307 |
|
| 308 |
@pytest.mark.xdist_group('recycle-bin') |
| 309 |
def test_get_recycle_bin(self): |
| 310 |
"""Unit test for get_recycle_bin""" |
| 311 |
for f in get_recycle_bin(): |
| 312 |
self.assertLExists(extended_path(f)) |
| 313 |
|
| 314 |
@pytest.mark.no_xdist |
| 315 |
@pytest.mark.xdist_group('recycle-bin') |
| 316 |
@common.skipUnlessDestructive |
| 317 |
def test_get_recycle_bin_destructive(self): |
| 318 |
"""Unit test the destructive part of get_recycle_bin""" |
| 319 |
added_count = put_objects_into_recycle_bin() |
| 320 |
# clear recycle bin |
| 321 |
counter = 0 |
| 322 |
for f in get_recycle_bin(): |
| 323 |
counter += 1 |
| 324 |
FileUtilities.delete(f) |
| 325 |
self.assertGreaterEqual(counter, added_count, 'deleted %d' % counter) |
| 326 |
# now it should be empty |
| 327 |
for _f in get_recycle_bin(): |
| 328 |
self.fail('recycle bin should be empty, but it is not') |
| 329 |
|
| 330 |
def _test_link_helper(self, mklink_option, recycle_container, clear_recycle_bin): |
| 331 |
"""Helper function for testing directory junctions and symlinks in the recycle bin. |
| 332 |
|
| 333 |
Tests that get_recycle_bin() correctly handles Windows directory links |
| 334 |
when they are placed in the recycle bin, and verifies that the original |
| 335 |
target directory and its contents are preserved after clearing the bin. |
| 336 |
|
| 337 |
Args: |
| 338 |
mklink_option: Link type to create. '/j' for directory junction, |
| 339 |
'/d' for directory symbolic link. |
| 340 |
recycle_container: If True, move the container directory to the |
| 341 |
recycle bin. If False, move only the link itself. |
| 342 |
clear_recycle_bin: If True, clear the recycle bin after moving |
| 343 |
the link. If False, manually delete items from get_recycle_bin(). |
| 344 |
|
| 345 |
Note: |
| 346 |
Directory symbolic links (/d) require administrator privileges. |
| 347 |
""" |
| 348 |
assert mklink_option in ('/j', '/d') |
| 349 |
if mklink_option == '/d': |
| 350 |
self.skipUnlessAdmin() |
| 351 |
# make a normal directory with a file in it |
| 352 |
target_dir = self.mkdir('target_dir') |
| 353 |
|
| 354 |
canary_base = f'do_not_delete{randint(10000, 9999999)}' |
| 355 |
canary_fn = os.path.join(target_dir, canary_base) |
| 356 |
common.touch_file(canary_fn) |
| 357 |
self.assertFalse(is_junction(canary_fn)) |
| 358 |
|
| 359 |
# make a normal directory to hold a link |
| 360 |
container_dir = self.mkdir('container_dir') |
| 361 |
|
| 362 |
# create the link |
| 363 |
link_pathname = os.path.join(container_dir, 'link') |
| 364 |
if mklink_option == '/j': |
| 365 |
self._create_win_junction(target_dir, link_pathname) |
| 366 |
else: |
| 367 |
self._create_win_dir_symlink(target_dir, link_pathname) |
| 368 |
|
| 369 |
# put the link in the recycle bin |
| 370 |
move_to_recycle_bin( |
| 371 |
container_dir if recycle_container else link_pathname) |
| 372 |
|
| 373 |
def cleanup_dirs(): |
| 374 |
shutil.rmtree(container_dir, True) |
| 375 |
self.assertNotExists(container_dir) |
| 376 |
shutil.rmtree(target_dir, True) |
| 377 |
|
| 378 |
if not clear_recycle_bin: |
| 379 |
cleanup_dirs() |
| 380 |
return |
| 381 |
|
| 382 |
# clear the recycle bin |
| 383 |
for f in get_recycle_bin(): |
| 384 |
if canary_base in f: |
| 385 |
logger.error('get_recycle_bin() returned canary: %s', f) |
| 386 |
FileUtilities.delete(f, shred=False) |
| 387 |
|
| 388 |
# verify the canary is still there |
| 389 |
self.assertExists(canary_fn) |
| 390 |
|
| 391 |
# clean up |
| 392 |
cleanup_dirs() |
| 393 |
|
| 394 |
@pytest.mark.xdist_group('recycle-bin') |
| 395 |
def test_link_types(self): |
| 396 |
"""Unit test for directory junctions and symlinks with recycle bin""" |
| 397 |
for mklink_option, recycle_container, clear_recycle_bin in itertools.product( |
| 398 |
('/j', '/d'), (False, True), (False, True) |
| 399 |
): |
| 400 |
with self.subTest(mklink_option=mklink_option, |
| 401 |
recycle_container=recycle_container, |
| 402 |
clear_recycle_bin=clear_recycle_bin): |
| 403 |
self._test_link_helper( |
| 404 |
mklink_option, recycle_container, clear_recycle_bin) |
| 405 |
|
| 406 |
def _test_broken_link_in_recycle_bin(self, mklink_option, recycle_container, |
| 407 |
break_before_recycle): |
| 408 |
"""Helpful function to test broken directory junctions and symlinks |
| 409 |
in the recycle bin. |
| 410 |
|
| 411 |
When a broken link (target deleted) is in the recycle bin, deleting it |
| 412 |
should delete the link itself, not attempt to follow or restore the |
| 413 |
target. |
| 414 |
|
| 415 |
Args: |
| 416 |
mklink_option: Link type to create. '/j' for directory junction, |
| 417 |
'/d' for directory symbolic link. |
| 418 |
recycle_container: If True, move the container directory to the |
| 419 |
recycle bin. If False, move only the link itself. |
| 420 |
break_before_recycle: If True, delete the target before moving |
| 421 |
the link to the recycle bin. If False, recycle first and then |
| 422 |
delete the target. |
| 423 |
""" |
| 424 |
assert mklink_option in ('/j', '/d') |
| 425 |
if mklink_option == '/d': |
| 426 |
self.skipUnlessAdmin() |
| 427 |
|
| 428 |
before = set(get_recycle_bin()) |
| 429 |
target_dir = self.mkdir('target_dir') |
| 430 |
canary_fn = os.path.join( |
| 431 |
target_dir, f'canary{randint(10000, 9999999)}') |
| 432 |
common.touch_file(canary_fn) |
| 433 |
|
| 434 |
container_dir = self.mkdir('container_dir') |
| 435 |
link_pathname = os.path.join(container_dir, 'link') |
| 436 |
if mklink_option == '/j': |
| 437 |
self._create_win_junction(target_dir, link_pathname) |
| 438 |
else: |
| 439 |
self._create_win_dir_symlink(target_dir, link_pathname) |
| 440 |
|
| 441 |
self.assertTrue(os.path.lexists(link_pathname)) |
| 442 |
self.assertExists(canary_fn) |
| 443 |
|
| 444 |
if break_before_recycle: |
| 445 |
shutil.rmtree(target_dir) |
| 446 |
self.assertTrue(os.path.lexists(link_pathname)) |
| 447 |
self.assertFalse(os.path.exists(link_pathname)) |
| 448 |
|
| 449 |
move_to_recycle_bin( |
| 450 |
container_dir if recycle_container else link_pathname) |
| 451 |
|
| 452 |
if not break_before_recycle: |
| 453 |
shutil.rmtree(target_dir) |
| 454 |
if not recycle_container: |
| 455 |
shutil.rmtree(container_dir) |
| 456 |
|
| 457 |
try: |
| 458 |
added = [p for p in get_recycle_bin() if p not in before] |
| 459 |
self.assertTrue( |
| 460 |
added, 'recycle bin should contain recycled link') |
| 461 |
|
| 462 |
broken = [] |
| 463 |
for f in added: |
| 464 |
ep = extended_path(f) |
| 465 |
self.assertLExists(ep) |
| 466 |
if ((os.path.islink(ep) or is_junction(ep)) and |
| 467 |
not os.path.exists(ep)): |
| 468 |
broken.append(f) |
| 469 |
self.assertTrue( |
| 470 |
broken, 'expected broken link (lexists, not exists)') |
| 471 |
|
| 472 |
for f in added: |
| 473 |
ep = extended_path(f) |
| 474 |
self.assertTrue(FileUtilities.delete(ep, shred=False)) |
| 475 |
self.assertNotLExists(ep) |
| 476 |
|
| 477 |
self.assertFalse(os.path.lexists(link_pathname)) |
| 478 |
self.assertFalse(os.path.lexists(target_dir)) |
| 479 |
if recycle_container or not break_before_recycle: |
| 480 |
self.assertFalse(os.path.lexists(container_dir)) |
| 481 |
else: |
| 482 |
self.assertTrue(os.path.lexists(container_dir)) |
| 483 |
finally: |
| 484 |
empty_recycle_bin(None, True) |
| 485 |
if os.path.lexists(container_dir): |
| 486 |
shutil.rmtree(container_dir, True) |
| 487 |
if os.path.lexists(target_dir): |
| 488 |
shutil.rmtree(target_dir, True) |
| 489 |
|
| 490 |
def _test_broken_link_delete(self, mklink_option, shred): |
| 491 |
"""Helper function to test FileUtilities.delete() on a broken |
| 492 |
link outside the recycle bin. |
| 493 |
|
| 494 |
- Tests both junctions and directory symlinks. |
| 495 |
- Test is Windows only. |
| 496 |
- Target is a directory (not a file). |
| 497 |
- Target is broken (does not exist). |
| 498 |
- Tests both shredding and unlink. |
| 499 |
- Does not invoke the recycle bin. |
| 500 |
""" |
| 501 |
assert mklink_option in ('/j', '/d') |
| 502 |
if mklink_option == '/d': |
| 503 |
self.skipUnlessAdmin() |
| 504 |
|
| 505 |
target_dir = self.mkdir('broken_link_delete_target') |
| 506 |
container_dir = self.mkdir('broken_link_delete_container') |
| 507 |
link_pathname = os.path.join(container_dir, 'link') |
| 508 |
if mklink_option == '/j': |
| 509 |
self._create_win_junction(target_dir, link_pathname) |
| 510 |
else: |
| 511 |
self._create_win_dir_symlink(target_dir, link_pathname) |
| 512 |
shutil.rmtree(target_dir) |
| 513 |
self.assertLExists(link_pathname) |
| 514 |
self.assertFalse(os.path.exists(link_pathname)) |
| 515 |
self.assertTrue(FileUtilities.delete(link_pathname, shred=shred)) |
| 516 |
self.assertNotLExists(link_pathname) |
| 517 |
shutil.rmtree(container_dir, True) |
| 518 |
|
| 519 |
@pytest.mark.xdist_group('recycle-bin') |
| 520 |
def test_broken_link_in_recycle_bin(self): |
| 521 |
"""Unit test for broken directory junctions and symlinks in recycle bin |
| 522 |
|
| 523 |
- Tests both junctions and directory symlinks. |
| 524 |
- Target is a directory (not a file). |
| 525 |
- Target is broken (does not exist). |
| 526 |
- Tests both container in recycle bin and outside recycle bin. |
| 527 |
- Tests both break target before and after recycling. |
| 528 |
- Test is Windows only (of course). |
| 529 |
""" |
| 530 |
for mklink_option, recycle_container, break_before_recycle in itertools.product( |
| 531 |
('/j', '/d'), (False, True), (False, True) |
| 532 |
): |
| 533 |
with self.subTest(mklink_option=mklink_option, |
| 534 |
recycle_container=recycle_container, |
| 535 |
break_before_recycle=break_before_recycle): |
| 536 |
self._test_broken_link_in_recycle_bin( |
| 537 |
mklink_option, recycle_container, break_before_recycle) |
| 538 |
for mklink_option, shred in itertools.product( |
| 539 |
('/j', '/d'), (False, True) |
| 540 |
): |
| 541 |
with self.subTest(mklink_option=mklink_option, shred=shred, |
| 542 |
outside_bin=True): |
| 543 |
self._test_broken_link_delete(mklink_option, shred) |
| 544 |
|
| 545 |
def test_delete_locked_file(self): |
| 546 |
"""Unit test for delete_locked_file""" |
| 547 |
tests = ('regular', 'unicode-emdash-u\u2014', 'long' + 'x' * 100) |
| 548 |
for test in tests: |
| 549 |
pathname = self.mkstemp(suffix=test) |
| 550 |
time.sleep(5) # avoid race condition |
| 551 |
self.assertExists(pathname) |
| 552 |
logger.debug('delete_locked_file(%s) ' % pathname) |
| 553 |
if not shell.IsUserAnAdmin(): |
| 554 |
with self.assertRaises(WindowsError): |
| 555 |
delete_locked_file(pathname) |
| 556 |
else: |
| 557 |
try: |
| 558 |
delete_locked_file(pathname) |
| 559 |
except WindowsError: |
| 560 |
logger.exception( |
| 561 |
'delete_locked_file() threw an error, which may be a false positive') |
| 562 |
self.assertExists(pathname) |
| 563 |
logger.info('reboot Windows and check the three files are deleted') |
| 564 |
|
| 565 |
def test_delete_parent_lock_needed(self): |
| 566 |
old_admin = Windows._delete_parent_lock_admin |
| 567 |
try: |
| 568 |
with mock.patch('bleachbit.Windows.shell.IsUserAnAdmin', return_value=False): |
| 569 |
Windows._delete_parent_lock_admin = None |
| 570 |
self.assertFalse(Windows._delete_parent_lock_needed( |
| 571 |
r'C:\Windows\Temp\bleachbit-test-file')) |
| 572 |
|
| 573 |
with mock.patch('bleachbit.Windows.shell.IsUserAnAdmin', return_value=True): |
| 574 |
Windows._delete_parent_lock_admin = None |
| 575 |
with mock.patch.dict(os.environ, {'USERPROFILE': r'C:\Users\bleachbit'}): |
| 576 |
self.assertFalse(Windows._delete_parent_lock_needed( |
| 577 |
r'C:\Users\bleachbit\AppData\Local\Temp\bleachbit-test-file')) |
| 578 |
self.assertTrue(Windows._delete_parent_lock_needed( |
| 579 |
r'C:\Windows\Temp\bleachbit-test-file')) |
| 580 |
finally: |
| 581 |
Windows._delete_parent_lock_admin = old_admin |
| 582 |
|
| 583 |
def test_delete_with_parent_lock_reuses_handle(self): |
| 584 |
Windows._delete_parent_lock_handle = None |
| 585 |
Windows._delete_parent_lock_key = None |
| 586 |
handle = mock.sentinel.handle |
| 587 |
delete_func = mock.Mock(return_value=mock.sentinel.deleted) |
| 588 |
with mock.patch('bleachbit.Windows._delete_parent_lock_needed', return_value=True), \ |
| 589 |
mock.patch('bleachbit.Windows._delete_parent_directory', return_value=r'\\?\C:\Windows\Temp'), \ |
| 590 |
mock.patch('bleachbit.Windows.win32file.CreateFile', return_value=handle) as create_file, \ |
| 591 |
mock.patch('bleachbit.Windows.win32file.GetFileAttributesW', return_value=0), \ |
| 592 |
mock.patch('bleachbit.Windows.win32file.CloseHandle') as close_handle: |
| 593 |
self.assertEqual(Windows.with_parent_lock( |
| 594 |
r'C:\Windows\Temp\one.tmp', delete_func, r'C:\Windows\Temp\one.tmp'), mock.sentinel.deleted) |
| 595 |
self.assertEqual(Windows.with_parent_lock( |
| 596 |
r'C:\Windows\Temp\two.tmp', delete_func, r'C:\Windows\Temp\two.tmp'), mock.sentinel.deleted) |
| 597 |
self.assertEqual(create_file.call_count, 1) |
| 598 |
self.assertEqual(delete_func.call_count, 2) |
| 599 |
Windows._close_delete_parent_lock() |
| 600 |
close_handle.assert_called_once_with(handle) |
| 601 |
|
| 602 |
def test_delete_with_parent_lock_closes_handle_on_delete_error(self): |
| 603 |
Windows._delete_parent_lock_handle = None |
| 604 |
Windows._delete_parent_lock_key = None |
| 605 |
handle = mock.sentinel.handle |
| 606 |
delete_func = mock.Mock(side_effect=RuntimeError('delete failed')) |
| 607 |
with mock.patch('bleachbit.Windows._delete_parent_lock_needed', return_value=True), \ |
| 608 |
mock.patch('bleachbit.Windows._delete_parent_directory', return_value=r'\\?\C:\Windows\Temp'), \ |
| 609 |
mock.patch('bleachbit.Windows.win32file.CreateFile', return_value=handle), \ |
| 610 |
mock.patch('bleachbit.Windows.win32file.GetFileAttributesW', return_value=0), \ |
| 611 |
mock.patch('bleachbit.Windows.win32file.CloseHandle') as close_handle: |
| 612 |
with self.assertRaises(RuntimeError): |
| 613 |
Windows.with_parent_lock( |
| 614 |
r'C:\Windows\Temp\one.tmp', delete_func, r'C:\Windows\Temp\one.tmp') |
| 615 |
close_handle.assert_called_once_with(handle) |
| 616 |
self.assertIsNone(Windows._delete_parent_lock_handle) |
| 617 |
|
| 618 |
def test_lock_delete_parent_rejects_reparse_point(self): |
| 619 |
Windows._delete_parent_lock_handle = None |
| 620 |
Windows._delete_parent_lock_key = None |
| 621 |
handle = mock.sentinel.handle |
| 622 |
with mock.patch('bleachbit.Windows._delete_parent_directory', return_value=r'\\?\C:\Windows\Temp'), \ |
| 623 |
mock.patch('bleachbit.Windows.win32file.CreateFile', return_value=handle), \ |
| 624 |
mock.patch('bleachbit.Windows.win32file.GetFileAttributesW', |
| 625 |
return_value=Windows.FILE_ATTRIBUTE_REPARSE_POINT), \ |
| 626 |
mock.patch('bleachbit.Windows.win32file.CloseHandle') as close_handle: |
| 627 |
with self.assertRaises(OSError): |
| 628 |
Windows._lock_delete_parent(r'C:\Windows\Temp\one.tmp') |
| 629 |
close_handle.assert_called_once_with(handle) |
| 630 |
self.assertIsNone(Windows._delete_parent_lock_handle) |
| 631 |
|
| 632 |
def test_delete_registry_key(self): |
| 633 |
"""Unit test for delete_registry_key""" |
| 634 |
# (return value, key, really_delete) |
| 635 |
tests = ((False, 'HKCU\\Software\\BleachBit\\DoesNotExist', False, ), |
| 636 |
(False, 'HKCU\\Software\\BleachBit\\DoesNotExist', True, ), |
| 637 |
(True, 'HKCU\\Software\\BleachBit\\DeleteThisKey', False, ), |
| 638 |
(True, 'HKCU\\Software\\BleachBit\\DeleteThisKey', True, ), ) |
| 639 |
|
| 640 |
# create a nested key |
| 641 |
key = 'Software\\BleachBit\\DeleteThisKey' |
| 642 |
subkey = key + '\\AndThisKey' |
| 643 |
hkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER, subkey) |
| 644 |
hkey.Close() |
| 645 |
|
| 646 |
# test |
| 647 |
for test in tests: |
| 648 |
rc = test[0] |
| 649 |
key = test[1] |
| 650 |
really_delete = test[2] |
| 651 |
return_value = delete_registry_key(key, really_delete) |
| 652 |
self.assertEqual(rc, return_value) |
| 653 |
if really_delete: |
| 654 |
self.assertFalse(detect_registry_key(key)) |
| 655 |
|
| 656 |
# Test Unicode key. In BleachBit 0.7.3 this scenario would lead to |
| 657 |
# the error (bug 537109) |
| 658 |
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position |
| 659 |
# 11: ordinal not in range(128) |
| 660 |
key = r'Software\\BleachBit\\DeleteThisKey' |
| 661 |
hkey = winreg.CreateKey( |
| 662 |
winreg.HKEY_CURRENT_USER, key + r'\\AndThisKey-Ö') |
| 663 |
hkey.Close() |
| 664 |
return_value = delete_registry_key('HKCU\\' + key, True) |
| 665 |
self.assertTrue(return_value) |
| 666 |
return_value = delete_registry_key('HKCU\\' + key, True) |
| 667 |
self.assertFalse(return_value) |
| 668 |
|
| 669 |
def test_delete_updates(self): |
| 670 |
"""Unit test for delete_updates |
| 671 |
|
| 672 |
As a preview, this does not modify services or delete files. |
| 673 |
""" |
| 674 |
if not shell.IsUserAnAdmin(): |
| 675 |
# It should return None without doing any work. |
| 676 |
for _ in delete_updates(): |
| 677 |
pass |
| 678 |
return |
| 679 |
|
| 680 |
counter = 0 |
| 681 |
for cmd in delete_updates(): |
| 682 |
counter += 1 |
| 683 |
self.assertIsInstance(cmd, (Delete, Function)) |
| 684 |
logger.debug('delete_updates() returned %s commands', f'{counter:,}') |
| 685 |
|
| 686 |
def test_is_service_running(self): |
| 687 |
"""Unit test for is_service_running()""" |
| 688 |
# RPC is always running. |
| 689 |
self.assertTrue(is_service_running('rpcss')) |
| 690 |
# Windows Update is sometimes running. |
| 691 |
self.assertIsInstance(is_service_running('wuauserv'), bool) |
| 692 |
# Non-existent service should raise an error. |
| 693 |
with self.assertRaises(pywintypes.error): |
| 694 |
is_service_running('does_not_exist') |
| 695 |
# None should raise an error. |
| 696 |
with self.assertRaises(AssertionError): |
| 697 |
is_service_running(None) |
| 698 |
|
| 699 |
def test_is_ots_elevation_without_flag_returns_false(self): |
| 700 |
"""Without --uac-sid-token, is_ots_elevation() returns False""" |
| 701 |
argv = ['bleachbit.exe', '--gui'] |
| 702 |
with mock.patch('bleachbit.Windows.sys.argv', argv): |
| 703 |
self.assertFalse(is_ots_elevation()) |
| 704 |
|
| 705 |
def test_is_ots_elevation_false_when_tokens_match(self): |
| 706 |
"""If current token matches parent token, there is no elevation""" |
| 707 |
parent_token = 'ABCDEFGH' |
| 708 |
argv = ['bleachbit.exe', '--gui', '--uac-sid-token', parent_token] |
| 709 |
with mock.patch('bleachbit.Windows.sys.argv', argv): |
| 710 |
with mock.patch('bleachbit.Windows.get_sid_token_48', return_value=parent_token): |
| 711 |
self.assertFalse(is_ots_elevation()) |
| 712 |
|
| 713 |
def test_is_ots_elevation_true_when_tokens_differ(self): |
| 714 |
"""If current token differs from parent token, elevation is detected""" |
| 715 |
parent_token = 'ABCDEFGH' |
| 716 |
argv = ['bleachbit.exe', '--gui', '--uac-sid-token', parent_token] |
| 717 |
with mock.patch('bleachbit.Windows.sys.argv', argv): |
| 718 |
with mock.patch('bleachbit.Windows.get_sid_token_48', return_value='DIFFERNT'): |
| 719 |
self.assertTrue(is_ots_elevation()) |
| 720 |
|
| 721 |
def test_is_ots_elevation_ignores_flag_without_value(self): |
| 722 |
"""A trailing --uac-sid-token without value should not crash and returns False""" |
| 723 |
argv = ['bleachbit.exe', '--gui', '--uac-sid-token'] |
| 724 |
with mock.patch('bleachbit.Windows.sys.argv', argv): |
| 725 |
self.assertFalse(is_ots_elevation()) |
| 726 |
|
| 727 |
def test_is_ots_elevation_returns_false_on_get_sid_error(self): |
| 728 |
"""If get_sid_token_48() raises, is_ots_elevation() falls back to False""" |
| 729 |
parent_token = 'ABCDEFGH' |
| 730 |
argv = ['bleachbit.exe', '--gui', '--uac-sid-token', parent_token] |
| 731 |
with mock.patch('bleachbit.Windows.sys.argv', argv): |
| 732 |
with mock.patch('bleachbit.Windows.get_sid_token_48', side_effect=RuntimeError('error')): |
| 733 |
self.assertFalse(is_ots_elevation()) |
| 734 |
|
| 735 |
def test_add_command_line_parameters_omits_duplicate_gui(self): |
| 736 |
"""UAC parameters already include --gui, so do not append it again.""" |
| 737 |
argv = ['bleachbit.exe', '--gui', '--exit'] |
| 738 |
with mock.patch('bleachbit.Windows.sys.argv', argv): |
| 739 |
self.assertEqual( |
| 740 |
'--gui --no-uac --exit', |
| 741 |
_add_command_line_parameters(['--gui', '--no-uac'])) |
| 742 |
|
| 743 |
def test_add_command_line_parameters_context_menu_omits_duplicate_gui(self): |
| 744 |
"""Context-menu UAC parameters keep the quoted path but skip --gui.""" |
| 745 |
file_to_shred = r'C:\Users\test user\AppData\Local\Temp\delete me.txt' |
| 746 |
argv = [ |
| 747 |
'bleachbit.exe', |
| 748 |
'--gui', |
| 749 |
'--no-delete-confirmation', |
| 750 |
'--context-menu', |
| 751 |
file_to_shred, |
| 752 |
] |
| 753 |
with mock.patch('bleachbit.Windows.sys.argv', argv): |
| 754 |
self.assertEqual( |
| 755 |
'--gui --no-uac --no-delete-confirmation --context-menu ' |
| 756 |
f'"{file_to_shred}"', |
| 757 |
_add_command_line_parameters(['--gui', '--no-uac'])) |
| 758 |
|
| 759 |
def test_elevate_privileges_omits_duplicate_gui(self): |
| 760 |
"""The elevated UAC command line should contain --gui only once.""" |
| 761 |
argv = ['bleachbit.exe', '--gui', '--exit'] |
| 762 |
with mock.patch('bleachbit.Windows.sys.argv', argv): |
| 763 |
with mock.patch('bleachbit.Windows.shell.IsUserAnAdmin', return_value=False): |
| 764 |
with mock.patch('bleachbit.Windows.path_on_network', return_value=False): |
| 765 |
with mock.patch('bleachbit.Windows.get_sid_token_48', return_value='ABCDEFGH'): |
| 766 |
with mock.patch( |
| 767 |
'bleachbit.Windows.shell.ShellExecuteEx', |
| 768 |
return_value={'hProcess': object()}) as shell_exec: |
| 769 |
self.assertTrue(elevate_privileges(True)) |
| 770 |
|
| 771 |
parameters = shell_exec.call_args.kwargs['lpParameters'] |
| 772 |
self.assertEqual(1, parameters.split().count('--gui')) |
| 773 |
self.assertIn('--exit', parameters) |
| 774 |
|
| 775 |
def test_splash_thread_reuses_cached_class_atom(self): |
| 776 |
"""_register_window_class skips RegisterClass when cached.""" |
| 777 |
splash = SplashThread() |
| 778 |
self.addCleanup(lambda: setattr(SplashThread, '_class_atom', None)) |
| 779 |
SplashThread._class_atom = 9876 |
| 780 |
with mock.patch('bleachbit.Windows.win32gui.RegisterClass') as mock_register: |
| 781 |
atom = splash._register_window_class(mock.Mock()) |
| 782 |
self.assertEqual(atom, 9876) |
| 783 |
mock_register.assert_not_called() |
| 784 |
|
| 785 |
def test_splash_thread_recovers_when_class_exists(self): |
| 786 |
"""_register_window_class handles ERROR_CLASS_ALREADY_EXISTS.""" |
| 787 |
splash = SplashThread() |
| 788 |
self.addCleanup(lambda: setattr(SplashThread, '_class_atom', None)) |
| 789 |
SplashThread._class_atom = None |
| 790 |
wnd_class = mock.Mock() |
| 791 |
wnd_class.hInstance = mock.sentinel.instance |
| 792 |
wnd_class.lpszClassName = 'SimpleWin32' |
| 793 |
register_error = pywintypes.error( |
| 794 |
1410, 'RegisterClass', 'Class already exists.') |
| 795 |
with mock.patch('bleachbit.Windows.win32gui.RegisterClass', side_effect=register_error) as mock_register, \ |
| 796 |
mock.patch('bleachbit.Windows.win32gui.GetClassInfo', return_value=(4321,)) as mock_get_class_info: |
| 797 |
atom = splash._register_window_class(wnd_class) |
| 798 |
self.assertEqual(atom, 4321) |
| 799 |
self.assertEqual(SplashThread._class_atom, 4321) |
| 800 |
mock_register.assert_called_once_with(wnd_class) |
| 801 |
mock_get_class_info.assert_called_once_with( |
| 802 |
wnd_class.hInstance, wnd_class.lpszClassName) |
| 803 |
|
| 804 |
def test_splash_thread_suppresses_startup_error(self): |
| 805 |
"""start() does not fail the GUI if splash initialization fails.""" |
| 806 |
splash = SplashThread() |
| 807 |
with mock.patch.object(splash, '_show_splash_screen', side_effect=RuntimeError('boom')): |
| 808 |
splash.start() |
| 809 |
self.assertIsNotNone(splash._startup_error) |
| 810 |
|
| 811 |
def test_splash_thread_join_handles_missing_window(self): |
| 812 |
"""join() succeeds even when window handle was never created.""" |
| 813 |
splash = SplashThread() |
| 814 |
splash._startup_error = RuntimeError('boom') |
| 815 |
splash._splash_screen_started.set() |
| 816 |
splash.start = lambda: None # prevent thread start |
| 817 |
# Directly call join; should not raise even though handle is None |
| 818 |
splash.join(timeout=0) |
| 819 |
|
| 820 |
def test_splash_thread_join_uses_send_message_timeout(self): |
| 821 |
"""join() closes the splash synchronously with a timeout.""" |
| 822 |
splash = SplashThread() |
| 823 |
splash._splash_screen_handle = 1234 |
| 824 |
with mock.patch.object(splash, 'is_alive', return_value=True), \ |
| 825 |
mock.patch.object(splash, '_hide_window') as mock_hide, \ |
| 826 |
mock.patch('bleachbit.Windows.win32gui.IsWindow', return_value=True), \ |
| 827 |
mock.patch( |
| 828 |
'bleachbit.Windows.ctypes.windll.user32.SendMessageTimeoutW', |
| 829 |
return_value=1) as mock_send, \ |
| 830 |
mock.patch('bleachbit.Windows.win32gui.PostMessage') as mock_post, \ |
| 831 |
mock.patch('bleachbit.Windows.Thread.join') as mock_thread_join: |
| 832 |
splash.join(timeout=0) |
| 833 |
|
| 834 |
mock_send.assert_called_once() |
| 835 |
mock_hide.assert_called_once_with(1234) |
| 836 |
mock_post.assert_not_called() |
| 837 |
mock_thread_join.assert_called_once_with(splash, timeout=0) |
| 838 |
|
| 839 |
def test_splash_thread_join_falls_back_after_send_failure(self): |
| 840 |
"""join() falls back to PostMessage if synchronous close fails.""" |
| 841 |
splash = SplashThread() |
| 842 |
splash._splash_screen_handle = 1234 |
| 843 |
with mock.patch.object(splash, 'is_alive', return_value=True), \ |
| 844 |
mock.patch.object(splash, '_hide_window'), \ |
| 845 |
mock.patch('bleachbit.Windows.win32gui.IsWindow', return_value=True), \ |
| 846 |
mock.patch( |
| 847 |
'bleachbit.Windows.ctypes.windll.user32.SendMessageTimeoutW', |
| 848 |
side_effect=RuntimeError('boom')), \ |
| 849 |
mock.patch('bleachbit.Windows.win32gui.PostMessage') as mock_post, \ |
| 850 |
mock.patch('bleachbit.Windows.Thread.join'): |
| 851 |
splash.join(timeout=0) |
| 852 |
|
| 853 |
mock_post.assert_called_once_with( |
| 854 |
1234, Windows.win32con.WM_CLOSE, 0, 0) |
| 855 |
|
| 856 |
def test_get_splash_screen_delay_seconds_default(self): |
| 857 |
with mock.patch.dict(os.environ, {}, clear=False): |
| 858 |
os.environ.pop('BLEACHBIT_SPLASH_SCREEN_DELAY', None) |
| 859 |
self.assertEqual(get_splash_screen_delay_seconds(), 0.0) |
| 860 |
|
| 861 |
def test_get_splash_screen_delay_seconds_valid(self): |
| 862 |
with mock.patch.dict(os.environ, {'BLEACHBIT_SPLASH_SCREEN_DELAY': '3.5'}, clear=False): |
| 863 |
self.assertEqual(get_splash_screen_delay_seconds(), 3.5) |
| 864 |
|
| 865 |
def test_get_splash_screen_delay_seconds_invalid(self): |
| 866 |
with mock.patch.dict(os.environ, {'BLEACHBIT_SPLASH_SCREEN_DELAY': 'abc'}, clear=False): |
| 867 |
self.assertEqual(get_splash_screen_delay_seconds(), 0.0) |
| 868 |
|
| 869 |
def test_get_splash_screen_delay_seconds_negative(self): |
| 870 |
with mock.patch.dict(os.environ, {'BLEACHBIT_SPLASH_SCREEN_DELAY': '-1'}, clear=False): |
| 871 |
self.assertEqual(get_splash_screen_delay_seconds(), 0.0) |
| 872 |
|
| 873 |
@common.skipUnlessDestructive |
| 874 |
def test_run_net_service_command(self): |
| 875 |
"""Integration test for run_net_service_command(). |
| 876 |
|
| 877 |
Actually stop/start Windows Update service. |
| 878 |
|
| 879 |
spooler (Print Spooler) is often on by default and has no dependencies. |
| 880 |
|
| 881 |
Windows Audio Endpoint Builder (AudioEndpointBuilder) is often on |
| 882 |
by default and depends on audiosrv (Windows Audio). |
| 883 |
|
| 884 |
Requires admin. |
| 885 |
""" |
| 886 |
if not shell.IsUserAnAdmin(): |
| 887 |
self.skipTest('requires administrator privileges') |
| 888 |
|
| 889 |
def _service_exists_and_enabled(svc): |
| 890 |
scm = win32service.OpenSCManager( |
| 891 |
None, None, win32service.SC_MANAGER_CONNECT) |
| 892 |
try: |
| 893 |
hs = win32service.OpenService( |
| 894 |
scm, svc, win32service.SERVICE_QUERY_STATUS | win32service.SERVICE_QUERY_CONFIG) |
| 895 |
try: |
| 896 |
cfg = win32service.QueryServiceConfig(hs) |
| 897 |
return True if cfg[1] != win32service.SERVICE_DISABLED else False |
| 898 |
finally: |
| 899 |
win32service.CloseServiceHandle(hs) |
| 900 |
except pywintypes.error: |
| 901 |
return False |
| 902 |
finally: |
| 903 |
win32service.CloseServiceHandle(scm) |
| 904 |
|
| 905 |
def _can_open_all_access(svc): |
| 906 |
scm = win32service.OpenSCManager( |
| 907 |
None, None, win32service.SC_MANAGER_CONNECT) |
| 908 |
try: |
| 909 |
try: |
| 910 |
hs = win32service.OpenService( |
| 911 |
scm, svc, win32service.SERVICE_ALL_ACCESS) |
| 912 |
except pywintypes.error: |
| 913 |
return False |
| 914 |
else: |
| 915 |
win32service.CloseServiceHandle(hs) |
| 916 |
return True |
| 917 |
finally: |
| 918 |
win32service.CloseServiceHandle(scm) |
| 919 |
|
| 920 |
is_ci = 'GITHUB_ACTIONS' in os.environ |
| 921 |
if is_ci: |
| 922 |
candidates = ('bits', 'wuauserv', |
| 923 |
'AudioEndpointBuilder', 'spooler') |
| 924 |
service = None |
| 925 |
# Prefer already-running to avoid state changes |
| 926 |
for s in candidates: |
| 927 |
if _service_exists_and_enabled(s) and _can_open_all_access(s) and is_service_running(s): |
| 928 |
service = s |
| 929 |
break |
| 930 |
# If none are running, pick any we can open with required access |
| 931 |
if not service: |
| 932 |
for s in candidates: |
| 933 |
if _service_exists_and_enabled(s) and _can_open_all_access(s): |
| 934 |
service = s |
| 935 |
break |
| 936 |
else: |
| 937 |
candidates = ('AudioEndpointBuilder', |
| 938 |
'spooler', 'bits', 'wuauserv') |
| 939 |
service = None |
| 940 |
for s in candidates: |
| 941 |
if _service_exists_and_enabled(s): |
| 942 |
service = s |
| 943 |
break |
| 944 |
if not service: |
| 945 |
self.skipTest('no suitable startable service on this machine') |
| 946 |
|
| 947 |
initial_running = is_service_running(service) |
| 948 |
|
| 949 |
try: |
| 950 |
if is_ci: |
| 951 |
ret = run_net_service_command(service, True) |
| 952 |
self.assertEqual(ret, 0) |
| 953 |
ret = run_net_service_command(service, True) |
| 954 |
self.assertEqual(ret, 0) |
| 955 |
else: |
| 956 |
ret = run_net_service_command(service, False) |
| 957 |
self.assertEqual(ret, 0) |
| 958 |
self.assertFalse(is_service_running(service)) |
| 959 |
if service == 'AudioEndpointBuilder': |
| 960 |
self.assertFalse(is_service_running('audiosrv')) |
| 961 |
ret = run_net_service_command(service, False) |
| 962 |
self.assertEqual(ret, 0) |
| 963 |
self.assertFalse(is_service_running(service)) |
| 964 |
ret = run_net_service_command(service, True) |
| 965 |
self.assertEqual(ret, 0) |
| 966 |
self.assertTrue(is_service_running(service)) |
| 967 |
ret = run_net_service_command(service, True) |
| 968 |
self.assertEqual(ret, 0) |
| 969 |
self.assertTrue(is_service_running(service)) |
| 970 |
finally: |
| 971 |
if not is_ci: |
| 972 |
run_net_service_command(service, initial_running) |
| 973 |
self.assertEqual(initial_running, is_service_running(service)) |
| 974 |
|
| 975 |
def test_run_net_service_command_not_admin(self): |
| 976 |
"""Test as run_net_service_command() as not admin user""" |
| 977 |
if shell.IsUserAnAdmin(): |
| 978 |
self.skipTest('requires non-admin user') |
| 979 |
service = 'wuauserv' |
| 980 |
initial_running = is_service_running(service) |
| 981 |
for start in (True, False): |
| 982 |
with self.assertRaises(RuntimeError): |
| 983 |
run_net_service_command(service, start) |
| 984 |
self.assertEqual(is_service_running(service), initial_running) |
| 985 |
|
| 986 |
def test_run_net_service_command_invalid_service(self): |
| 987 |
"""Test as run_net_service_command() with invalid service""" |
| 988 |
for service in ('does_not_exist', None): |
| 989 |
for start in (True, False): |
| 990 |
with self.subTest(service=service, start=start): |
| 991 |
with self.assertRaises((AssertionError, RuntimeError)): |
| 992 |
run_net_service_command(service, start) |
| 993 |
|
| 994 |
def test_delete_registry_value(self): |
| 995 |
"""Unit test for delete_registry_value""" |
| 996 |
|
| 997 |
# |
| 998 |
# test: value does exist |
| 999 |
# |
| 1000 |
|
| 1001 |
# create a name-value pair |
| 1002 |
key = 'Software\\BleachBit' |
| 1003 |
hkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER, key) |
| 1004 |
|
| 1005 |
value_name = 'delete_this_value_name' |
| 1006 |
winreg.SetValueEx( |
| 1007 |
hkey, value_name, 0, winreg.REG_SZ, 'delete this value') |
| 1008 |
hkey.Close() |
| 1009 |
|
| 1010 |
# delete and confirm |
| 1011 |
self.assertTrue( |
| 1012 |
delete_registry_value('HKCU\\' + key, value_name, False)) |
| 1013 |
self.assertTrue( |
| 1014 |
delete_registry_value('HKCU\\' + key, value_name, True)) |
| 1015 |
self.assertFalse( |
| 1016 |
delete_registry_value('HKCU\\' + key, value_name, False)) |
| 1017 |
self.assertFalse( |
| 1018 |
delete_registry_value('HKCU\\' + key, value_name, True)) |
| 1019 |
|
| 1020 |
# |
| 1021 |
# test: value does not exist |
| 1022 |
# |
| 1023 |
self.assertFalse(delete_registry_value( |
| 1024 |
'HKCU\\' + key, 'doesnotexist', False)) |
| 1025 |
self.assertFalse(delete_registry_value( |
| 1026 |
'HKCU\\' + key, 'doesnotexist', True)) |
| 1027 |
self.assertFalse(delete_registry_value( |
| 1028 |
'HKCU\\doesnotexist', value_name, False)) |
| 1029 |
self.assertFalse(delete_registry_value( |
| 1030 |
'HKCU\\doesnotexist', value_name, True)) |
| 1031 |
|
| 1032 |
def test_detect_registry_key(self): |
| 1033 |
"""Test for detect_registry_key()""" |
| 1034 |
self.assertTrue(detect_registry_key('HKCU\\Software\\Microsoft\\')) |
| 1035 |
self.assertTrue(not detect_registry_key( |
| 1036 |
'HKCU\\Software\\DoesNotExist')) |
| 1037 |
|
| 1038 |
@pytest.mark.xdist_group('gui') |
| 1039 |
def test_get_clipboard_paths(self): |
| 1040 |
"""Unit test for get_clipboard_paths""" |
| 1041 |
# The clipboard is an unknown state, so check the function does |
| 1042 |
# not crash and that it returns the right data type. |
| 1043 |
paths = get_clipboard_paths() |
| 1044 |
self.assertIsInstance(paths, (type(None), tuple)) |
| 1045 |
|
| 1046 |
# Set the clipboard to an unsupported type (text), so expect no |
| 1047 |
# files are returned |
| 1048 |
import win32clipboard |
| 1049 |
win32clipboard.OpenClipboard() |
| 1050 |
win32clipboard.EmptyClipboard() |
| 1051 |
fname = r'c:\windows\notepad.exe' |
| 1052 |
win32clipboard.SetClipboardText(fname, win32clipboard.CF_TEXT) |
| 1053 |
win32clipboard.SetClipboardText(fname, win32clipboard.CF_UNICODETEXT) |
| 1054 |
self.assertEqual(win32clipboard.GetClipboardData( |
| 1055 |
win32clipboard.CF_TEXT), fname.encode('ascii')) |
| 1056 |
self.assertEqual(win32clipboard.GetClipboardData( |
| 1057 |
win32clipboard.CF_UNICODETEXT), fname) |
| 1058 |
win32clipboard.CloseClipboard() |
| 1059 |
|
| 1060 |
paths = get_clipboard_paths() |
| 1061 |
self.assertIsInstance(paths, (type(None), tuple)) |
| 1062 |
self.assertEqual(paths, ()) |
| 1063 |
|
| 1064 |
# Put files in the clipboard in supported format |
| 1065 |
args = ('powershell.exe', 'Set-Clipboard', |
| 1066 |
'-Path', r'c:\windows\*.exe') |
| 1067 |
(ext_rc, _stdout, _stderr) = General.run_external(args) |
| 1068 |
# It may print "Requested Clipboard operation did not succeed" to stderr. |
| 1069 |
self.assertEqual( |
| 1070 |
ext_rc, 0, f"powershell.exe failed with return code {ext_rc}: {_stderr}") |
| 1071 |
paths = get_clipboard_paths() |
| 1072 |
self.assertIsInstance(paths, (type(None), tuple)) |
| 1073 |
self.assertGreater(len(paths), 1) |
| 1074 |
for path in paths: |
| 1075 |
self.assertExists(path) |
| 1076 |
|
| 1077 |
def test_get_font_conf_file(self): |
| 1078 |
"""Unit test for get_font_conf_file""" |
| 1079 |
# This tests only one of three situations. |
| 1080 |
from bleachbit.GtkShim import gtk_may_be_available |
| 1081 |
if not gtk_may_be_available(): |
| 1082 |
self.skipTest("GTK is not available") |
| 1083 |
font_fn = get_font_conf_file() |
| 1084 |
self.assertExists(font_fn) |
| 1085 |
|
| 1086 |
def test_has_fontconfig_cache(self): |
| 1087 |
"""Unit test for has_fontconfig_cache()""" |
| 1088 |
font_conf = self.write_file( |
| 1089 |
'fonts.conf', |
| 1090 |
text='<?xml version="1.0"?>\n' |
| 1091 |
'<fontconfig>\n' |
| 1092 |
' <cachedir>~/.fontconfig</cachedir>\n' |
| 1093 |
'</fontconfig>\n') |
| 1094 |
self.assertFalse(has_fontconfig_cache(font_conf)) |
| 1095 |
|
| 1096 |
def test_has_fontconfig_cache_rejects_dtd(self): |
| 1097 |
"""A fonts.conf with a DTD is rejected (entity-expansion defense)""" |
| 1098 |
font_conf = self.write_file( |
| 1099 |
'fonts_dtd.conf', |
| 1100 |
text='<?xml version="1.0"?>\n' |
| 1101 |
'<!DOCTYPE fontconfig [ <!ENTITY x "y"> ]>\n' |
| 1102 |
'<fontconfig><cachedir>~/.fontconfig</cachedir></fontconfig>\n') |
| 1103 |
self.assertRaises(ValueError, has_fontconfig_cache, font_conf) |
| 1104 |
|
| 1105 |
def test_has_fontconfig_cache_allows_external_doctype(self): |
| 1106 |
"""A real fonts.conf, which declares an external-only DOCTYPE, must not be rejected""" |
| 1107 |
font_conf = self.write_file( |
| 1108 |
'fonts_external_dtd.conf', |
| 1109 |
text='<?xml version="1.0"?>\n' |
| 1110 |
'<!DOCTYPE fontconfig SYSTEM "fonts.dtd">\n' |
| 1111 |
'<fontconfig><cachedir>~/.fontconfig</cachedir></fontconfig>\n') |
| 1112 |
self.assertFalse(has_fontconfig_cache(font_conf)) |
| 1113 |
|
| 1114 |
def test_get_known_folder_path(self): |
| 1115 |
"""Unit test for get_known_folder_path""" |
| 1116 |
ret = get_known_folder_path('LocalAppDataLow') |
| 1117 |
self.assertNotEqual(ret, '') |
| 1118 |
self.assertNotEqual(ret, None) |
| 1119 |
self.assertExists(ret) |
| 1120 |
|
| 1121 |
def test_get_fixed_drives(self): |
| 1122 |
"""Unit test for get_fixed_drives""" |
| 1123 |
drives = [] |
| 1124 |
for drive in get_fixed_drives(): |
| 1125 |
drives.append(drive) |
| 1126 |
self.assertEqual(drive, drive.upper()) |
| 1127 |
self.assertIn("C:\\", drives) |
| 1128 |
|
| 1129 |
def test_get_sid_token_48_basic_properties(self): |
| 1130 |
"""get_sid_token_48() returns an 8-char, URL-safe ASCII string""" |
| 1131 |
token = get_sid_token_48() |
| 1132 |
self.assertIsString(token) |
| 1133 |
# 6 bytes (48 bits) become 8 base64-url characters without padding |
| 1134 |
self.assertEqual(len(token), 8) |
| 1135 |
for ch in token: |
| 1136 |
self.assertLess(ord(ch), 128) |
| 1137 |
# urlsafe_b64encode must not use '+', '/', or '=' |
| 1138 |
self.assertNotIn('+', token) |
| 1139 |
self.assertNotIn('/', token) |
| 1140 |
self.assertNotIn('=', token) |
| 1141 |
|
| 1142 |
def test_get_sid_token_48_is_deterministic_for_current_process(self): |
| 1143 |
"""Multiple calls for the same process should yield the same token""" |
| 1144 |
t1 = get_sid_token_48() |
| 1145 |
t2 = get_sid_token_48() |
| 1146 |
self.assertEqual(t1, t2) |
| 1147 |
|
| 1148 |
def test_get_windows_version(self): |
| 1149 |
"""Unit test for get_windows_version""" |
| 1150 |
v = get_windows_version() |
| 1151 |
self.assertGreaterEqual(v, 5.1) |
| 1152 |
self.assertGreater(v, 5) |
| 1153 |
self.assertIsInstance(v, Decimal) |
| 1154 |
|
| 1155 |
@pytest.mark.xdist_group('recycle-bin') |
| 1156 |
def test_empty_recycle_bin(self): |
| 1157 |
"""Unit test for empty_recycle_bin""" |
| 1158 |
# check the function basically works |
| 1159 |
for drive in get_fixed_drives(): |
| 1160 |
ret = empty_recycle_bin(drive, really_delete=False) |
| 1161 |
self.assertIsInteger(ret) |
| 1162 |
|
| 1163 |
@pytest.mark.no_xdist |
| 1164 |
@pytest.mark.xdist_group('recycle-bin') |
| 1165 |
@common.skipUnlessDestructive |
| 1166 |
def test_empty_recycle_bin_per_drive_destructive(self): |
| 1167 |
"""Empty recycle bin in each drive individually""" |
| 1168 |
put_objects_into_recycle_bin() |
| 1169 |
for drive in get_fixed_drives(): |
| 1170 |
with self.subTest(drive=drive): |
| 1171 |
try: |
| 1172 |
ret = empty_recycle_bin(drive, really_delete=True) |
| 1173 |
except pywintypes.com_error as e: |
| 1174 |
if e.args[0] == -2147024893 and 'GITHUB_ACTIONS' in os.environ: |
| 1175 |
self.skipTest( |
| 1176 |
'reproducible only in CI and does not ' |
| 1177 |
'test a scenario used outside the tests') |
| 1178 |
raise |
| 1179 |
self.assertIsInteger(ret) |
| 1180 |
|
| 1181 |
@pytest.mark.no_xdist |
| 1182 |
@pytest.mark.xdist_group('recycle-bin') |
| 1183 |
@common.skipUnlessDestructive |
| 1184 |
def test_empty_recycle_bin_all_drives_destructive(self): |
| 1185 |
"""Empty recycle bin in all drives at once""" |
| 1186 |
put_objects_into_recycle_bin() |
| 1187 |
ret = empty_recycle_bin(None, really_delete=True) |
| 1188 |
self.assertIsInteger(ret) |
| 1189 |
|
| 1190 |
# Verify that there are no objects in the bin. |
| 1191 |
for _f in get_recycle_bin(): |
| 1192 |
self.fail('recycle bin should be empty, but it is not') |
| 1193 |
|
| 1194 |
# Repeat the call to empty for two reasons. |
| 1195 |
# 1. Trying to empty an empty recycling bin can cause |
| 1196 |
# a 'catastrophic failure' error (handled in the function) |
| 1197 |
# 2. It should show zero bytes were deleted |
| 1198 |
for drive in get_fixed_drives(): |
| 1199 |
ret = empty_recycle_bin(drive, really_delete=True) |
| 1200 |
self.assertEqual(ret, 0) |
| 1201 |
|
| 1202 |
def test_file_wipe(self): |
| 1203 |
"""Unit test for file_wipe |
| 1204 |
|
| 1205 |
There are more tests in testwipe.py |
| 1206 |
""" |
| 1207 |
|
| 1208 |
from bleachbit.WindowsWipe import file_wipe, open_file, close_file, file_make_sparse |
| 1209 |
from bleachbit.Windows import elevate_privileges |
| 1210 |
from win32con import GENERIC_WRITE, WRITE_DAC |
| 1211 |
|
| 1212 |
dirname = self.mkdtemp() |
| 1213 |
|
| 1214 |
filenames = ('short', 'long' + 'x' * 250, 'utf8-ɡælɪk') |
| 1215 |
for filename in filenames: |
| 1216 |
longname = os.path.join(dirname, filename) |
| 1217 |
logger.debug('file_wipe(%s)', longname) |
| 1218 |
|
| 1219 |
def _write_file(longname, contents): |
| 1220 |
self.write_file(longname, contents) |
| 1221 |
import win32api |
| 1222 |
shortname = extended_path_undo( |
| 1223 |
win32api.GetShortPathName(extended_path(longname))) |
| 1224 |
self.assertExists(shortname) |
| 1225 |
return shortname |
| 1226 |
|
| 1227 |
def _deny_access(fh): |
| 1228 |
import win32security |
| 1229 |
import ntsecuritycon as con |
| 1230 |
|
| 1231 |
user, _, _ = win32security.LookupAccountName( |
| 1232 |
"", win32api.GetUserName()) |
| 1233 |
dacl = win32security.ACL() |
| 1234 |
dacl.AddAccessDeniedAce( |
| 1235 |
win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, user) |
| 1236 |
win32security.SetSecurityInfo(fh, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION, |
| 1237 |
None, None, dacl, None) |
| 1238 |
|
| 1239 |
def _test_wipe(contents, deny_access=False, is_sparse=False): |
| 1240 |
shortname = _write_file(longname, contents) |
| 1241 |
if deny_access or is_sparse: |
| 1242 |
fh = open_file(extended_path(longname), |
| 1243 |
mode=GENERIC_WRITE | WRITE_DAC) |
| 1244 |
if is_sparse: |
| 1245 |
file_make_sparse(fh) |
| 1246 |
if deny_access: |
| 1247 |
_deny_access(fh) |
| 1248 |
close_file(fh) |
| 1249 |
logger.debug('test_file_wipe(): filename length={}, shortname length ={}, contents length={}, is_sparse={}'.format( |
| 1250 |
len(longname), len(shortname), len(contents), is_sparse)) |
| 1251 |
if shell.IsUserAnAdmin(): |
| 1252 |
# wiping requires admin privileges |
| 1253 |
file_wipe(shortname) |
| 1254 |
file_wipe(longname) |
| 1255 |
else: |
| 1256 |
with self.assertRaises(pywintypes.error): |
| 1257 |
file_wipe(shortname) |
| 1258 |
file_wipe(longname) |
| 1259 |
self.assertExists(shortname) |
| 1260 |
os.remove(extended_path(shortname)) |
| 1261 |
self.assertNotExists(shortname) |
| 1262 |
|
| 1263 |
# A small file that fits in MFT |
| 1264 |
_test_wipe(b'') |
| 1265 |
|
| 1266 |
# requires wiping of extents |
| 1267 |
_test_wipe(b'secret' * 100000) |
| 1268 |
|
| 1269 |
# requires wiping of extents: special file case |
| 1270 |
elevate_privileges(False) |
| 1271 |
_test_wipe(b'secret' * 100000, deny_access=True, is_sparse=True) |
| 1272 |
|
| 1273 |
shutil.rmtree(dirname, True) |
| 1274 |
|
| 1275 |
if shell.IsUserAnAdmin(): |
| 1276 |
logger.warning( |
| 1277 |
'You should also run test_file_wipe() without admin privileges.') |
| 1278 |
else: |
| 1279 |
logger.warning( |
| 1280 |
'You should also run test_file_wipe() with admin privileges.') |
| 1281 |
|
| 1282 |
def test_setup_environment(self): |
| 1283 |
"""Unit test for setup_environment""" |
| 1284 |
setup_environment() |
| 1285 |
envs = ['commonappdata', 'documents', 'music', 'pictures', 'video', |
| 1286 |
'localappdata', 'localappdatalow'] |
| 1287 |
for env in envs: |
| 1288 |
self.assertExists(os.environ[env]) |
| 1289 |
|
| 1290 |
def test_split_registry_key(self): |
| 1291 |
"""Unit test for split_registry_key""" |
| 1292 |
tests = (('HKCU\\Software', winreg.HKEY_CURRENT_USER, 'Software'), |
| 1293 |
('HKLM\\SOFTWARE', winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE'), |
| 1294 |
('HKU\\.DEFAULT', winreg.HKEY_USERS, '.DEFAULT')) |
| 1295 |
for (input_key, expected_hive, expected_key) in tests: |
| 1296 |
(hive, key) = split_registry_key(input_key) |
| 1297 |
self.assertEqual(expected_hive, hive) |
| 1298 |
self.assertEqual(expected_key, key) |
| 1299 |
|
| 1300 |
def test_read_registry_key(self): |
| 1301 |
"""Unit test for read_registry_key""" |
| 1302 |
tests = (('HKCR\\.bmp', 'PerceivedType', 'image'), |
| 1303 |
('HKCU\\Software\\BleachBit\\DoesNotExist', 'DoesNotExist', None)) |
| 1304 |
for (input_key, input_value, expected_value) in tests: |
| 1305 |
value = read_registry_key(input_key, input_value) |
| 1306 |
if value is not None: |
| 1307 |
value = value.lower() # casing varies by Windows version: image vs Image |
| 1308 |
self.assertEqual(expected_value, value) |
| 1309 |
|
| 1310 |
def test_parse_windows_build(self): |
| 1311 |
"""Unit test for parse_windows_build""" |
| 1312 |
tests = (('5.1.2600', Decimal('5.1')), |
| 1313 |
('5.1', Decimal('5.1')), |
| 1314 |
('10.0.10240', 10), |
| 1315 |
('10.0', 10)) |
| 1316 |
for test in tests: |
| 1317 |
self.assertEqual(parse_windows_build(test[0]), test[1]) |
| 1318 |
|
| 1319 |
# test for crash |
| 1320 |
parse_windows_build() |
| 1321 |
parse_windows_build(platform.version()) |
| 1322 |
parse_windows_build(platform.uname()[3]) |
| 1323 |
|
| 1324 |
def test_path_on_network(self): |
| 1325 |
"""Unit test for path_on_network""" |
| 1326 |
self.assertFalse(path_on_network('c:\\bleachbit.exe')) |
| 1327 |
self.assertFalse(path_on_network('a:\\bleachbit.exe')) |
| 1328 |
self.assertTrue(path_on_network('\\\\Server\\Folder\\bleachbit.exe')) |
| 1329 |
|
| 1330 |
def test_shell_change_notify(self): |
| 1331 |
"""Unit test for shell_change_notify""" |
| 1332 |
ret = shell_change_notify() |
| 1333 |
self.assertEqual(ret, 0) |
| 1334 |
|
| 1335 |
def test_splash_screen(self): |
| 1336 |
"""Unit test for splash screen""" |
| 1337 |
splash_thread = SplashThread() |
| 1338 |
icon_path = splash_thread.get_icon_path() |
| 1339 |
self.assertTrue(icon_path.is_absolute()) |
| 1340 |
self.assertExists(icon_path) |
| 1341 |
splash_thread.start() |
| 1342 |
timeout = 5.0 # seconds |
| 1343 |
start_time = time.time() |
| 1344 |
time.sleep(1) |
| 1345 |
while not splash_thread.is_alive() and (time.time() - start_time) < timeout: |
| 1346 |
time.sleep(0.1) |
| 1347 |
self.assertTrue(splash_thread.is_alive(), |
| 1348 |
'Splash thread did not start within timeout') |
| 1349 |
splash_thread.join() |
| 1350 |
|
| 1351 |
# Originally, running twice in same process caused indefinite hang, |
| 1352 |
# so run it twice. |
| 1353 |
repeat = SplashThread() |
| 1354 |
repeat.start() |
| 1355 |
repeat.join() |
| 1356 |
|
| 1357 |
def test_splash_screen_window_pos(self): |
| 1358 |
"""Unit test for calculate_window_position()""" |
| 1359 |
splash_thread = SplashThread() |
| 1360 |
|
| 1361 |
# Test with a typical 1080p display |
| 1362 |
display_width = 1920 |
| 1363 |
display_height = 1080 |
| 1364 |
x, y, width, height = splash_thread.calculate_window_position( |
| 1365 |
display_width, display_height) |
| 1366 |
|
| 1367 |
# The window should have positive dimensions |
| 1368 |
self.assertGreater(width, 0) |
| 1369 |
self.assertGreater(height, 0) |
| 1370 |
|
| 1371 |
# The window position should be positive (on screen) |
| 1372 |
self.assertGreaterEqual(x, 0) |
| 1373 |
self.assertGreaterEqual(y, 0) |
| 1374 |
|
| 1375 |
# The window should fit within the display |
| 1376 |
self.assertLessEqual(x + width, display_width) |
| 1377 |
self.assertLessEqual(y + height, display_height) |
| 1378 |
|
| 1379 |
# The window should be roughly centered |
| 1380 |
# x should be approximately (display_width - width) / 2 |
| 1381 |
expected_x = (display_width - width) // 2 |
| 1382 |
self.assertEqual(x, expected_x) |
| 1383 |
# y should be approximately (display_height - height) / 2 |
| 1384 |
expected_y = (display_height - height) // 2 |
| 1385 |
self.assertEqual(y, expected_y) |
| 1386 |
|
| 1387 |
# Splash screen is the square logo. |
| 1388 |
self.assertEqual(width, 256) |
| 1389 |
self.assertEqual(height, 256) |
| 1390 |
|
| 1391 |
def test_set_environ(self): |
| 1392 |
for folder in ['folderäö', 'folder']: |
| 1393 |
test_dir = os.path.join(self.tempdir, folder) |
| 1394 |
os.mkdir(test_dir) |
| 1395 |
self.assertExists(test_dir) |
| 1396 |
set_environ('cd_test', test_dir) |
| 1397 |
self.assertEqual(os.environ['cd_test'], test_dir) |
| 1398 |
os.environ.pop('cd_test') |
| 1399 |
|
| 1400 |
@staticmethod |
| 1401 |
def _parse_windows_command_line(cmd): |
| 1402 |
"""Parse a command line the same way Windows does (CommandLineToArgvW).""" |
| 1403 |
fn = ctypes.windll.shell32.CommandLineToArgvW |
| 1404 |
fn.argtypes = [ctypes.c_wchar_p, ctypes.POINTER(ctypes.c_int)] |
| 1405 |
fn.restype = ctypes.POINTER(ctypes.c_wchar_p) |
| 1406 |
argc = ctypes.c_int() |
| 1407 |
argv_p = fn(cmd, ctypes.byref(argc)) |
| 1408 |
try: |
| 1409 |
return [argv_p[i] for i in range(argc.value)] |
| 1410 |
finally: |
| 1411 |
ctypes.windll.kernel32.LocalFree(argv_p) |
| 1412 |
|
| 1413 |
def _assert_roundtrips(self, base, extra_argv): |
| 1414 |
"""cmd has no exe name, so prepend one before parsing it back.""" |
| 1415 |
with mock.patch('bleachbit.Windows.sys.argv', ['bleachbit.exe'] + extra_argv): |
| 1416 |
cmd = _add_command_line_parameters(base) |
| 1417 |
argv = self._parse_windows_command_line(f'"dummy.exe" {cmd}') |
| 1418 |
self.assertEqual(argv[1:], base + extra_argv) |
| 1419 |
|
| 1420 |
def test_add_command_line_parameters_quoting(self): |
| 1421 |
"""Args must round-trip unchanged through the Windows argv parser.""" |
| 1422 |
base = [r'C:\Program Files\BleachBit\bleachbit.py', '--gui', '--no-uac'] |
| 1423 |
|
| 1424 |
# simple argument |
| 1425 |
self._assert_roundtrips(base, ['--debug-log']) |
| 1426 |
|
| 1427 |
# argument with spaces |
| 1428 |
self._assert_roundtrips(base, ['--debug-log', r'C:\temp\my log.txt']) |
| 1429 |
|
| 1430 |
# embedded quotes and ampersands attempting to break out of the argument |
| 1431 |
malicious = r'C:\test" & calc.exe & "' |
| 1432 |
self._assert_roundtrips(base, ['--context-menu', malicious]) |
| 1433 |
|
| 1434 |
# embedded quote attempting to inject a whole extra argument |
| 1435 |
injection = 'foo" --no-uac "bar' |
| 1436 |
self._assert_roundtrips(base, ['--context-menu', injection]) |
| 1437 |
|
| 1438 |
# multiple arguments, one with spaces, in a realistic combination |
| 1439 |
self._assert_roundtrips( |
| 1440 |
base, ['--context-menu', r'C:\path with spaces\file.txt', '--debug-log']) |