| 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 Unix |
| 9 |
""" |
| 10 |
|
| 11 |
from unittest import mock |
| 12 |
import os |
| 13 |
import random |
| 14 |
import re |
| 15 |
import subprocess |
| 16 |
import tempfile |
| 17 |
import unittest |
| 18 |
from xml.dom.minidom import parseString |
| 19 |
|
| 20 |
from tests import common |
| 21 |
from bleachbit import General, logger |
| 22 |
from bleachbit.FileUtilities import children_in_directory, exe_exists, getsize |
| 23 |
from bleachbit.VFS import ListVFS |
| 24 |
from bleachbit.Unix import ( |
| 25 |
_is_broken_xdg_desktop_application, |
| 26 |
apt_autoclean, |
| 27 |
apt_autoremove, |
| 28 |
clear_snapd_cache, |
| 29 |
dnf_autoremove, |
| 30 |
dnf_clean, |
| 31 |
parse_dnf_freed_space, |
| 32 |
find_available_locales, |
| 33 |
find_best_locale, |
| 34 |
get_apt_size, |
| 35 |
get_distribution_name_version_distro, |
| 36 |
get_distribution_name_version_os_release, |
| 37 |
get_distribution_name_version_platform_freedesktop, |
| 38 |
get_distribution_name_version, |
| 39 |
get_globs_size, |
| 40 |
get_purgeable_locales, |
| 41 |
get_trash_paths, |
| 42 |
is_broken_xdg_desktop, |
| 43 |
is_unix_display_protocol_wayland, |
| 44 |
journald_clean, |
| 45 |
JOURNALD_REGEX, |
| 46 |
LocaleCleanerPath, |
| 47 |
Locales, |
| 48 |
pacman_cache, |
| 49 |
root_is_not_allowed_to_X_session, |
| 50 |
snapd_is_active, |
| 51 |
snap_disabled_clean, |
| 52 |
snap_disabled_preview, |
| 53 |
snap_parse_list, |
| 54 |
rotated_logs, |
| 55 |
run_cleaner_cmd, |
| 56 |
wine_to_linux_path, |
| 57 |
yum_clean, |
| 58 |
) |
| 59 |
|
| 60 |
|
| 61 |
class FakeConfig: |
| 62 |
def __init__(self, options): |
| 63 |
self.options = options |
| 64 |
|
| 65 |
def has_option(self, section, option): |
| 66 |
return section in self.options and option in self.options[section] |
| 67 |
|
| 68 |
def get(self, section, option): |
| 69 |
return self.options[section][option] |
| 70 |
|
| 71 |
|
| 72 |
class UnixTestCase(common.BleachbitTestCase): |
| 73 |
|
| 74 |
"""Test case for module Unix""" |
| 75 |
|
| 76 |
def setUp(self): |
| 77 |
"""Initialize unit tests""" |
| 78 |
self.locales = Locales() |
| 79 |
clear_snapd_cache() |
| 80 |
super().setUp() |
| 81 |
|
| 82 |
@common.skipIfWindows |
| 83 |
def test_apt(self): |
| 84 |
"""Unit test for method apt_autoclean() and apt_autoremove()""" |
| 85 |
if 0 != os.geteuid() or not exe_exists(General.resolve_exe('apt-get')): |
| 86 |
self.assertRaises(RuntimeError, apt_autoclean) |
| 87 |
self.assertRaises(RuntimeError, apt_autoremove) |
| 88 |
else: |
| 89 |
bytes_freed = apt_autoclean() |
| 90 |
self.assertIsInteger(bytes_freed) |
| 91 |
logger.debug('apt bytes cleaned %d', bytes_freed) |
| 92 |
bytes_freed = apt_autoremove() |
| 93 |
self.assertIsInteger(bytes_freed) |
| 94 |
logger.debug('apt bytes cleaned %d', bytes_freed) |
| 95 |
|
| 96 |
def test_apt_autoclean_mock(self): |
| 97 |
"""Unit test for apt_autoclean() parsing of 'Del' lines""" |
| 98 |
# apt >= 3.2 (Ubuntu 26.04) prints a space between the size and units |
| 99 |
output = '\n'.join(( |
| 100 |
'Del libcurl3t64-gnutls 8.18.0-1ubuntu2.2 [417 kB]', |
| 101 |
'Del libcurl4t64 8.18.0-1ubuntu2.2 [426 kB]', |
| 102 |
'Del curl 8.18.0-1ubuntu2.2 [272 kB]', |
| 103 |
)) |
| 104 |
with mock.patch('bleachbit.Unix.FileUtilities.exe_exists', return_value=True), \ |
| 105 |
mock.patch('bleachbit.Unix.subprocess.check_output', return_value=output): |
| 106 |
self.assertEqual(apt_autoclean(), 417000 + 426000 + 272000) |
| 107 |
|
| 108 |
# older apt printed the size without a space |
| 109 |
output = 'Del curl 8.18.0-1ubuntu2.2 [272kB]' |
| 110 |
with mock.patch('bleachbit.Unix.FileUtilities.exe_exists', return_value=True), \ |
| 111 |
mock.patch('bleachbit.Unix.subprocess.check_output', return_value=output): |
| 112 |
self.assertEqual(apt_autoclean(), 272000) |
| 113 |
|
| 114 |
@common.skipIfWindows |
| 115 |
def test_find_available_locales(self): |
| 116 |
"""Unit test for method find_available_locales()""" |
| 117 |
locales = find_available_locales() |
| 118 |
self.assertIsInstance(locales, list) |
| 119 |
for locale in locales: |
| 120 |
self.assertIsLanguageCode(locale) |
| 121 |
|
| 122 |
def test_find_available_locales_mock(self): |
| 123 |
"""Unit test for method find_available_locales() with mock""" |
| 124 |
mock_locales = ['C', 'C.utf8', 'en_US.utf8', |
| 125 |
'es_MX', 'es_MX.iso88591', 'es_MX.utf8', 'POSIX'] |
| 126 |
with mock.patch('bleachbit.Unix.General.run_external') as mock_run_external: |
| 127 |
mock_run_external.return_value = ( |
| 128 |
0, "\n".join(mock_locales) + "\n", "") |
| 129 |
locales = find_available_locales() |
| 130 |
self.assertEqual(locales, mock_locales) |
| 131 |
mock_run_external.assert_called_once_with( |
| 132 |
[General.resolve_exe('locale'), '-a']) |
| 133 |
|
| 134 |
@mock.patch('locale.getlocale') |
| 135 |
@mock.patch('bleachbit.Unix.find_available_locales') |
| 136 |
def test_find_best_locale(self, mock_find_available_locales, mock_getlocale): |
| 137 |
"""Unit test for method find_best_locale()""" |
| 138 |
mock_find_available_locales.return_value = [ |
| 139 |
'C', |
| 140 |
'C.utf8', |
| 141 |
'de_DE.utf8', |
| 142 |
'en_US.iso88591', |
| 143 |
'en_US.utf8', |
| 144 |
'es_MX', |
| 145 |
'es_MX.iso88591', |
| 146 |
'es_MX.utf8', |
| 147 |
'nds_DE.utf8', |
| 148 |
'POSIX', |
| 149 |
] |
| 150 |
mock_getlocale.return_value = ('en_US', 'UTF-8') |
| 151 |
for locale in ('en', 'en_US', 'en_US.utf8'): |
| 152 |
self.assertEqual(find_best_locale(locale), 'en_US.UTF-8') |
| 153 |
|
| 154 |
mock_find_available_locales.assert_called() |
| 155 |
mock_getlocale.assert_called() |
| 156 |
|
| 157 |
for locale in ('de', 'de_DE', 'de_DE.utf8'): |
| 158 |
self.assertEqual(find_best_locale(locale), 'de_DE.utf8') |
| 159 |
|
| 160 |
# Test language with a three-letter code. |
| 161 |
for locale in ('nds', 'nds_DE', 'nds_DE.utf8'): |
| 162 |
self.assertEqual(find_best_locale(locale), 'nds_DE.utf8') |
| 163 |
|
| 164 |
# Reverse the list. |
| 165 |
mock_find_available_locales.return_value = mock_find_available_locales.return_value[ |
| 166 |
::-1] |
| 167 |
for locale in ('en', 'en_US', 'en_US.utf8'): |
| 168 |
self.assertEqual(find_best_locale(locale), 'en_US.UTF-8') |
| 169 |
|
| 170 |
# ISO-8859-1 is less preferred than UTF-8 |
| 171 |
mock_find_available_locales.return_value.remove('en_US.utf8') |
| 172 |
mock_getlocale.return_value = ('es_MX', 'UTF-8') |
| 173 |
for locale in ('en', 'en_US'): |
| 174 |
self.assertEqual(find_best_locale(locale), 'en_US.iso88591') |
| 175 |
|
| 176 |
mock_getlocale.return_value = ('es_MX', 'UTF-8') |
| 177 |
mock_find_available_locales.return_value = ['C', 'C.utf8', 'en_US.utf8', |
| 178 |
'es_MX.iso88591', 'es_MX.utf8', 'POSIX'] |
| 179 |
for locale in ('es', 'es_MX', 'es_MX.utf8'): |
| 180 |
self.assertEqual(find_best_locale(locale), 'es_MX.UTF-8') |
| 181 |
|
| 182 |
self.assertEqual(find_best_locale('C'), 'C') |
| 183 |
self.assertEqual(find_best_locale(''), 'C') |
| 184 |
self.assertEqual(find_best_locale('POSIX'), 'POSIX') |
| 185 |
|
| 186 |
self.assertRaises(AssertionError, find_best_locale, None) |
| 187 |
self.assertRaises(AssertionError, find_best_locale, []) |
| 188 |
|
| 189 |
@mock.patch('locale.getlocale') |
| 190 |
@mock.patch('bleachbit.Unix.find_available_locales') |
| 191 |
def test_find_best_locale_macos_uppercase_utf8( |
| 192 |
self, mock_find_available_locales, mock_getlocale): |
| 193 |
"""macOS's locale -a uses '.UTF-8' (uppercase, hyphenated), |
| 194 |
unlike the lowercase '.utf8' used elsewhere in this test file. |
| 195 |
The UTF-8 variant must still be preferred over a non-UTF-8 one |
| 196 |
regardless of that formatting difference.""" |
| 197 |
mock_getlocale.return_value = ('fr_FR', 'UTF-8') |
| 198 |
mock_find_available_locales.return_value = [ |
| 199 |
'en_NZ.ISO8859-1', |
| 200 |
'en_US.UTF-8', |
| 201 |
] |
| 202 |
self.assertEqual(find_best_locale('en'), 'en_US.UTF-8') |
| 203 |
|
| 204 |
@unittest.skipUnless(exe_exists(General.resolve_exe('apt-get')), |
| 205 |
'skipping tests for unavailable apt-get') |
| 206 |
def test_get_apt_size(self): |
| 207 |
"""Unit test for method get_apt_size()""" |
| 208 |
size = get_apt_size() |
| 209 |
self.assertIsInteger(size) |
| 210 |
self.assertGreaterEqual(size, 0) |
| 211 |
|
| 212 |
def test_get_globs_size_vanished(self): |
| 213 |
"""get_globs_size() skips a file that vanishes between glob and getsize""" |
| 214 |
real_fn = self.write_file('globs-size-real', contents=b'0123456789') |
| 215 |
expected = getsize(real_fn) |
| 216 |
self.assertGreater(expected, 0) |
| 217 |
pattern = os.path.join(self.tempdir, 'globs-size-*') |
| 218 |
self.assertEqual(expected, get_globs_size([pattern])) |
| 219 |
|
| 220 |
# A file listed by the glob but gone by the time it is measured |
| 221 |
ghost_fn = os.path.join(self.tempdir, 'globs-size-ghost') |
| 222 |
with mock.patch('bleachbit.Unix.glob.iglob', |
| 223 |
return_value=iter([real_fn, ghost_fn])): |
| 224 |
self.assertEqual(expected, get_globs_size([pattern])) |
| 225 |
|
| 226 |
# Other errors must still propagate |
| 227 |
with mock.patch('bleachbit.Unix.FileUtilities.getsize', |
| 228 |
side_effect=PermissionError('denied')): |
| 229 |
with self.assertRaises(PermissionError): |
| 230 |
get_globs_size([pattern]) |
| 231 |
|
| 232 |
@common.skipIfWindows |
| 233 |
def test_get_distribution_name_version(self): |
| 234 |
"""Unit test for method get_distribution_name_version()""" |
| 235 |
ret_real = get_distribution_name_version() |
| 236 |
ret_platform_freedesktop = get_distribution_name_version_platform_freedesktop() |
| 237 |
ret_distro = get_distribution_name_version_distro() |
| 238 |
ret_os_release = get_distribution_name_version_os_release() |
| 239 |
|
| 240 |
for ret in (ret_real, ret_platform_freedesktop, ret_distro, ret_os_release): |
| 241 |
if ret is None: |
| 242 |
continue |
| 243 |
self.assertIsInstance(ret, str) |
| 244 |
self.assertGreater(len(ret), 0) |
| 245 |
self.assertLess(len(ret), 100) |
| 246 |
self.assertIn(' ', ret) |
| 247 |
if ret_platform_freedesktop and ret_os_release: |
| 248 |
self.assertEqual(ret_platform_freedesktop, ret_os_release) |
| 249 |
if ret_distro and ret_os_release: |
| 250 |
self.assertEqual(ret_distro, ret_os_release) |
| 251 |
|
| 252 |
self.assertIsNotNone(ret_real) |
| 253 |
|
| 254 |
@common.skipIfWindows |
| 255 |
def test_is_broken_xdg_desktop_real(self): |
| 256 |
"""Unit test for is_broken_xdg_desktop() |
| 257 |
|
| 258 |
Check it does not crash on real-world .desktop files. |
| 259 |
""" |
| 260 |
menu_dirs = ['/usr/share/applications', |
| 261 |
'~/.local/share/applications', |
| 262 |
'~/snap/steam/common/.local/share/applications', |
| 263 |
'/usr/share/autostart', |
| 264 |
'/usr/share/gnome/autostart', |
| 265 |
'/usr/share/gnome/apps', |
| 266 |
'/usr/share/mimelnk', |
| 267 |
'/usr/share/applnk-redhat/', |
| 268 |
'/usr/local/share/applications/', |
| 269 |
'/usr/share/ubuntu-wayland/'] |
| 270 |
for dirname in menu_dirs: |
| 271 |
for filename in [fn for fn in children_in_directory(os.path.expanduser(dirname), False) |
| 272 |
if fn.endswith('.desktop') |
| 273 |
]: |
| 274 |
self.assertIsInstance(is_broken_xdg_desktop(filename), bool) |
| 275 |
|
| 276 |
@common.skipIfWindows |
| 277 |
@mock.patch('bleachbit.Unix.logger.info') |
| 278 |
def test_is_broken_xdg_desktop_other(self, mock_logger): |
| 279 |
"""Unit test for is_broken_xdg_desktop() using non-.desktop files""" |
| 280 |
# Recursing /usr/bin and /usr/lib was slow (100k+ files, each getting |
| 281 |
# children_in_directory's symlink checks). A flat /etc listing is enough. |
| 282 |
etc_dir = '/etc' |
| 283 |
filenames = [os.path.join(etc_dir, name) for name in os.listdir(etc_dir) |
| 284 |
if not name.endswith('.desktop') |
| 285 |
and os.path.isfile(os.path.join(etc_dir, name))] |
| 286 |
sample_size = min(30, len(filenames)) |
| 287 |
sampled_filenames = random.sample(filenames, sample_size) |
| 288 |
for filename in sampled_filenames: |
| 289 |
result = is_broken_xdg_desktop(filename) |
| 290 |
self.assertTrue( |
| 291 |
result, msg=f"Expected is_broken_xdg_desktop({filename}) to return True, but got {result}") |
| 292 |
mock_logger.assert_called() |
| 293 |
mock_logger.reset_mock() |
| 294 |
|
| 295 |
def test_is_broken_xdg_desktop_wine(self): |
| 296 |
"""Unit test for certain Wine .desktop file |
| 297 |
|
| 298 |
https://github.com/bleachbit/bleachbit/issues/1756 |
| 299 |
""" |
| 300 |
if not os.getenv('PATH'): |
| 301 |
self.skipTest("PATH environment variable is not set") |
| 302 |
with tempfile.NamedTemporaryFile(mode='w', suffix='.desktop', prefix='bleachbit-xdg-') as tmp: |
| 303 |
tmp.write("""[Desktop Entry] |
| 304 |
Name=What's New |
| 305 |
Exec=env WINEPREFIX="/home/bem/.wine" wine C:\\\\windows\\\\command\\\\start.exe /Unix /home/bem/.wine/dosdevices/c:/users/Public/Start\\ Menu/Programs/Biet-O-Matic/What\\'s\\ New.lnk |
| 306 |
Type=Application |
| 307 |
StartupNotify=true |
| 308 |
Path=/home/bem/.wine/dosdevices/c:/Program Files (x86)/Biet-O-Matic |
| 309 |
Icon=6B19_WhatsNew.0""") |
| 310 |
tmp.flush() |
| 311 |
self.assertIsInstance(is_broken_xdg_desktop(tmp.name), bool) |
| 312 |
|
| 313 |
@mock.patch('bleachbit.FileUtilities.exe_exists') |
| 314 |
@common.skipIfWindows |
| 315 |
def test_is_broken_xdg_desktop_chrome(self, mock_exe_exists): |
| 316 |
"""Unit test for certain Chrome .desktop file |
| 317 |
|
| 318 |
https://github.com/bleachbit/bleachbit/issues/1729 |
| 319 |
""" |
| 320 |
mock_exe_exists.return_value = True |
| 321 |
with tempfile.NamedTemporaryFile(mode='w', suffix='.desktop', prefix='bleachbit-xdg-') as tmp: |
| 322 |
tmp.write("""#!/usr/bin/env xdg-open |
| 323 |
[Desktop Entry] |
| 324 |
Version=1.0 |
| 325 |
Terminal=false |
| 326 |
Type=Application |
| 327 |
Name=Google News |
| 328 |
Exec=/opt/google/chrome/google-chrome --profile-directory=Default --app-id=abcdefghijklmnopqrstuvwxy |
| 329 |
Icon=chrome-abcdefghijklmnopqrstuvwxy-Default |
| 330 |
StartupWMClass=crx_abcdefghijklmnopqrstuvwxy""") |
| 331 |
tmp.flush() |
| 332 |
self.assertFalse(is_broken_xdg_desktop(tmp.name)) |
| 333 |
|
| 334 |
@common.skipIfWindows |
| 335 |
def test_is_broken_xdg_desktop_chatgpt(self): |
| 336 |
"""Unit test for certain ChatGPT .desktop file |
| 337 |
|
| 338 |
Linux Mint made this file for a Web App. |
| 339 |
|
| 340 |
I changed Exec from vivaldi-stale to test without mock. |
| 341 |
|
| 342 |
https://github.com/bleachbit/bleachbit/issues/1729 |
| 343 |
""" |
| 344 |
with tempfile.NamedTemporaryFile(mode='w', suffix='.desktop', prefix='bleachbit-xdg-') as tmp: |
| 345 |
tmp.write("""[Desktop Entry] |
| 346 |
Version=1.0 |
| 347 |
Name=ChatGPT |
| 348 |
Comment=Web App |
| 349 |
Exec=ls --app="https://chatgpt.com/" --class=WebApp-ChatGPT3878 --name=WebApp-ChatGPT3878 |
| 350 |
Terminal=false |
| 351 |
X-MultipleArgs=false |
| 352 |
Type=Application |
| 353 |
Icon=/home/username/.local/share/icons/icons8-chatgpt-150.svg |
| 354 |
Categories=GTK;Network; |
| 355 |
MimeType=text/html;text/xml;application/xhtml_xml; |
| 356 |
StartupWMClass=chatgpt.com |
| 357 |
StartupNotify=true |
| 358 |
X-WebApp-Browser=Vivaldi |
| 359 |
X-WebApp-URL=https://chatgpt.com |
| 360 |
X-WebApp-CustomParameters= |
| 361 |
X-WebApp-Navbar=false |
| 362 |
X-WebApp-PrivateWindow=false |
| 363 |
X-WebApp-Isolated=false |
| 364 |
Keywords=deepseek,chatgpt,gpt,gemini,ai |
| 365 |
Hidden=false |
| 366 |
NoDisplay=false |
| 367 |
PrefersNonDefaultGPU=false""") |
| 368 |
tmp.flush() |
| 369 |
self.assertFalse(is_broken_xdg_desktop(tmp.name)) |
| 370 |
|
| 371 |
@common.skipIfWindows |
| 372 |
def test_get_trash_paths(self): |
| 373 |
"""Unit test for get_trash_paths()""" |
| 374 |
seen = [] |
| 375 |
for p in get_trash_paths(): |
| 376 |
seen.append(p) |
| 377 |
self.assertExists(p.path) |
| 378 |
self.assertEqual(len(seen), len( |
| 379 |
set(p.path for p in seen)), "Duplicate trash paths found") |
| 380 |
|
| 381 |
@common.skipIfWindows |
| 382 |
def test_get_trash_paths_includes_now_empty_folder(self): |
| 383 |
"""Regression test: a folder sent to the macOS Trash must be |
| 384 |
yielded for deletion itself, not just the files inside it. |
| 385 |
|
| 386 |
get_trash_paths() previously called |
| 387 |
children_in_directory(dirname, False), where the second argument |
| 388 |
is list_directories, not 'recursive' as an earlier comment |
| 389 |
claimed. With False, only files are yielded and a folder emptied |
| 390 |
by this same cleaning pass is left behind forever, empty, in |
| 391 |
~/.Trash. |
| 392 |
""" |
| 393 |
trash_dir = self.mkdtemp(prefix='bleachbit-test-trash') |
| 394 |
sub_dir = os.path.join(trash_dir, 'folder-in-trash') |
| 395 |
os.mkdir(sub_dir) |
| 396 |
file_path = os.path.join(sub_dir, 'file.txt') |
| 397 |
self.write_file(file_path) |
| 398 |
|
| 399 |
real_expanduser = os.path.expanduser |
| 400 |
|
| 401 |
def fake_expanduser(p): |
| 402 |
if p == '~/.Trash': |
| 403 |
return trash_dir |
| 404 |
return real_expanduser(p) |
| 405 |
|
| 406 |
with mock.patch('os.path.expanduser', side_effect=fake_expanduser): |
| 407 |
paths = [p.path for p in get_trash_paths()] |
| 408 |
|
| 409 |
self.assertIn(file_path, paths) |
| 410 |
self.assertIn( |
| 411 |
sub_dir, paths, |
| 412 |
'the emptied folder itself must also be yielded for deletion') |
| 413 |
|
| 414 |
@common.skipIfWindows |
| 415 |
def test_desktop_valid_exe(self): |
| 416 |
"""Unit test for .desktop file with valid Unix exe (not env)""" |
| 417 |
fake_config = FakeConfig({"Desktop Entry": {"Exec": "ls"}}) |
| 418 |
if os.getenv('PATH'): |
| 419 |
result = _is_broken_xdg_desktop_application( |
| 420 |
fake_config, "foo.desktop") |
| 421 |
self.assertFalse(result) |
| 422 |
else: |
| 423 |
with self.assertRaises(RuntimeError): |
| 424 |
_is_broken_xdg_desktop_application(fake_config, "foo.desktop") |
| 425 |
|
| 426 |
def test_desktop_shlex_failure(self): |
| 427 |
"""Unit test for .desktop file with shlex exception |
| 428 |
|
| 429 |
Malformed Exec values (unbalanced quotes) are undefined behavior per |
| 430 |
the XDG spec. The function returns False so the file is preserved |
| 431 |
rather than risking deletion of a working launcher. |
| 432 |
""" |
| 433 |
fake_config = FakeConfig( |
| 434 |
{"Desktop Entry": {"Exec": "env ENVVAR=bar ls \"notepad.exe"}}) |
| 435 |
result = _is_broken_xdg_desktop_application( |
| 436 |
fake_config, "foo.desktop") |
| 437 |
self.assertFalse(result) |
| 438 |
|
| 439 |
@mock.patch('bleachbit.FileUtilities.exe_exists') |
| 440 |
def test_desktop_quoted_exe_with_spaces(self, mock_exe_exists): |
| 441 |
"""Regression test for #2118: AppImage .desktop with quoted Exec path |
| 442 |
|
| 443 |
Before the fix, the naive ``split(" ")[0]`` returned the executable |
| 444 |
path with its surrounding double-quotes still attached, so |
| 445 |
``exe_exists`` reported it missing and the .desktop file was flagged |
| 446 |
for deletion. |
| 447 |
""" |
| 448 |
mock_exe_exists.return_value = True |
| 449 |
fake_config = FakeConfig({"Desktop Entry": { |
| 450 |
"Exec": '"/home/user/Applications/AppManager" %u'}}) |
| 451 |
result = _is_broken_xdg_desktop_application( |
| 452 |
fake_config, "com.github.AppManager.desktop") |
| 453 |
self.assertFalse(result) |
| 454 |
mock_exe_exists.assert_called_with( |
| 455 |
'/home/user/Applications/AppManager') |
| 456 |
|
| 457 |
@mock.patch('bleachbit.FileUtilities.exe_exists') |
| 458 |
def test_desktop_quoted_exe_path_containing_spaces(self, mock_exe_exists): |
| 459 |
"""Quoted Exec path that itself contains spaces must round-trip.""" |
| 460 |
mock_exe_exists.return_value = True |
| 461 |
fake_config = FakeConfig({"Desktop Entry": { |
| 462 |
"Exec": '"/home/user/Applications/Converter NOW" %f'}}) |
| 463 |
result = _is_broken_xdg_desktop_application( |
| 464 |
fake_config, "converter.desktop") |
| 465 |
self.assertFalse(result) |
| 466 |
mock_exe_exists.assert_called_with( |
| 467 |
'/home/user/Applications/Converter NOW') |
| 468 |
|
| 469 |
def test_desktop_empty_exec(self): |
| 470 |
"""Whitespace-only Exec is treated as broken.""" |
| 471 |
fake_config = FakeConfig({"Desktop Entry": {"Exec": " "}}) |
| 472 |
result = _is_broken_xdg_desktop_application( |
| 473 |
fake_config, "foo.desktop") |
| 474 |
self.assertTrue(result) |
| 475 |
|
| 476 |
@common.skipIfWindows |
| 477 |
def test_desktop_env_valid(self): |
| 478 |
"""Unit test for .desktop file with valid env Exec""" |
| 479 |
fake_config = FakeConfig( |
| 480 |
{"Desktop Entry": {"Exec": "env FOO=bar ls /usr/bin"}}) |
| 481 |
result = _is_broken_xdg_desktop_application(fake_config, "foo.desktop") |
| 482 |
self.assertFalse(result) |
| 483 |
|
| 484 |
@mock.patch('bleachbit.FileUtilities.exe_exists') |
| 485 |
def test_desktop_missing_wine(self, mock_exe_exists): |
| 486 |
"""Unit test for .desktop file without Wine installed""" |
| 487 |
mock_exe_exists.side_effect = [ |
| 488 |
True, False] # First True for 'env', then False for 'wine' |
| 489 |
fake_config = FakeConfig( |
| 490 |
{"Desktop Entry": {"Exec": "env WINEPREFIX=/some/path wine notepad.exe"}}) |
| 491 |
result = _is_broken_xdg_desktop_application(fake_config, "foo.desktop") |
| 492 |
self.assertTrue(result) |
| 493 |
mock_exe_exists.assert_has_calls([mock.call('env'), mock.call('wine')]) |
| 494 |
|
| 495 |
@mock.patch('os.path.exists') |
| 496 |
@mock.patch('bleachbit.FileUtilities.exe_exists') |
| 497 |
def test_desktop_wine_valid_windows_exe(self, mock_exe_exists, mock_path_exists): |
| 498 |
"""Unit test for .desktop file pointing to valid Windows application""" |
| 499 |
fake_config = FakeConfig({"Desktop Entry": { |
| 500 |
"Exec": r"/usr/bin/env WINEPREFIX=/some/path wine C:\\Windows\\notepad.exe"}}) |
| 501 |
mock_exe_exists.return_value = True # for env and wine |
| 502 |
mock_path_exists.return_value = True # for notepad |
| 503 |
result = _is_broken_xdg_desktop_application(fake_config, "foo.desktop") |
| 504 |
self.assertFalse(result) |
| 505 |
|
| 506 |
@mock.patch('os.path.exists') |
| 507 |
@mock.patch('bleachbit.FileUtilities.exe_exists') |
| 508 |
def test_desktop_env_missing_windows_exe(self, mock_exe_exists, mock_path_exists): |
| 509 |
"""Unit test for .desktop file with env pointing to missing Windows application""" |
| 510 |
fake_config = FakeConfig({"Desktop Entry": { |
| 511 |
"Exec": "env WINEPREFIX=/some/path wine_exe does_not_exist.exe"}}) |
| 512 |
mock_exe_exists.return_value = True # for env and wine |
| 513 |
mock_path_exists.return_value = False # for does_not_exist.exe |
| 514 |
result = _is_broken_xdg_desktop_application(fake_config, "foo.desktop") |
| 515 |
self.assertTrue(result) |
| 516 |
|
| 517 |
def test_desktop_missing_keys(self): |
| 518 |
"""Unit test for .desktop file missing keys""" |
| 519 |
|
| 520 |
test_cases = [ |
| 521 |
("", "Blank file"), |
| 522 |
("[Desktop Entry]\n", "missing Type and Name"), |
| 523 |
("[Desktop Entry]\nType=Application\n", "missing Name key"), |
| 524 |
("[Desktop Entry]\nName=Test\n", "missing Type key"), |
| 525 |
("[Desktop Entry]\nType=Link\nName=Test\n", |
| 526 |
"Type=Link and missing URL key"), |
| 527 |
("[Desktop Entry]\nType=Application\nName=Test", |
| 528 |
"Type=Application and missing Exec"), |
| 529 |
("garbage", "Not a .desktop file"), |
| 530 |
("#/bin/bash\necho hello world", "Bash script") |
| 531 |
] |
| 532 |
|
| 533 |
for content, description in test_cases: |
| 534 |
with tempfile.NamedTemporaryFile(mode='w+', delete=False) as tf: |
| 535 |
tf.write(content) |
| 536 |
tf.flush() |
| 537 |
result = is_broken_xdg_desktop(tf.name) |
| 538 |
self.assertTrue(result, f"Failed case: {description}") |
| 539 |
os.unlink(tf.name) |
| 540 |
|
| 541 |
@common.skipIfWindows |
| 542 |
def test_journald_clean(self): |
| 543 |
if not exe_exists(General.resolve_exe('journalctl')): |
| 544 |
self.assertRaises(RuntimeError, journald_clean) |
| 545 |
else: |
| 546 |
try: |
| 547 |
journald_clean() |
| 548 |
except RuntimeError as rte: |
| 549 |
# On my system as a regular user, this succeeds. |
| 550 |
# On Travis running Trusty, this worked. |
| 551 |
# On Travis running Xenial, there is a permissions error. |
| 552 |
if common.have_root(): |
| 553 |
raise rte |
| 554 |
|
| 555 |
def test_journald_regex(self): |
| 556 |
"""Test the regex for journald_clean()""" |
| 557 |
positive_cases = ('Vacuuming done, freed 0B of archived journals on disk.', |
| 558 |
'Vacuuming done, freed 1K of archived journals on disk.', |
| 559 |
'Vacuuming done, freed 100.0M of archived journals on disk.', |
| 560 |
'Vacuuming done, freed 1G of archived journals on disk.', |
| 561 |
'Vacuuming done, freed 0B of archived journals from /run/log/journal.', |
| 562 |
'Vacuuming done, freed 1.0G of archived journals from /var/log/journal/123abc.') |
| 563 |
regex = re.compile(JOURNALD_REGEX) |
| 564 |
for pos in positive_cases: |
| 565 |
self.assertTrue(regex.match(pos)) |
| 566 |
negative_cases = ('Deleted archived journal /var/log/journal/123/[email protected]~ (56.0M).', |
| 567 |
'Archived and active journals take up 100.0M on disk.') |
| 568 |
for neg in negative_cases: |
| 569 |
self.assertFalse(regex.match(neg)) |
| 570 |
|
| 571 |
def test_get_purgeable_locales(self): |
| 572 |
"""Unit test for method get_purgeable_locales()""" |
| 573 |
# 'en' implies 'en_US' |
| 574 |
locales_to_keep = ['en', 'en_AU', 'en_CA', 'en_GB'] |
| 575 |
purgeable_locales = get_purgeable_locales(locales_to_keep) |
| 576 |
self.assertIsInstance(purgeable_locales, frozenset) |
| 577 |
self.assertIn('es', purgeable_locales) |
| 578 |
self.assertIn('pt', purgeable_locales) |
| 579 |
self.assertIn('de', purgeable_locales) |
| 580 |
for keep in locales_to_keep + ['en_US']: |
| 581 |
self.assertNotIn(keep, purgeable_locales) |
| 582 |
|
| 583 |
# 'en_US' keeps 'en' but discards 'en_AU'. |
| 584 |
purgeable_locales = get_purgeable_locales(['en_US']) |
| 585 |
self.assertNotIn('en', purgeable_locales) |
| 586 |
self.assertNotIn('en_US', purgeable_locales) |
| 587 |
self.assertIn('en_AU', purgeable_locales) |
| 588 |
|
| 589 |
def test_locale_regex(self): |
| 590 |
"""Unit test for locale_to_language()""" |
| 591 |
tests = {'en': 'en', |
| 592 |
'en_US': 'en', |
| 593 |
'en_US@piglatin': 'en', |
| 594 |
'en_US.utf8': 'en', |
| 595 |
'ko_KR.eucKR': 'ko', |
| 596 |
'pl.ISO8859-2': 'pl', |
| 597 |
'zh_TW.Big5': 'zh'} |
| 598 |
regex = re.compile('^' + Locales.localepattern + '$') |
| 599 |
for locale, tlc in tests.items(): |
| 600 |
m = regex.match(locale) |
| 601 |
self.assertIsNotNone(m, 'expected positive match for ' + locale) |
| 602 |
self.assertEqual(m.group("locale"), tlc) |
| 603 |
for test in ['default', 'C', 'English', 'ru_RU.txt', 'ru.txt']: |
| 604 |
self.assertIsNone(regex.match( |
| 605 |
test), 'expected negative match for ' + test) |
| 606 |
|
| 607 |
@common.skipIfWindows |
| 608 |
def test_localization_paths(self): |
| 609 |
"""Unit test for localization_paths()""" |
| 610 |
configpath = parseString( |
| 611 |
'<path location="/usr/share/locale/" filter="*" />').firstChild |
| 612 |
self.locales.add_xml(configpath) |
| 613 |
counter = 0 |
| 614 |
for path in self.locales.localization_paths(['en', 'en_AU', 'en_CA', 'en_GB']): |
| 615 |
self.assertLExists(path) |
| 616 |
self.assertTrue(path.startswith('/usr/share/locale')) |
| 617 |
# /usr/share/locale/en_* should be ignored |
| 618 |
self.assertEqual(path.find('/en_'), -1, 'expected path ' + path + |
| 619 |
' to not contain /en_') |
| 620 |
counter += 1 |
| 621 |
self.assertGreater(counter, 0, 'Zero files deleted by localization cleaner. ' + |
| 622 |
'This may be an error unless you really deleted all the files.') |
| 623 |
|
| 624 |
@common.skipIfWindows |
| 625 |
def test_fakelocalizationdirs(self): |
| 626 |
"""Create a faked localization hierarchy and clean it afterwards""" |
| 627 |
|
| 628 |
keepdirs = [ |
| 629 |
'important_dontdelete', |
| 630 |
'important_dontdelete/ru', |
| 631 |
'delete', |
| 632 |
'delete/locale', |
| 633 |
'delete/locale/en', |
| 634 |
'delete/dummyfiles', |
| 635 |
'foobar', |
| 636 |
'foobar/locale'] |
| 637 |
nukedirs = [ |
| 638 |
'delete/locale/ru', |
| 639 |
'foobar/locale/ru'] |
| 640 |
keepfiles = [ |
| 641 |
'delete/dummyfiles/dontdeleteme_ru.txt', |
| 642 |
'important_dontdelete/exceptthisone_ru.txt', |
| 643 |
'delete/dummyfiles/en.txt', |
| 644 |
'delete/dummyfiles/ru.dic'] |
| 645 |
nukefiles = [ |
| 646 |
'delete/dummyfiles/ru.txt', |
| 647 |
'delete/locale/ru_RU.UTF8.txt'] |
| 648 |
for path in keepdirs + nukedirs: |
| 649 |
os.mkdir(os.path.join(self.tempdir, path)) |
| 650 |
for path in keepfiles + nukefiles: |
| 651 |
self.write_file(path) |
| 652 |
|
| 653 |
configxml = '<path directoryregex="^.*$">' \ |
| 654 |
' <path directoryregex="^(locale|dummyfiles)$">' \ |
| 655 |
' <path location="." filter="*" />' \ |
| 656 |
r' <regexfilter postfix="\.txt" />' \ |
| 657 |
' </path>' \ |
| 658 |
'</path>' |
| 659 |
config = parseString(configxml) |
| 660 |
self.locales._paths = LocaleCleanerPath(self.tempdir) |
| 661 |
self.locales.add_xml(config.firstChild, None) |
| 662 |
# normpath because paths may contain ./ |
| 663 |
deletelist = [os.path.normpath( |
| 664 |
path) for path in self.locales.localization_paths(['en', 'de'])] |
| 665 |
for path in keepdirs + keepfiles: |
| 666 |
self.assertNotIn(os.path.join(self.tempdir, path), deletelist) |
| 667 |
for path in nukedirs + nukefiles: |
| 668 |
self.assertIn(os.path.join(self.tempdir, path), deletelist) |
| 669 |
|
| 670 |
@common.skipIfWindows |
| 671 |
def test_rotated_logs_real(self): |
| 672 |
"""Unit test for rotated_logs()""" |
| 673 |
for path in rotated_logs(): |
| 674 |
self.assertLExists( |
| 675 |
path, f"Rotated log path '{path}' does not exist") |
| 676 |
|
| 677 |
@mock.patch('os.access') |
| 678 |
@mock.patch('os.path.isdir') |
| 679 |
@mock.patch('bleachbit.FileUtilities.whitelisted') |
| 680 |
@mock.patch('bleachbit.FileUtilities.children_in_directory') |
| 681 |
def test_rotated_logs_mock(self, mock_cid, mock_whitelisted, mock_isdir, mock_access): |
| 682 |
# Simulate a writable /var/log so the macOS permission check in |
| 683 |
# rotated_logs() does not interfere with this test, which is |
| 684 |
# about the keep_lists/positive_re filtering logic, not |
| 685 |
# permissions (that's covered by a dedicated test). |
| 686 |
mock_isdir.return_value = True |
| 687 |
mock_access.return_value = True |
| 688 |
mock_whitelisted.side_effect = lambda path: path.startswith( |
| 689 |
'/var/log/whitelisted/') |
| 690 |
expected_delete = [ |
| 691 |
'/var/log/apt/history.log.1.gz', |
| 692 |
'/var/log/auth.log.3.old', |
| 693 |
'/var/log/dmesg.0', |
| 694 |
'/var/log/dmesg.1.gz', |
| 695 |
'/var/log/foo.gz', |
| 696 |
'/var/log/foo.old', |
| 697 |
'/var/log/foo/bar.0', |
| 698 |
'/var/log/foo/bar.gz', |
| 699 |
'/var/log/foo/bar.old', |
| 700 |
'/var/log/kern.log-20230601', |
| 701 |
'/var/log/messages-20090118.bz2', |
| 702 |
'/var/log/messages-20090118.gz', |
| 703 |
'/var/log/messages-20090118.xz', |
| 704 |
'/var/log/messages-20090118', |
| 705 |
'/var/log/messages.2.bz2', |
| 706 |
'/var/log/samba/log.smbd-20250126.gz', |
| 707 |
'/var/log/syslog.1', |
| 708 |
'/var/log/syslog.2.xz', |
| 709 |
'/var/log/cups/access_log.9' |
| 710 |
|
| 711 |
] |
| 712 |
expected_keep = [ |
| 713 |
'/var/log/dmesg', |
| 714 |
'/var/log/packages/foo.0', |
| 715 |
'/var/log/removed_packages/foo.0', |
| 716 |
'/var/log/removed_scripts/foo.0', |
| 717 |
'/var/log/samba/log.192.168.0.1', |
| 718 |
'/var/log/samba/log.172.17.0.1', |
| 719 |
'/var/log/scripts/foo.0', |
| 720 |
'/var/log/syslog', |
| 721 |
'/var/log/sysstat/sar24', |
| 722 |
'/var/log/whitelisted/foo.0' |
| 723 |
] |
| 724 |
mock_cid.return_value = iter(expected_delete + expected_keep) |
| 725 |
result = list(rotated_logs()) |
| 726 |
self.assertEqual(set(result), set(expected_delete)) |
| 727 |
for path in expected_keep: |
| 728 |
self.assertNotIn(path, result) |
| 729 |
mock_cid.assert_called_once_with('/var/log') |
| 730 |
mock_whitelisted.assert_called() |
| 731 |
|
| 732 |
@mock.patch('bleachbit.Unix.IS_MAC', True) |
| 733 |
@mock.patch('os.access') |
| 734 |
@mock.patch('os.path.isdir') |
| 735 |
@mock.patch('bleachbit.FileUtilities.whitelisted') |
| 736 |
@mock.patch('bleachbit.FileUtilities.children_in_directory') |
| 737 |
def test_rotated_logs_macos_permission_check( |
| 738 |
self, mock_cid, mock_whitelisted, mock_isdir, mock_access): |
| 739 |
"""On macOS, skip a path only if its parent dir exists and is |
| 740 |
unwritable. A nonexistent parent (os.access() also returns False |
| 741 |
for that) must not be treated the same as 'no permission'.""" |
| 742 |
mock_whitelisted.return_value = False |
| 743 |
candidates = [ |
| 744 |
'/var/log/protected/foo.0', |
| 745 |
'/var/log/missing_parent/foo.0', |
| 746 |
] |
| 747 |
mock_cid.return_value = iter(candidates) |
| 748 |
mock_isdir.side_effect = lambda p: p == '/var/log/protected' |
| 749 |
mock_access.return_value = False |
| 750 |
|
| 751 |
result = list(rotated_logs()) |
| 752 |
|
| 753 |
self.assertNotIn('/var/log/protected/foo.0', result) |
| 754 |
self.assertIn('/var/log/missing_parent/foo.0', result) |
| 755 |
|
| 756 |
@common.skipIfWindows |
| 757 |
def test_run_cleaner_cmd(self): |
| 758 |
"""Unit test for run_cleaner_cmd()""" |
| 759 |
self.assertRaises(RuntimeError, run_cleaner_cmd, |
| 760 |
'/hopethisdoesntexist', []) |
| 761 |
# Use absolute path in case like `env -i`. |
| 762 |
which_sh = 'sh' if exe_exists('sh') else '/usr/bin/sh' |
| 763 |
self.assertRaises(subprocess.CalledProcessError, run_cleaner_cmd, |
| 764 |
which_sh, ['-c', 'echo errormsg; false']) |
| 765 |
# test if regexes for invalid lines work |
| 766 |
self.assertRaises(RuntimeError, run_cleaner_cmd, 'echo', ['This is an invalid line'], |
| 767 |
error_line_regexes=['invalid']) |
| 768 |
|
| 769 |
freed_space_regex = r'^Freed ([\d.]+[kMT]?B)' |
| 770 |
lines = ['Test line', |
| 771 |
'Freed 100B on your hard drive', |
| 772 |
'Freed 1.9kB, hooray!', |
| 773 |
'Fred 12MB'] |
| 774 |
freed_space = run_cleaner_cmd( |
| 775 |
'echo', ['\n'.join(lines)], freed_space_regex) |
| 776 |
self.assertEqual(freed_space, 2000) |
| 777 |
|
| 778 |
@common.skipIfWindows |
| 779 |
def test_wine_to_linux_path(self): |
| 780 |
"""Unit test for wine_to_linux_path()""" |
| 781 |
wineprefix = "/home/foo/.wine" |
| 782 |
windows_pathname = "C:\\Program Files\\NSIS\\NSIS.exe" |
| 783 |
result = "/home/foo/.wine/drive_c/Program Files/NSIS/NSIS.exe" |
| 784 |
self.assertEqual(wine_to_linux_path( |
| 785 |
wineprefix, windows_pathname), result) |
| 786 |
|
| 787 |
@common.skipIfWindows |
| 788 |
def test_yum_clean(self): |
| 789 |
"""Unit test for yum_clean()""" |
| 790 |
if 0 != os.geteuid() or os.path.exists('/var/run/yum.pid') \ |
| 791 |
or not exe_exists(General.resolve_exe('yum')): |
| 792 |
self.assertRaises(RuntimeError, yum_clean) |
| 793 |
else: |
| 794 |
bytes_freed = yum_clean() |
| 795 |
self.assertIsInteger(bytes_freed) |
| 796 |
logger.debug('yum bytes cleaned %d', bytes_freed) |
| 797 |
|
| 798 |
@common.skipIfWindows |
| 799 |
def test_dnf_clean(self): |
| 800 |
"""Unit test for dnf_clean()""" |
| 801 |
if 0 != os.geteuid() or os.path.exists('/var/run/dnf.pid') \ |
| 802 |
or not exe_exists(General.resolve_exe('dnf')): |
| 803 |
self.assertRaises(RuntimeError, dnf_clean) |
| 804 |
else: |
| 805 |
bytes_freed = dnf_clean() |
| 806 |
self.assertIsInteger(bytes_freed) |
| 807 |
logger.debug('dnf bytes cleaned %d', bytes_freed) |
| 808 |
|
| 809 |
@common.skipIfWindows |
| 810 |
@mock.patch('bleachbit.Language.setup_translation') |
| 811 |
@mock.patch('bleachbit.Unix.os.geteuid') |
| 812 |
@mock.patch('bleachbit.Unix.FileUtilities.exe_exists') |
| 813 |
@mock.patch('bleachbit.Unix.General.run_external') |
| 814 |
@mock.patch('bleachbit.Unix.FileUtilities.getsizedir') |
| 815 |
@mock.patch('bleachbit.Unix.os.path.exists') |
| 816 |
def test_dnf_clean_mock(self, mock_path_exists, mock_getsizedir, mock_run, |
| 817 |
mock_exe, mock_geteuid, mock_setup): |
| 818 |
"""Unit test for dnf_clean() with mock for DNF4 and DNF5""" |
| 819 |
# Don't call setup_translation() for real because it uses |
| 820 |
# os.path.exists(), which is mocked here. |
| 821 |
mock_setup.return_value = None |
| 822 |
# Pretend to be root so the euid guard in dnf_clean() does not |
| 823 |
# short-circuit the rest of the logic under test. |
| 824 |
mock_geteuid.return_value = 0 |
| 825 |
mock_exe.return_value = True |
| 826 |
mock_path_exists.return_value = True |
| 827 |
# dnf.pid present -> RuntimeError |
| 828 |
self.assertRaises(RuntimeError, dnf_clean) |
| 829 |
|
| 830 |
mock_path_exists.return_value = False |
| 831 |
|
| 832 |
# DNF5 reports freed space directly in its summary line, so the |
| 833 |
# getsizedir fallback (post-run measurement) must not be used. |
| 834 |
# The pre-run measurement still happens once for the DNF4 fallback. |
| 835 |
mock_run.return_value = ( |
| 836 |
0, 'Removed 12 files, 3 directories ' |
| 837 |
'(total of 25 MiB). 0 errors occurred.\n', '') |
| 838 |
mock_getsizedir.reset_mock() |
| 839 |
self.assertEqual(dnf_clean(), 25 * 1024 ** 2) |
| 840 |
self.assertEqual(mock_getsizedir.call_count, 1) |
| 841 |
|
| 842 |
mock_run.return_value = ( |
| 843 |
0, 'Removed 12 files, 3 directories ' |
| 844 |
'(total of 25 MiB). 1 errors occurred.\n', '') |
| 845 |
self.assertRaises(RuntimeError, dnf_clean) |
| 846 |
|
| 847 |
# DNF5 "nothing to clean" still parses to 0 bytes. |
| 848 |
mock_run.return_value = ( |
| 849 |
0, 'Removed 0 files, 0 directories ' |
| 850 |
'(total of 0 B). 0 errors occurred.\n', '') |
| 851 |
self.assertEqual(dnf_clean(), 0) |
| 852 |
|
| 853 |
# DNF4 does not report freed space, so fall back to the cache |
| 854 |
# directory size difference (old - new). |
| 855 |
mock_run.return_value = (0, 'Cleaning repos: ', '') |
| 856 |
mock_getsizedir.side_effect = [1000, 250] |
| 857 |
self.assertEqual(dnf_clean(), 750) |
| 858 |
|
| 859 |
# DNF4 invalid output line raises RuntimeError. |
| 860 |
mock_run.return_value = ( |
| 861 |
0, 'You need to be root to perform this command.\n', '') |
| 862 |
mock_getsizedir.side_effect = None |
| 863 |
mock_getsizedir.return_value = 1000 |
| 864 |
self.assertRaises(RuntimeError, dnf_clean) |
| 865 |
|
| 866 |
# DNF4 non-zero exit code raises RuntimeError. |
| 867 |
mock_run.return_value = (1, '', 'some error') |
| 868 |
self.assertRaises(RuntimeError, dnf_clean) |
| 869 |
|
| 870 |
# dnf not installed -> RuntimeError. |
| 871 |
mock_exe.return_value = False |
| 872 |
self.assertRaises(RuntimeError, dnf_clean) |
| 873 |
|
| 874 |
# non-root user -> RuntimeError (DNF5 would otherwise silently |
| 875 |
# clean the per-user cache and report 0 bytes freed). |
| 876 |
mock_exe.return_value = True |
| 877 |
mock_geteuid.return_value = 1000 |
| 878 |
self.assertRaises(RuntimeError, dnf_clean) |
| 879 |
|
| 880 |
@common.skipIfWindows |
| 881 |
def test_dnf_autoremove_real(self): |
| 882 |
"""Unit test for dnf_autoremove() with real dnf""" |
| 883 |
if 0 != os.geteuid() or os.path.exists('/var/run/dnf.pid') \ |
| 884 |
or not exe_exists(General.resolve_exe('dnf')): |
| 885 |
self.assertRaises(RuntimeError, dnf_autoremove) |
| 886 |
else: |
| 887 |
bytes_freed = dnf_autoremove() |
| 888 |
self.assertIsInteger(bytes_freed) |
| 889 |
logger.debug('dnf bytes cleaned %d', bytes_freed) |
| 890 |
|
| 891 |
@common.skipIfWindows |
| 892 |
@mock.patch('bleachbit.Language.setup_translation') |
| 893 |
@mock.patch('bleachbit.Unix.FileUtilities.exe_exists') |
| 894 |
@mock.patch('bleachbit.Unix.os.path.exists') |
| 895 |
@mock.patch('bleachbit.General.run_external') |
| 896 |
def test_dnf_autoremove_mock(self, mock_run, mock_path_exists, mock_exe, |
| 897 |
mock_setup): |
| 898 |
"""Unit test for dnf_autoremove() with mock""" |
| 899 |
# Don't call setup_translation() for real because it uses |
| 900 |
# os.path.exists(), which is mocked here. |
| 901 |
mock_setup.return_value = None |
| 902 |
mock_exe.return_value = True |
| 903 |
mock_path_exists.return_value = True |
| 904 |
self.assertRaises(RuntimeError, dnf_autoremove) |
| 905 |
|
| 906 |
mock_path_exists.return_value = False |
| 907 |
|
| 908 |
# dnf not installed -> RuntimeError. |
| 909 |
mock_exe.return_value = False |
| 910 |
self.assertRaises(RuntimeError, dnf_autoremove) |
| 911 |
mock_exe.return_value = True |
| 912 |
|
| 913 |
mock_run.return_value = (1, 'stdout', 'stderr') |
| 914 |
self.assertRaises(RuntimeError, dnf_autoremove) |
| 915 |
|
| 916 |
mock_run.return_value = (0, 'Nothing to do.', 'stderr') |
| 917 |
bytes_freed = dnf_autoremove() |
| 918 |
self.assertEqual(bytes_freed, 0) |
| 919 |
|
| 920 |
mock_run.return_value = ( |
| 921 |
0, 'Remove 112 Packages\nFreed space: 299 M\n', 'stderr') |
| 922 |
bytes_freed = dnf_autoremove() |
| 923 |
# dnf's format_number() uses 1024-based binary units, so 299 M |
| 924 |
# means 299 * 1024**2, not 299 * 1000**2. |
| 925 |
self.assertEqual(bytes_freed, 299 * 1024 ** 2) |
| 926 |
|
| 927 |
# DNF5 autoremove reports the net freed size in its summary line. |
| 928 |
mock_run.return_value = ( |
| 929 |
0, 'After this operation, 299 MiB will be freed ' |
| 930 |
'(install 0 B, remove 299 MiB).\n', 'stderr') |
| 931 |
bytes_freed = dnf_autoremove() |
| 932 |
self.assertEqual(bytes_freed, 299 * 1024 ** 2) |
| 933 |
|
| 934 |
@common.skipIfWindows |
| 935 |
def test_parse_dnf_freed_space(self): |
| 936 |
"""Directly test parse_dnf_freed_space()""" |
| 937 |
# DNF4 autoremove: "Freed space: <n> <unit>" |
| 938 |
dnf4_cases = [ |
| 939 |
('Freed space: 0 \n', 0), |
| 940 |
('Freed space: 500 \n', 500), |
| 941 |
('Freed space: 999 \n', 999), |
| 942 |
('Freed space: 1.5 k\n', int(1.5 * 1024)), |
| 943 |
('Freed space: 10 k\n', 10 * 1024), |
| 944 |
('Freed space: 5.0 M\n', int(5.0 * 1024 ** 2)), |
| 945 |
('Freed space: 299 M\n', 299 * 1024 ** 2), |
| 946 |
('Freed space: 1.0 G\n', int(1.0 * 1024 ** 3)), |
| 947 |
('Freed space: 1.5 T\n', int(1.5 * 1024 ** 4)), |
| 948 |
('Nothing to do.\n', None), |
| 949 |
('', None), |
| 950 |
] |
| 951 |
# DNF5 autoremove: "After this operation, <n> <unit> will be freed |
| 952 |
# (install <n> <unit>, remove <n> <unit>)." |
| 953 |
dnf5_autoremove_cases = [ |
| 954 |
('After this operation, 0 B will be freed ' |
| 955 |
'(install 0 B, remove 0 B).\n', 0), |
| 956 |
('After this operation, 500 B will be freed ' |
| 957 |
'(install 0 B, remove 500 B).\n', 500), |
| 958 |
('After this operation, 1 KiB will be freed ' |
| 959 |
'(install 0 B, remove 1 KiB).\n', 1024), |
| 960 |
('After this operation, 10 KiB will be freed ' |
| 961 |
'(install 0 B, remove 10 KiB).\n', 10 * 1024), |
| 962 |
('After this operation, 5 MiB will be freed ' |
| 963 |
'(install 0 B, remove 5 MiB).\n', 5 * 1024 ** 2), |
| 964 |
('After this operation, 299 MiB will be freed ' |
| 965 |
'(install 0 B, remove 299 MiB).\n', 299 * 1024 ** 2), |
| 966 |
('After this operation, 1 GiB will be freed ' |
| 967 |
'(install 0 B, remove 1 GiB).\n', 1024 ** 3), |
| 968 |
('After this operation, 2 TiB will be freed ' |
| 969 |
'(install 0 B, remove 2 TiB).\n', 2 * 1024 ** 4), |
| 970 |
('After this operation, 1.5 MiB will be freed ' |
| 971 |
'(install 0 B, remove 1.5 MiB).\n', int(1.5 * 1024 ** 2)), |
| 972 |
('Nothing to do.\n', None), |
| 973 |
('', None), |
| 974 |
] |
| 975 |
# DNF5 "clean all": "Removed <f> files, <d> directories (total of |
| 976 |
# <n> <unit>). <n> errors occurred." |
| 977 |
dnf5_clean_cases = [ |
| 978 |
('Removed 0 files, 0 directories (total of 0 B). ' |
| 979 |
'0 errors occurred.\n', 0), |
| 980 |
('Removed 1 files, 0 directories (total of 500 B). ' |
| 981 |
'0 errors occurred.\n', 500), |
| 982 |
('Removed 1 files, 0 directories (total of 999 B). ' |
| 983 |
'0 errors occurred.\n', 999), |
| 984 |
('Removed 1 files, 0 directories (total of 1 KiB). ' |
| 985 |
'0 errors occurred.\n', 1024), |
| 986 |
('Removed 5 files, 1 directories (total of 10 KiB). ' |
| 987 |
'0 errors occurred.\n', 10 * 1024), |
| 988 |
('Removed 5 files, 1 directories (total of 5 MiB). ' |
| 989 |
'0 errors occurred.\n', 5 * 1024 ** 2), |
| 990 |
('Removed 5 files, 1 directories (total of 299 MiB). ' |
| 991 |
'0 errors occurred.\n', 299 * 1024 ** 2), |
| 992 |
('Removed 5 files, 1 directories (total of 1 GiB). ' |
| 993 |
'0 errors occurred.\n', 1024 ** 3), |
| 994 |
('Removed 5 files, 1 directories (total of 2 TiB). ' |
| 995 |
'0 errors occurred.\n', 2 * 1024 ** 4), |
| 996 |
('Removed 12 files, 3 directories (total of 25 MiB). ' |
| 997 |
'0 errors occurred.\n', 25 * 1024 ** 2), |
| 998 |
('Cache directory "/var/cache/libdnf5" does not exist. ' |
| 999 |
'Nothing to clean.\n', None), |
| 1000 |
('', None), |
| 1001 |
] |
| 1002 |
for output, expected in dnf4_cases + dnf5_autoremove_cases \ |
| 1003 |
+ dnf5_clean_cases: |
| 1004 |
with self.subTest(output=output.strip()): |
| 1005 |
self.assertEqual(parse_dnf_freed_space(output), expected) |
| 1006 |
|
| 1007 |
@common.skipIfWindows |
| 1008 |
def test_pacman_cache(self): |
| 1009 |
"""Unit test for pacman_cache()""" |
| 1010 |
if 0 != os.geteuid() or os.path.exists('/var/lib/pacman/db.lck') \ |
| 1011 |
or not exe_exists(General.resolve_exe('paccache')): |
| 1012 |
self.assertRaises(RuntimeError, pacman_cache) |
| 1013 |
else: |
| 1014 |
bytes_freed = pacman_cache() |
| 1015 |
self.assertIsInteger(bytes_freed) |
| 1016 |
logger.debug('pacman bytes cleaned %d', bytes_freed) |
| 1017 |
|
| 1018 |
@common.skipIfWindows |
| 1019 |
@mock.patch('bleachbit.Unix.General.run_external') |
| 1020 |
@mock.patch('bleachbit.Unix.exe_exists') |
| 1021 |
@mock.patch('bleachbit.Unix.os.path.exists') |
| 1022 |
def test_pacman_cache_mock(self, mock_path_exists, mock_exe_exists, mock_run): |
| 1023 |
"""Unit test pacman_cache() parse logic without pacman installed""" |
| 1024 |
mock_path_exists.return_value = False |
| 1025 |
mock_exe_exists.return_value = True |
| 1026 |
mock_run.return_value = ( |
| 1027 |
0, |
| 1028 |
"==> finished: 3 packages removed (42.31 M freed)\n", |
| 1029 |
'' |
| 1030 |
) |
| 1031 |
|
| 1032 |
bytes_freed = pacman_cache() |
| 1033 |
self.assertEqual(bytes_freed, 42310000) |
| 1034 |
|
| 1035 |
mock_run.assert_called_once_with( |
| 1036 |
[General.resolve_exe('paccache'), '-rk0']) |
| 1037 |
|
| 1038 |
# real paccache reports binary units (MiB), not decimal (M) |
| 1039 |
mock_run.return_value = ( |
| 1040 |
0, |
| 1041 |
"==> finished: 3 packages removed (42.31 MiB freed)\n", |
| 1042 |
'' |
| 1043 |
) |
| 1044 |
bytes_freed = pacman_cache() |
| 1045 |
self.assertEqual(bytes_freed, 44365250) |
| 1046 |
|
| 1047 |
def test_snapd_is_active_no_snap(self): |
| 1048 |
"""Unit test for snapd_is_active() when snap is not installed""" |
| 1049 |
with mock.patch('bleachbit.Unix.exe_exists', return_value=False): |
| 1050 |
self.assertFalse(snapd_is_active()) |
| 1051 |
|
| 1052 |
def test_snapd_is_active_no_systemctl(self): |
| 1053 |
"""Unit test for snapd_is_active() when systemctl is not installed""" |
| 1054 |
with mock.patch('bleachbit.Unix.exe_exists', side_effect=lambda x: x == 'snap'): |
| 1055 |
self.assertFalse(snapd_is_active()) |
| 1056 |
|
| 1057 |
def test_snapd_is_active_inactive(self): |
| 1058 |
"""Unit test for snapd_is_active() when snapd.socket is inactive""" |
| 1059 |
with mock.patch('bleachbit.Unix.exe_exists', return_value=True), \ |
| 1060 |
mock.patch('bleachbit.General.run_external', return_value=(1, '', '')): |
| 1061 |
self.assertFalse(snapd_is_active()) |
| 1062 |
|
| 1063 |
def test_snapd_is_active_active(self): |
| 1064 |
"""Unit test for snapd_is_active() when snapd.socket is active""" |
| 1065 |
with mock.patch('bleachbit.Unix.exe_exists', return_value=True), \ |
| 1066 |
mock.patch('bleachbit.General.run_external', return_value=(0, '', '')): |
| 1067 |
self.assertTrue(snapd_is_active()) |
| 1068 |
|
| 1069 |
def test_snapd_is_active_timeout(self): |
| 1070 |
"""Unit test for snapd_is_active() timeout handling""" |
| 1071 |
with mock.patch('bleachbit.Unix.exe_exists', return_value=True), \ |
| 1072 |
mock.patch('bleachbit.General.run_external') as mock_run: |
| 1073 |
mock_run.side_effect = subprocess.TimeoutExpired( |
| 1074 |
['systemctl', 'is-active', '--quiet', 'snapd.socket'], 5) |
| 1075 |
self.assertFalse(snapd_is_active()) |
| 1076 |
|
| 1077 |
@common.skipIfWindows |
| 1078 |
@common.skipUnlessDestructive |
| 1079 |
def test_snap_disabled_clean(self): |
| 1080 |
"""Unit test for snap_disabled_clean()""" |
| 1081 |
if not exe_exists(General.resolve_exe('snap')): |
| 1082 |
self.assertRaises(RuntimeError, snap_disabled_clean) |
| 1083 |
else: |
| 1084 |
bytes_freed = snap_disabled_clean() |
| 1085 |
self.assertIsInteger(bytes_freed) |
| 1086 |
logger.debug('snap disabled bytes freed %d', bytes_freed) |
| 1087 |
|
| 1088 |
@common.skipIfWindows |
| 1089 |
def test_snap_disabled_preview(self): |
| 1090 |
"""Unit test for snap_disabled_preview()""" |
| 1091 |
if not exe_exists(General.resolve_exe('snap')): |
| 1092 |
self.assertRaises(RuntimeError, snap_disabled_preview) |
| 1093 |
else: |
| 1094 |
bytes_freed = snap_disabled_preview() |
| 1095 |
self.assertIsInstance(bytes_freed, int) |
| 1096 |
logger.debug('snap disabled bytes freed %d', bytes_freed) |
| 1097 |
|
| 1098 |
@common.skipIfWindows |
| 1099 |
def test_snap_timeout(self): |
| 1100 |
"""Unit test for snap_disabled_full() timeout handling""" |
| 1101 |
with mock.patch('bleachbit.Unix.snapd_is_active', return_value=True), \ |
| 1102 |
mock.patch('bleachbit.General.run_external') as mock_run: |
| 1103 |
# Simulate snap list --all hanging |
| 1104 |
mock_run.side_effect = subprocess.TimeoutExpired( |
| 1105 |
['snap', 'list', '--all'], 10) |
| 1106 |
with self.assertRaises(RuntimeError) as cm: |
| 1107 |
snap_disabled_preview() |
| 1108 |
self.assertIn('timed out', str(cm.exception)) |
| 1109 |
|
| 1110 |
def test_snap_parse_list_real_data(self): |
| 1111 |
"""Unit test for snap_parse_list() with real 'snap list --all' output""" |
| 1112 |
sample = ( |
| 1113 |
"Name Version Rev Tracking Publisher Notes\n" |
| 1114 |
"astral-uv 0.8.9 902 latest/stable lengau classic\n" |
| 1115 |
"astral-uv 0.7.21 759 latest/stable lengau disabled,classic\n" |
| 1116 |
"bare 1.0 5 latest/stable canonical** base\n" |
| 1117 |
"cheese 44.1 78 latest/stable ken-vandine* -\n" |
| 1118 |
"cheese 44.1 76 latest/stable ken-vandine* disabled\n" |
| 1119 |
) |
| 1120 |
expected = [ |
| 1121 |
('astral-uv', '759'), |
| 1122 |
('cheese', '76') |
| 1123 |
] |
| 1124 |
result = snap_parse_list(sample) |
| 1125 |
self.assertEqual(result, expected) |
| 1126 |
|
| 1127 |
def test_snap_parse_list_no_snaps_message(self): |
| 1128 |
"""Unit test for snap_parse_list() with 'no snaps installed' output""" |
| 1129 |
sample = "No snaps are installed yet. Try 'snap install hello-world'.\n" |
| 1130 |
result = snap_parse_list(sample) |
| 1131 |
self.assertEqual(result, []) |
| 1132 |
|
| 1133 |
@common.skipIfWindows |
| 1134 |
def test_is_unix_display_protocol_wayland_no_mock(self): |
| 1135 |
"""Unit test for test_is_unix_display_protocol_wayland() with no mock""" |
| 1136 |
ret = is_unix_display_protocol_wayland() |
| 1137 |
self.assertIsInstance(ret, bool) |
| 1138 |
|
| 1139 |
@common.skipIfWindows |
| 1140 |
def test_is_unix_display_protocol_wayland_mock_env(self): |
| 1141 |
"""Unit test for test_is_unix_display_protocol_wayland() by mocking os.environ""" |
| 1142 |
# The environment variables take precedence. |
| 1143 |
with mock.patch.dict('os.environ', {'XDG_SESSION_TYPE': 'x11'}, clear=True): |
| 1144 |
self.assertFalse(is_unix_display_protocol_wayland()) |
| 1145 |
with mock.patch.dict('os.environ', {'XDG_SESSION_TYPE': 'wayland'}, clear=True): |
| 1146 |
self.assertTrue(is_unix_display_protocol_wayland()) |
| 1147 |
with mock.patch.dict('os.environ', {'WAYLAND_DISPLAY': 'yes'}, clear=True): |
| 1148 |
self.assertTrue(is_unix_display_protocol_wayland()) |
| 1149 |
|
| 1150 |
@common.skipIfWindows |
| 1151 |
@mock.patch.dict(os.environ, {}, clear=True) |
| 1152 |
def test_is_unix_display_protocol_wayland_mock_no_env(self): |
| 1153 |
"""Unit test for test_is_unix_display_protocol_wayland() by clearing os.environ""" |
| 1154 |
self.assertEqual(len(os.environ), 0) |
| 1155 |
|
| 1156 |
# Check that it does not throw an exception. |
| 1157 |
is_unix_display_protocol_wayland() |
| 1158 |
|
| 1159 |
display_protocol = None |
| 1160 |
|
| 1161 |
def side_effect_func(value): |
| 1162 |
if len(value) == 1: |
| 1163 |
return (0, 'SESSION UID USER SEAT TTY \n 2 1000 debian seat0 tty2\n\n1 sessions listed.\n', '') |
| 1164 |
if len(value) > 1: |
| 1165 |
return (0, f'Type={display_protocol}\n', '') |
| 1166 |
assert False # should never reach here |
| 1167 |
|
| 1168 |
for display_protocol, assert_method in [['wayland', self.assertTrue], ['donotexist', self.assertFalse]]: |
| 1169 |
with mock.patch('bleachbit.General.run_external') as mock_run_external: |
| 1170 |
mock_run_external.side_effect = side_effect_func |
| 1171 |
is_wayland = is_unix_display_protocol_wayland() |
| 1172 |
assert mock_run_external.called |
| 1173 |
self.assertIsInstance(is_wayland, bool) |
| 1174 |
assert_method(is_wayland) |
| 1175 |
|
| 1176 |
with mock.patch('bleachbit.General.run_external') as mock_run_external: |
| 1177 |
mock_run_external.side_effect = FileNotFoundError('not found') |
| 1178 |
self.assertFalse(is_unix_display_protocol_wayland()) |
| 1179 |
assert mock_run_external.called |
| 1180 |
|
| 1181 |
with mock.patch('bleachbit.General.run_external') as mock_run_external: |
| 1182 |
mock_run_external.side_effect = lambda a: (1, None, None) |
| 1183 |
self.assertFalse(is_unix_display_protocol_wayland()) |
| 1184 |
assert mock_run_external.called |
| 1185 |
|
| 1186 |
with mock.patch('bleachbit.General.run_external') as mock_run_external: |
| 1187 |
mock_run_external.side_effect = lambda a: ( |
| 1188 |
0, 'test of invalid output from loginctl', None) |
| 1189 |
self.assertFalse(is_unix_display_protocol_wayland()) |
| 1190 |
assert mock_run_external.called |
| 1191 |
|
| 1192 |
@common.skipIfWindows |
| 1193 |
def test_xhost_autorized_root(self): |
| 1194 |
error_code = None |
| 1195 |
|
| 1196 |
def side_effect_func(*args, **_kwargs): |
| 1197 |
self.assertEqual(args[0][0], General.resolve_exe('xhost')) |
| 1198 |
return (error_code, |
| 1199 |
'', |
| 1200 |
'') |
| 1201 |
|
| 1202 |
for error_code, expected_root_autorized in [[1, True], [0, False]]: |
| 1203 |
with mock.patch('bleachbit.General.run_external') as mock_run_external: |
| 1204 |
mock_run_external.side_effect = side_effect_func |
| 1205 |
root_autorized = root_is_not_allowed_to_X_session() |
| 1206 |
self.assertIsInstance(root_autorized, bool) |
| 1207 |
self.assertEqual(expected_root_autorized, root_autorized) |
| 1208 |
|
| 1209 |
@common.skipIfWindows |
| 1210 |
def test_get_trash_paths_snap_symlink(self): |
| 1211 |
"""Do not follow symlinks in ~/snap when finding trash""" |
| 1212 |
with common.set_temporary_env('HOME', self.tempdir): |
| 1213 |
# Create snap structure: snap/app/238/.local/share/Trash/files/ |
| 1214 |
real_rev = os.path.join(self.tempdir, 'snap', 'app', '238') |
| 1215 |
trash_files = os.path.join( |
| 1216 |
real_rev, '.local', 'share', 'Trash', 'files') |
| 1217 |
os.makedirs(trash_files) |
| 1218 |
test_file = os.path.join(trash_files, 'test.txt') |
| 1219 |
with open(test_file, 'w') as f: |
| 1220 |
f.write('test') |
| 1221 |
# Create symlink current -> 238 |
| 1222 |
current_dir = os.path.join(self.tempdir, 'snap', 'app', 'current') |
| 1223 |
os.symlink('238', current_dir) |
| 1224 |
|
| 1225 |
paths = [cmd.path for cmd in get_trash_paths()] |
| 1226 |
# Should find the test file through the real path |
| 1227 |
self.assertIn(test_file, paths) |
| 1228 |
# Should NOT find it through the symlink |
| 1229 |
symlink_path = os.path.join( |
| 1230 |
self.tempdir, 'snap', 'app', 'current', '.local', 'share', |
| 1231 |
'Trash', 'files', 'test.txt') |
| 1232 |
self.assertNotIn(symlink_path, paths) |
| 1233 |
|
| 1234 |
|
| 1235 |
class LocalizationsTestCase(common.BleachbitTestCase): |
| 1236 |
|
| 1237 |
"""Test case for localizations in Unix module""" |
| 1238 |
|
| 1239 |
@staticmethod |
| 1240 |
def _get_recognized_paths(vfs): |
| 1241 |
"""Load localizations.xml and return paths recognized by it using the given VFS.""" |
| 1242 |
xml_path = os.path.join(os.path.dirname( |
| 1243 |
os.path.dirname(__file__)), 'cleaners', 'localizations.xml') |
| 1244 |
with open(xml_path, 'r', encoding='utf-8') as f: |
| 1245 |
xml_doc = parseString(f.read()) |
| 1246 |
|
| 1247 |
localizations_node = None |
| 1248 |
for child in xml_doc.firstChild.childNodes: |
| 1249 |
if child.nodeType == child.ELEMENT_NODE and child.nodeName == 'localizations': |
| 1250 |
localizations_node = child |
| 1251 |
break |
| 1252 |
assert localizations_node is not None, 'localizations.xml must contain a <localizations> element' |
| 1253 |
|
| 1254 |
locales = Locales(vfs=vfs) |
| 1255 |
for child in localizations_node.childNodes: |
| 1256 |
if child.nodeType == child.ELEMENT_NODE: |
| 1257 |
locales.add_xml(child) |
| 1258 |
|
| 1259 |
recognized = set() |
| 1260 |
for (_locale, _specifier, path) in locales._paths.get_localizations('/'): |
| 1261 |
recognized.add(path) |
| 1262 |
return recognized |
| 1263 |
|
| 1264 |
@staticmethod |
| 1265 |
def _path_matches_recognized(test_path, recognized): |
| 1266 |
"""Return True if test_path is in recognized or is a child/descendant of one.""" |
| 1267 |
if test_path in recognized: |
| 1268 |
return True |
| 1269 |
for rec_path in recognized: |
| 1270 |
if test_path.startswith(rec_path + '/'): |
| 1271 |
return True |
| 1272 |
return False |
| 1273 |
|
| 1274 |
def test_localization_paths_positive(self): |
| 1275 |
"""Verify each path in localization_paths_positive.txt is matched by localizations.xml |
| 1276 |
|
| 1277 |
Uses a virtual filesystem so the test verifies actual XML rule matching |
| 1278 |
without requiring a real /var/lib/flatpak tree. |
| 1279 |
""" |
| 1280 |
data_file = os.path.join(os.path.dirname( |
| 1281 |
__file__), 'localization_paths_positive.txt') |
| 1282 |
self.assertExists(data_file) |
| 1283 |
|
| 1284 |
with open(data_file, 'r', encoding='utf-8') as f: |
| 1285 |
test_paths = [line.strip() for line in f if line.strip() |
| 1286 |
and not line.strip().startswith('#')] |
| 1287 |
self.assertGreater(len(test_paths), 0, |
| 1288 |
'Test data file should contain at least one path') |
| 1289 |
|
| 1290 |
vfs = ListVFS(test_paths) |
| 1291 |
recognized = self._get_recognized_paths(vfs) |
| 1292 |
|
| 1293 |
for test_path in test_paths: |
| 1294 |
self.assertTrue( |
| 1295 |
self._path_matches_recognized(test_path, recognized), |
| 1296 |
f'Path not matched by localizations.xml: {test_path}' |
| 1297 |
) |
| 1298 |
|
| 1299 |
def test_localization_paths_negative(self): |
| 1300 |
"""Verify non-localization paths in flatpak are NOT matched |
| 1301 |
|
| 1302 |
Uses a virtual filesystem so the test verifies that paths |
| 1303 |
that look similar to localizations are correctly rejected. |
| 1304 |
""" |
| 1305 |
data_file = os.path.join(os.path.dirname( |
| 1306 |
__file__), 'localization_paths_negative.txt') |
| 1307 |
self.assertExists(data_file) |
| 1308 |
|
| 1309 |
with open(data_file, 'r', encoding='utf-8') as f: |
| 1310 |
negative_paths = [line.strip() for line in f if line.strip( |
| 1311 |
) and not line.strip().startswith('#')] |
| 1312 |
self.assertGreater(len(negative_paths), 0, |
| 1313 |
'Test data file should contain at least one path') |
| 1314 |
|
| 1315 |
positive_file = os.path.join(os.path.dirname( |
| 1316 |
__file__), 'localization_paths_positive.txt') |
| 1317 |
with open(positive_file, 'r', encoding='utf-8') as f: |
| 1318 |
positive_paths = [line.strip() for line in f if line.strip( |
| 1319 |
) and not line.strip().startswith('#')] |
| 1320 |
|
| 1321 |
vfs = ListVFS(positive_paths + negative_paths) |
| 1322 |
recognized = self._get_recognized_paths(vfs) |
| 1323 |
|
| 1324 |
for neg_path in negative_paths: |
| 1325 |
self.assertFalse( |
| 1326 |
self._path_matches_recognized(neg_path, recognized), |
| 1327 |
f'Path should NOT be matched by localizations.xml: {neg_path}' |
| 1328 |
) |