| 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 General |
| 9 |
""" |
| 10 |
|
| 11 |
# standard library |
| 12 |
import os |
| 13 |
import shutil |
| 14 |
import subprocess |
| 15 |
import sys |
| 16 |
import tempfile |
| 17 |
import time |
| 18 |
import warnings |
| 19 |
from unittest import mock |
| 20 |
|
| 21 |
# local |
| 22 |
from bleachbit import General, IS_POSIX, IS_WINDOWS, logger |
| 23 |
from bleachbit.FileUtilities import exe_exists, exists_in_path |
| 24 |
from bleachbit.General import ( |
| 25 |
boolstr_to_bool, |
| 26 |
chownself, |
| 27 |
get_executable, |
| 28 |
get_real_uid, |
| 29 |
get_real_username, |
| 30 |
makedirs, |
| 31 |
reject_xml_dtd, |
| 32 |
run_external, |
| 33 |
run_external_nowait, |
| 34 |
sanitize_root_env, |
| 35 |
shell_split, |
| 36 |
sudo_mode) |
| 37 |
from tests import common |
| 38 |
from tests.common import also_with_sudo |
| 39 |
|
| 40 |
|
| 41 |
class GeneralTestCase(common.BleachbitTestCase): |
| 42 |
"""Test case for module General""" |
| 43 |
|
| 44 |
def test_boolstr_to_bool(self): |
| 45 |
"""Test case for method boolstr_to_bool""" |
| 46 |
tests = (('True', True), |
| 47 |
('true', True), |
| 48 |
('False', False), |
| 49 |
('false', False)) |
| 50 |
|
| 51 |
for test in tests: |
| 52 |
self.assertEqual(boolstr_to_bool(test[0]), test[1]) |
| 53 |
|
| 54 |
def test_get_executable(self): |
| 55 |
"""Test for get_executable()""" |
| 56 |
exe = get_executable() |
| 57 |
self.assertIsInstance(exe, str) |
| 58 |
self.assertGreater(len(exe), 0) |
| 59 |
self.assertEqual(exe, exe.strip()) |
| 60 |
self.assertTrue(exe_exists(exe)) |
| 61 |
if sys.executable: |
| 62 |
self.assertEqual(exe, sys.executable) |
| 63 |
|
| 64 |
@also_with_sudo |
| 65 |
def test_get_real_uid(self): |
| 66 |
"""Test for get_real_uid()""" |
| 67 |
if not IS_POSIX: |
| 68 |
self.assertRaises(RuntimeError, get_real_uid) |
| 69 |
return |
| 70 |
|
| 71 |
# Basic functionality test |
| 72 |
uid = get_real_uid() |
| 73 |
self.assertIsInstance(uid, int) |
| 74 |
self.assertTrue(0 <= uid <= 65535) |
| 75 |
|
| 76 |
# Multiple calls should return same value |
| 77 |
uid2 = get_real_uid() |
| 78 |
self.assertEqual(uid, uid2) |
| 79 |
|
| 80 |
# Test relationship with sudo_mode() |
| 81 |
if sudo_mode(): |
| 82 |
self.assertGreater(uid, 0) |
| 83 |
self.assertNotEqual(uid, os.geteuid()) |
| 84 |
else: |
| 85 |
self.assertEqual(uid, os.getuid()) |
| 86 |
|
| 87 |
# Test that UID is exists in passwd |
| 88 |
# Import pwd here because it would fail on Windows. |
| 89 |
import pwd # pylint: disable=import-outside-toplevel |
| 90 |
try: |
| 91 |
pwd_entry = pwd.getpwuid(uid) |
| 92 |
self.assertIsInstance(pwd_entry.pw_name, str) |
| 93 |
self.assertGreater(len(pwd_entry.pw_name), 0) |
| 94 |
except KeyError: |
| 95 |
# UID might not be in passwd database in some test environments |
| 96 |
pass |
| 97 |
|
| 98 |
# Test environment variable consistency |
| 99 |
sudo_uid_env = os.getenv('SUDO_UID') |
| 100 |
if sudo_uid_env: |
| 101 |
self.assertEqual(uid, int(sudo_uid_env)) |
| 102 |
|
| 103 |
# Test with empty LOGNAME (if not in sudo mode) |
| 104 |
if not sudo_mode(): |
| 105 |
with common.set_temporary_env('LOGNAME', None): |
| 106 |
uid_no_logname = get_real_uid() |
| 107 |
self.assertIsInstance(uid_no_logname, int) |
| 108 |
self.assertTrue(0 <= uid_no_logname <= 65535) |
| 109 |
|
| 110 |
# Debug logging for troubleshooting |
| 111 |
logger.debug("os.getenv('LOGNAME') = %s", os.getenv('LOGNAME')) |
| 112 |
logger.debug("os.getenv('SUDO_UID') = %s", os.getenv('SUDO_UID')) |
| 113 |
logger.debug('os.geteuid() = %d', os.geteuid()) |
| 114 |
logger.debug('os.getuid() = %d', os.getuid()) |
| 115 |
logger.debug('get_real_uid() = %d', uid) |
| 116 |
logger.debug('sudo_mode() = %s', sudo_mode()) |
| 117 |
|
| 118 |
try: |
| 119 |
logger.debug('os.getlogin() = %s', os.getlogin()) |
| 120 |
except Exception: |
| 121 |
logger.exception('os.getlogin() raised exception') |
| 122 |
|
| 123 |
# Test that function doesn't modify global state |
| 124 |
uid_after = get_real_uid() |
| 125 |
self.assertEqual(uid, uid_after) |
| 126 |
|
| 127 |
def test_get_real_uid_numeric_login_without_passwd_entry(self): |
| 128 |
"""Docker containers may advertise UID as username without /etc/passwd.""" |
| 129 |
if not IS_POSIX: |
| 130 |
self.skipTest('POSIX-only behavior') |
| 131 |
|
| 132 |
# Ensure the code path executes past the SUDO_UID shortcut. |
| 133 |
env_overrides = {'SUDO_UID': ''} |
| 134 |
with mock.patch.dict(os.environ, env_overrides, clear=False): |
| 135 |
with mock.patch('os.getlogin', return_value='1000'): |
| 136 |
with mock.patch('pwd.getpwnam', side_effect=KeyError): |
| 137 |
uid = get_real_uid() |
| 138 |
self.assertEqual(uid, 1000) |
| 139 |
|
| 140 |
def test_sanitize_root_env_non_root(self): |
| 141 |
"""Not running as root: environment is returned unchanged.""" |
| 142 |
env = {'PATH': '/tmp/evil', 'LD_PRELOAD': 'evil.so'} |
| 143 |
with mock.patch('os.geteuid', return_value=1000, create=True): |
| 144 |
self.assertEqual(sanitize_root_env(env), env) |
| 145 |
|
| 146 |
def test_sanitize_root_env_root(self): |
| 147 |
"""As root: drop code-loading vars and PATH entries a non-root user could write.""" |
| 148 |
dropped_vars = ('LD_PRELOAD', 'LD_LIBRARY_PATH', 'LD_AUDIT', |
| 149 |
'DYLD_INSERT_LIBRARIES', 'DYLD_LIBRARY_PATH', |
| 150 |
'DYLD_FRAMEWORK_PATH', |
| 151 |
'GCONV_PATH', 'LOCPATH', 'NLSPATH', 'HOSTALIASES', |
| 152 |
'PYTHONPATH', 'PYTHONHOME', 'PYTHONSTARTUP', |
| 153 |
'PYTHONEXECUTABLE', |
| 154 |
'BASH_ENV', 'ENV', 'SHELLOPTS', 'BASHOPTS', 'IFS', |
| 155 |
'PERL5LIB', 'PERL5OPT', 'RUBYLIB', 'RUBYOPT', |
| 156 |
'NODE_OPTIONS') |
| 157 |
env = {var: '/tmp/evil' for var in dropped_vars} |
| 158 |
env['PATH'] = '/usr/bin' + os.pathsep + '/tmp/evil' |
| 159 |
env['HOME'] = '/root' |
| 160 |
with mock.patch('os.geteuid', return_value=0, create=True), \ |
| 161 |
mock.patch('bleachbit.General._path_dir_is_root_safe', |
| 162 |
side_effect=lambda d: d == '/usr/bin'): |
| 163 |
result = sanitize_root_env(env) |
| 164 |
self.assertEqual(result['PATH'], '/usr/bin') |
| 165 |
for dropped in dropped_vars: |
| 166 |
self.assertNotIn(dropped, result) |
| 167 |
self.assertEqual(result['HOME'], '/root') |
| 168 |
|
| 169 |
@common.skipIfWindows |
| 170 |
def test_run_external_nowait_sanitizes_env_when_called_directly(self): |
| 171 |
"""run_external_nowait() must sanitize env even when not called via run_external() |
| 172 |
|
| 173 |
Some callers (e.g. GuiApplication's self-restart) call this directly, |
| 174 |
bypassing run_external()'s own sanitize_root_env() call. |
| 175 |
""" |
| 176 |
hostile_env = {'PATH': '/usr/bin' + os.pathsep + '/tmp/evil', |
| 177 |
'LD_PRELOAD': '/tmp/evil.so'} |
| 178 |
captured = {} |
| 179 |
|
| 180 |
def fake_popen(args, **kwargs): |
| 181 |
captured['env'] = kwargs.get('env') |
| 182 |
proc = mock.Mock() |
| 183 |
return proc |
| 184 |
|
| 185 |
with mock.patch('os.geteuid', return_value=0, create=True), \ |
| 186 |
mock.patch('bleachbit.General._path_dir_is_root_safe', |
| 187 |
side_effect=lambda d: d == '/usr/bin'), \ |
| 188 |
mock.patch('bleachbit.General.subprocess.Popen', side_effect=fake_popen): |
| 189 |
run_external_nowait(['/bin/true'], env=hostile_env) |
| 190 |
self.assertNotIn('LD_PRELOAD', captured['env']) |
| 191 |
self.assertEqual(captured['env']['PATH'], '/usr/bin') |
| 192 |
# the caller's own dict must not be mutated in place |
| 193 |
self.assertIn('LD_PRELOAD', hostile_env) |
| 194 |
|
| 195 |
def test_reject_xml_dtd_internal_subset(self): |
| 196 |
"""A DTD with an internal subset is rejected, str or bytes.""" |
| 197 |
xml_text = ('<?xml version="1.0" encoding="UTF-8"?>' |
| 198 |
'<!DOCTYPE r [<!ENTITY x "y">]><r/>') |
| 199 |
with self.assertRaises(ValueError): |
| 200 |
reject_xml_dtd(xml_text) |
| 201 |
with self.assertRaises(ValueError): |
| 202 |
reject_xml_dtd(xml_text.encode('utf-8')) |
| 203 |
|
| 204 |
def test_reject_xml_dtd_str_with_encoding_declaration(self): |
| 205 |
"""pyexpat rejects str input with an encoding declaration; the wrapper must not.""" |
| 206 |
xml_text = ('<?xml version="1.0" encoding="UTF-8"?>' |
| 207 |
'<updates><stable ver="1">https://x</stable></updates>') |
| 208 |
# must not raise |
| 209 |
reject_xml_dtd(xml_text) |
| 210 |
reject_xml_dtd(xml_text.encode('utf-8')) |
| 211 |
reject_xml_dtd(xml_text, 'update XML') |
| 212 |
|
| 213 |
def test_reject_xml_dtd_external_doctype_allowed(self): |
| 214 |
"""An external-only DOCTYPE without internal subset is allowed.""" |
| 215 |
xml_text = ('<?xml version="1.0" encoding="UTF-8"?>' |
| 216 |
'<!DOCTYPE fonts SYSTEM "fonts.dtd"><fonts/>') |
| 217 |
reject_xml_dtd(xml_text) |
| 218 |
|
| 219 |
def test_get_real_uid_non_numeric_sudo_uid(self): |
| 220 |
"""A bogus SUDO_UID must not crash; fall through instead.""" |
| 221 |
if not IS_POSIX: |
| 222 |
self.skipTest('POSIX-only behavior') |
| 223 |
|
| 224 |
with mock.patch.dict(os.environ, {'SUDO_UID': 'not-a-number'}, clear=False): |
| 225 |
with mock.patch('os.getlogin', return_value='root'): |
| 226 |
uid = get_real_uid() |
| 227 |
self.assertIsInstance(uid, int) |
| 228 |
self.assertGreaterEqual(uid, 0) |
| 229 |
|
| 230 |
def test_chownself_root_guard(self): |
| 231 |
"""chownself() must refuse /root and its descendants, including |
| 232 |
via a non-canonical path spelling that a raw substring check |
| 233 |
would miss.""" |
| 234 |
if not IS_POSIX: |
| 235 |
self.skipTest('POSIX-only behavior') |
| 236 |
|
| 237 |
with mock.patch.object(General, 'get_real_uid', return_value=1000), \ |
| 238 |
mock.patch.object(os, 'chown') as mock_chown: |
| 239 |
for path in ('/root', '/root/', '/root/.ssh/authorized_keys', |
| 240 |
'/home/x/../../root', '/home/x/../../root/.bashrc'): |
| 241 |
with self.subTest(path=path): |
| 242 |
chownself(path) |
| 243 |
mock_chown.assert_not_called() |
| 244 |
|
| 245 |
# a sibling directory that merely starts with the string |
| 246 |
# "root" must not be treated as /root |
| 247 |
chownself('/rootlookalike/file') |
| 248 |
mock_chown.assert_called_once() |
| 249 |
mock_chown.reset_mock() |
| 250 |
|
| 251 |
# an ordinary path is still chowned |
| 252 |
chownself('/home/user/file') |
| 253 |
mock_chown.assert_called_once() |
| 254 |
|
| 255 |
@also_with_sudo |
| 256 |
def test_get_real_username(self): |
| 257 |
"""Test for get_real_username()""" |
| 258 |
if not IS_POSIX: |
| 259 |
self.assertRaises(RuntimeError, get_real_username) |
| 260 |
return |
| 261 |
username = get_real_username() |
| 262 |
self.assertIsInstance(username, str) |
| 263 |
self.assertGreater(len(username), 0) |
| 264 |
if sudo_mode(): |
| 265 |
self.assertNotEqual(username, 'root') |
| 266 |
|
| 267 |
def test_get_real_username_container_env_fallback(self): |
| 268 |
"""Ensure container fallback uses LOGNAME when getpass fails.""" |
| 269 |
if not IS_POSIX: |
| 270 |
self.skipTest('POSIX-only behavior') |
| 271 |
|
| 272 |
env = {'LOGNAME': 'containeruser'} |
| 273 |
with mock.patch.dict(os.environ, env, clear=True): |
| 274 |
with mock.patch('os.getlogin', side_effect=OSError('no tty')): |
| 275 |
with mock.patch('getpass.getuser', side_effect=KeyError): |
| 276 |
username = get_real_username() |
| 277 |
self.assertEqual(username, 'containeruser') |
| 278 |
|
| 279 |
def test_get_real_username_container_uid_fallback(self): |
| 280 |
"""Ensure fallback returns UID string when everything else fails.""" |
| 281 |
if not IS_POSIX: |
| 282 |
self.skipTest('POSIX-only behavior') |
| 283 |
|
| 284 |
env = {} |
| 285 |
with mock.patch.dict(os.environ, env, clear=True): |
| 286 |
with mock.patch('os.getlogin', side_effect=OSError('no tty')): |
| 287 |
with mock.patch('getpass.getuser', side_effect=OSError('no user')): |
| 288 |
with mock.patch('os.getuid', return_value=4242): |
| 289 |
username = get_real_username() |
| 290 |
self.assertEqual(username, '4242') |
| 291 |
|
| 292 |
@also_with_sudo |
| 293 |
def test_makedirs(self): |
| 294 |
"""Unit test for makedirs""" |
| 295 |
|
| 296 |
dir = os.path.join(self.tempdir, 'just', 'a', 'directory', 'adventure') |
| 297 |
# directory does not exist |
| 298 |
makedirs(dir) |
| 299 |
self.assertLExists(dir) |
| 300 |
# directory already exists |
| 301 |
makedirs(dir) |
| 302 |
self.assertLExists(dir) |
| 303 |
# clean up |
| 304 |
shutil.rmtree(os.path.join(self.tempdir, 'just')) |
| 305 |
|
| 306 |
def test_run_external(self): |
| 307 |
"""Unit test for run_external""" |
| 308 |
args = {'nt': ['cmd.exe', '/c', 'dir', r'%windir%\system32', '/s', '/b'], |
| 309 |
'posix': ['find', '/usr/bin']} |
| 310 |
(rc, _stdout, stderr) = run_external(args[os.name]) |
| 311 |
self.assertEqual(0, rc) |
| 312 |
self.assertEqual(0, len(stderr)) |
| 313 |
|
| 314 |
@common.skipUnlessWindows |
| 315 |
def test_run_external_quote(self): |
| 316 |
"""Unit test for run_external() with quoted command""" |
| 317 |
tests = [ |
| 318 |
(('cmd.exe', '/c', 'echo "hello world"'), 'hello world'), |
| 319 |
((os.path.expandvars('%windir%\\system32\\ping.exe'), '/?'), 'Usage: ping') |
| 320 |
] |
| 321 |
for args, expected in tests: |
| 322 |
(rc, stdout, stderr) = run_external(args) |
| 323 |
self.assertEqual(0, rc) |
| 324 |
self.assertIn(expected, stdout.strip()) |
| 325 |
self.assertEqual(0, len(stderr)) |
| 326 |
|
| 327 |
def test_run_external_does_not_exist(self): |
| 328 |
"""Unit test for run_external() with non-existent command""" |
| 329 |
self.assertRaises(OSError, run_external, ['cmddoesnotexist']) |
| 330 |
args = {'nt': ['cmd.exe', '/c', 'dir', r'c:\doesnotexist'], |
| 331 |
'posix': ['ls', '/doesnotexist']} |
| 332 |
(rc, _stdout, _stderr) = run_external(args[os.name]) |
| 333 |
self.assertNotEqual(0, rc) |
| 334 |
|
| 335 |
def test_run_external_nowait(self): |
| 336 |
"""Unit test for run_external() with wait=False""" |
| 337 |
with warnings.catch_warnings(record=True): |
| 338 |
warnings.simplefilter("error") |
| 339 |
|
| 340 |
output_file = os.path.join(self.tempdir, 'run_external_nowait.txt') |
| 341 |
|
| 342 |
cmd = [ |
| 343 |
sys.executable, |
| 344 |
'-c', |
| 345 |
( |
| 346 |
'import pathlib, sys, time; ' |
| 347 |
'time.sleep(2); ' |
| 348 |
'pathlib.Path(sys.argv[1]).write_text(' |
| 349 |
'"done", encoding="utf-8")' |
| 350 |
), |
| 351 |
output_file, |
| 352 |
] |
| 353 |
|
| 354 |
self.assertNotExists(output_file) |
| 355 |
|
| 356 |
(rc, stdout, stderr) = run_external(cmd, wait=False) |
| 357 |
self.assertEqual(0, rc) |
| 358 |
self.assertEqual(0, len(stdout)) |
| 359 |
self.assertEqual(0, len(stderr)) |
| 360 |
|
| 361 |
self.assertNotExists(output_file) |
| 362 |
|
| 363 |
for _ in range(200): |
| 364 |
if os.path.exists(output_file): |
| 365 |
break |
| 366 |
time.sleep(0.1) |
| 367 |
self.assertExists(output_file) |
| 368 |
|
| 369 |
@common.skipUnlessWindows |
| 370 |
def test_run_external_nowait_no_kwargs(self): |
| 371 |
"""Test run_external_nowait with kwargs=None""" |
| 372 |
cmd = ['cmd.exe', '/c', 'exit', '0'] |
| 373 |
result = run_external_nowait(cmd) |
| 374 |
self.assertTrue(result) |
| 375 |
|
| 376 |
def test_run_external_command_completion(self): |
| 377 |
"""Test that run_external() commands complete successfully""" |
| 378 |
with warnings.catch_warnings(record=True): |
| 379 |
# Any warning is an error. |
| 380 |
warnings.simplefilter("error") |
| 381 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 382 |
test_file = os.path.join(temp_dir, 'test_file.txt') |
| 383 |
|
| 384 |
if IS_POSIX: |
| 385 |
cmd = ['touch', test_file] |
| 386 |
expected_stdout = '' |
| 387 |
else: |
| 388 |
cmd = ['cmd.exe', '/c', 'copy', 'nul', test_file] |
| 389 |
expected_stdout = '1 file(s) copied.' |
| 390 |
|
| 391 |
# Wait for the command to complete. |
| 392 |
(rc, stdout, stderr) = run_external(cmd, timeout=5) |
| 393 |
self.assertEqual(0, rc, stderr) |
| 394 |
self.assertEqual('', stderr) |
| 395 |
self.assertEqual(expected_stdout, stdout.strip()) |
| 396 |
self.assertExists(test_file) |
| 397 |
|
| 398 |
os.unlink(test_file) |
| 399 |
self.assertNotExists(test_file) |
| 400 |
|
| 401 |
# Test with wait=False |
| 402 |
(rc, stdout, stderr) = run_external(cmd, wait=False, timeout=5) |
| 403 |
|
| 404 |
self.assertEqual(0, rc) |
| 405 |
self.assertEqual('', stdout) |
| 406 |
self.assertEqual('', stderr) |
| 407 |
# Poll for file creation. Touch normally completes in milliseconds, |
| 408 |
# so one second is plenty. |
| 409 |
for _ in range(100): |
| 410 |
if os.path.exists(test_file): |
| 411 |
break |
| 412 |
time.sleep(0.01) |
| 413 |
self.assertExists(test_file) |
| 414 |
|
| 415 |
def test_run_external_with_timeout_failure(self): |
| 416 |
"""Test run_external() with timeout value that is too short""" |
| 417 |
if IS_POSIX: |
| 418 |
args = ['sleep', '5'] |
| 419 |
else: |
| 420 |
args = ['ping', '-n', '10', '127.0.0.1'] |
| 421 |
with self.assertRaises(subprocess.TimeoutExpired): |
| 422 |
run_external(args, timeout=1) |
| 423 |
|
| 424 |
def test_run_external_stdout(self): |
| 425 |
"""Test that run_external properly captures stdout""" |
| 426 |
if IS_POSIX: |
| 427 |
args = ['echo', 'test output'] |
| 428 |
else: |
| 429 |
args = ['cmd.exe', '/c', 'echo test output'] |
| 430 |
(rc, stdout, stderr) = run_external(args) |
| 431 |
self.assertEqual(0, rc) |
| 432 |
self.assertIn('test output', stdout) |
| 433 |
self.assertEqual('', stderr) |
| 434 |
|
| 435 |
def test_run_external_stderr(self): |
| 436 |
"""Test that run_external properly captures stderr""" |
| 437 |
if IS_POSIX: |
| 438 |
args = ['sh', '-c', 'echo "error message" >&2'] |
| 439 |
else: |
| 440 |
args = ['cmd.exe', '/c', 'echo error message 1>&2'] |
| 441 |
(rc, stdout, stderr) = run_external(args) |
| 442 |
self.assertEqual(0, rc) |
| 443 |
self.assertEqual('', stdout) |
| 444 |
self.assertIn('error message', stderr) |
| 445 |
|
| 446 |
def test_run_external_return_codes(self): |
| 447 |
"""Test that run_external() properly returns non-zero exit codes""" |
| 448 |
if IS_POSIX: |
| 449 |
args = ['false'] |
| 450 |
else: |
| 451 |
args = ['cmd.exe', '/c', 'exit 1'] |
| 452 |
(rc, _, _) = run_external(args) |
| 453 |
self.assertEqual(1, rc) |
| 454 |
|
| 455 |
@common.skipIfWindows |
| 456 |
def test_run_external_clean_env(self): |
| 457 |
"""Unit test for clean_env parameter to run_external()""" |
| 458 |
|
| 459 |
def run(args, clean_env): |
| 460 |
(rc, stdout, _stderr) = run_external(args, clean_env=clean_env) |
| 461 |
self.assertEqual(rc, 0) |
| 462 |
return stdout.rstrip('\n') |
| 463 |
|
| 464 |
# clean_env should set language to C |
| 465 |
run(['sh', '-c', '[ "x$LANG" = "xC" ]'], clean_env=True) |
| 466 |
run(['sh', '-c', '[ "x$LC_ALL" = "xC" ]'], clean_env=True) |
| 467 |
|
| 468 |
# clean_env parameter should not alter the PATH, and the PATH |
| 469 |
# should not be empty |
| 470 |
path_clean = run(['bash', '-c', 'echo $PATH'], clean_env=True) |
| 471 |
if os.getenv('PATH'): |
| 472 |
self.assertEqual(common.get_env('PATH'), path_clean) |
| 473 |
self.assertGreater(len(path_clean), 10) |
| 474 |
|
| 475 |
path_unclean = run(['bash', '-c', 'echo $PATH'], clean_env=False) |
| 476 |
self.assertEqual(path_clean, path_unclean) |
| 477 |
|
| 478 |
# With parent environment set to English and parameter clean_env=False, |
| 479 |
# expect English |
| 480 |
with common.set_temporary_env('LC_ALL', 'C'): |
| 481 |
(rc, _, stderr) = run_external( |
| 482 |
['ls', '/doesnotexist'], clean_env=False) |
| 483 |
# GNU ls returns 2 for missing files, while BSD/macOS ls returns 1 |
| 484 |
self.assertIn( |
| 485 |
rc, (1, 2), 'ls /doesnotexist returned exit code %s' % rc) |
| 486 |
self.assertIn('No such file', stderr) |
| 487 |
|
| 488 |
# Set parent environment to Spanish. |
| 489 |
with common.set_temporary_env('LC_ALL', 'es_MX.UTF-8'): |
| 490 |
(rc, _, stderr) = run_external( |
| 491 |
['ls', '/doesnotexist'], clean_env=False) |
| 492 |
self.assertIn( |
| 493 |
rc, (1, 2), 'ls /doesnotexist returned exit code %s' % rc) |
| 494 |
if os.path.exists('/usr/share/locale-langpack/es/LC_MESSAGES/coreutils.mo'): |
| 495 |
# Spanish language pack is installed. |
| 496 |
self.assertIn('No existe el archivo', stderr) |
| 497 |
|
| 498 |
# Here the parent environment has Spanish, but the child process |
| 499 |
# should use English. |
| 500 |
(rc, _, stderr) = run_external( |
| 501 |
['ls', '/doesnotexist'], clean_env=True) |
| 502 |
self.assertIn( |
| 503 |
rc, (1, 2), 'ls /doesnotexist returned exit code %s' % rc) |
| 504 |
self.assertIn('No such file', stderr) |
| 505 |
|
| 506 |
def test_run_external_invalid(self): |
| 507 |
"""Unit test for run_external() with invalid arguments""" |
| 508 |
with self.assertRaises(AssertionError): |
| 509 |
run_external(None) |
| 510 |
with self.assertRaises(AssertionError): |
| 511 |
run_external('foo') |
| 512 |
with self.assertRaises(ValueError): |
| 513 |
run_external([None, 'foo']) |
| 514 |
with self.assertRaises(ValueError): |
| 515 |
run_external(['hello', None]) |
| 516 |
with self.assertRaises(ValueError): |
| 517 |
run_external(['']) |
| 518 |
with self.assertRaises(AssertionError): |
| 519 |
run_external([]) |
| 520 |
|
| 521 |
def test_run_external_timeout(self): |
| 522 |
"""Unit test for run_external() with timeout""" |
| 523 |
args = None |
| 524 |
if IS_POSIX: |
| 525 |
args = ['sleep', '10'] |
| 526 |
if IS_WINDOWS: |
| 527 |
args = ['ping', '-n', '10', '127.0.0.1'] |
| 528 |
start_time = time.time() |
| 529 |
with self.assertRaises(subprocess.TimeoutExpired): |
| 530 |
run_external(args, timeout=1) |
| 531 |
elapsed_time = time.time() - start_time |
| 532 |
self.assertLess(elapsed_time, 2) |
| 533 |
|
| 534 |
@common.skipIfWindows |
| 535 |
def test_dconf(self): |
| 536 |
"""Unit test for dconf""" |
| 537 |
if not exists_in_path('dconf'): |
| 538 |
self.skipTest('dconf not found') |
| 539 |
if sudo_mode(): |
| 540 |
self.skipTest('dconf not supported in sudo mode') |
| 541 |
# pylint: disable=import-outside-toplevel |
| 542 |
from bleachbit.GtkShim import is_gtk_available |
| 543 |
if not is_gtk_available(): |
| 544 |
self.skipTest('dconf not supported without GUI') |
| 545 |
args = ['dconf', 'write', |
| 546 |
'/apps/bleachbit/test', 'true'] |
| 547 |
(rc, stdout, stderr) = run_external(args) |
| 548 |
self.assertEqual(0, rc, stderr) |
| 549 |
self.assertEqual('', stderr) |
| 550 |
self.assertEqual('', stdout) |
| 551 |
|
| 552 |
def test_shell_split(self): |
| 553 |
"""Unit test for shell_split()""" |
| 554 |
tests = [('', []), |
| 555 |
('a', ['a']), |
| 556 |
('a b', ['a', 'b']) |
| 557 |
] |
| 558 |
if IS_WINDOWS: |
| 559 |
tests.append(('"a b"', ['a b'])) |
| 560 |
tests.append(('"a b" c', ['a b', 'c'])) |
| 561 |
tests.append(("echo 'a b'", ['echo', "'a b'"])) |
| 562 |
tests.append(('echo a\\ b', ['echo', 'a\\', 'b'])) |
| 563 |
elif IS_POSIX: |
| 564 |
tests.append(("echo 'a b'", ['echo', 'a b'])) |
| 565 |
tests.append(("echo 'a b' c", ['echo', 'a b', 'c'])) |
| 566 |
tests.append(('echo a\\ b', ['echo', 'a b'])) |
| 567 |
for test in tests: |
| 568 |
self.assertEqual(test[1], shell_split(test[0])) |
| 569 |
|
| 570 |
@common.skipIfWindows |
| 571 |
@also_with_sudo |
| 572 |
def test_sudo_mode(self): |
| 573 |
"""Unit test for sudo_mode""" |
| 574 |
self.assertIsInstance(sudo_mode(), bool) |