Debian Codegraph @

tests/TestExternalCommand.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (c) 2008-2026 Andrew Ziem.
3 #
4 # This work is licensed under the terms of the GNU GPL, version 3 or
5 # later. See the COPYING file in the top-level directory.
6
7
8 """
9 Test case for the context menu command
10 """
11
12
13 import os
14 import sys
15 import subprocess
16 import time
17 from contextlib import suppress
18 from unittest import mock
19
20 import psutil
21
22 from tests.common import pytest
23
24 import bleachbit
25 from bleachbit import IS_WINDOWS
26 from bleachbit.GtkShim import is_gtk_available
27 from bleachbit.Options import options
28 from tests import common
29
30 HAVE_GTK = is_gtk_available()
31 if HAVE_GTK:
32 from bleachbit.GuiApplication import Bleachbit
33
34
35 START_TIMEOUT_SECONDS = 20
36 MAX_PATH_DISPLAY = 200
37
38
39 def is_bleachbit_running_process(process_name, cmdline):
40 """Return whether process_name/cmdline represent a running BleachBit GUI/context process."""
41 assert isinstance(process_name, str)
42 assert isinstance(cmdline, list)
43 name_lower = (process_name or '').lower()
44 normalized_cmdline = [str(arg).lower() for arg in (cmdline or [])]
45 cmdline_str = ' '.join(normalized_cmdline)
46
47 image_is_python = name_lower.startswith('python')
48 # With subprocess shell=True, process image is cmd.exe instead of python.
49 image_is_cmd = name_lower in ('cmd.exe', 'cmd')
50 launches_python = 'python.exe' in cmdline_str or 'python3' in cmdline_str
51 if not (image_is_python or (image_is_cmd and launches_python)):
52 return False
53
54 has_bleachbit_entrypoint = any(
55 'bleachbit.py' in arg
56 for arg in normalized_cmdline
57 )
58 has_context_arg = any(
59 '--context-menu' in arg or '--gui' in arg for arg in normalized_cmdline)
60 return has_bleachbit_entrypoint and has_context_arg
61
62
63 def wait_for_process_tree_windows(process, timeout=60, poll_interval=0.1):
64 """Wait for a process and its grandchildren to complete on Windows.
65
66 This function handles the case where a child process spawns a grandchild
67 and then exits. It monitors the process tree to ensure all descendants
68 have completed before returning.
69
70 Args:
71 process: subprocess.Popen object for the child process
72 timeout: Maximum time to wait in seconds (default: 60)
73 poll_interval: How often to check process status in seconds (default: 0.1)
74
75 Returns:
76 The return code of the child process
77
78 Raises:
79 subprocess.TimeoutExpired: If the process tree doesn't complete within timeout
80 """
81
82 start_time = time.time()
83 child_pid = process.pid
84 grandchild_pids = set()
85 child_exited = False
86
87 while True:
88 elapsed = time.time() - start_time
89 if elapsed > timeout:
90 process.kill()
91 process.wait()
92 raise subprocess.TimeoutExpired(process.args, timeout)
93
94 if not child_exited:
95 child_status = process.poll()
96 if child_status is not None:
97 child_exited = True
98 else:
99 with suppress(psutil.NoSuchProcess, psutil.AccessDenied):
100 parent_process = psutil.Process(child_pid)
101 current_children = {
102 child.pid for child in parent_process.children(recursive=True)}
103 grandchild_pids.update(current_children)
104
105 if child_exited:
106 if not grandchild_pids:
107 return process.returncode
108
109 still_running = set()
110 for pid in grandchild_pids:
111 with suppress(psutil.NoSuchProcess, psutil.AccessDenied):
112 if psutil.pid_exists(pid):
113 proc = psutil.Process(pid)
114 if proc.is_running() and proc.status() != psutil.STATUS_ZOMBIE:
115 still_running.add(pid)
116
117 grandchild_pids = still_running
118 if not grandchild_pids:
119 return process.returncode
120
121 time.sleep(poll_interval)
122
123
124 class ApplicationRunningTracker:
125 """Tracks processes and window titles during application run detection"""
126
127 def __init__(self, check_window_title=False, timeout=0):
128 self.check_window_title = check_window_title
129 self.timeout = timeout
130 self.seen_processes = set()
131 self.seen_window_titles = set()
132 self.elapsed_time = None
133 # This search is more broader than criteria for whether application
134 # is running, in case the other criteria is too strict.
135 self.candidate_search = ['bleach', 'python']
136
137 def _check_application_state(self):
138 """Check current application state without timeout logic.
139
140 Returns tuple (is_running, window_open) where:
141 - is_running: True if bleachbit process found
142 - window_open: True if bleachbit window found (Windows only)
143 """
144 is_process_running = False
145 window_open = False
146
147 for process in psutil.process_iter(['name', 'cmdline']):
148 with suppress(psutil.NoSuchProcess, psutil.AccessDenied):
149 name = process.info['name'] or ''
150 cmdline = process.info['cmdline'] or []
151 name_and_cmdline = f"{name}: {' '.join(cmdline)[:MAX_PATH_DISPLAY]}"
152
153 # Track all interesting processes
154 for candidate in self.candidate_search:
155 if candidate in name_and_cmdline.lower():
156 self.seen_processes.add(name_and_cmdline)
157
158 if is_bleachbit_running_process(name, cmdline):
159 is_process_running = True
160
161 # Check window titles on Windows
162 if IS_WINDOWS and self.check_window_title:
163 opened_windows_titles = common.get_opened_windows_titles()
164 window_open = any(
165 'BleachBit' == window_title for window_title in opened_windows_titles)
166
167 for window_title in opened_windows_titles:
168 for candidate in self.candidate_search:
169 if candidate in window_title.lower():
170 self.seen_window_titles.add(window_title)
171 break
172
173 return is_process_running, window_open
174
175 def _is_running_based_on_checks(self, is_process_running, window_open):
176 """Determine if application is running based on check_window_title setting."""
177 if self.check_window_title and IS_WINDOWS:
178 return is_process_running and window_open
179 return is_process_running or window_open
180
181 def is_application_running(self, expect_running=True):
182 """Check if the application is running with optional timeout polling.
183
184 Args:
185 expect_running: If True, poll until timeout waiting for app to start.
186 If False, return immediately.
187
188 Returns:
189 bool: True if application is running, False otherwise
190 """
191 if expect_running and self.timeout > 0:
192 start_time = time.time()
193 while True:
194 is_process_running, window_open = self._check_application_state()
195 if self._is_running_based_on_checks(is_process_running, window_open):
196 return True
197 self.elapsed_time = time.time() - start_time
198 if self.elapsed_time >= self.timeout:
199 return False
200 # Add safety check to prevent infinite loops
201 if self.elapsed_time > self.timeout + 5: # Extra safety margin
202 return False
203 time.sleep(0.1)
204 else:
205 is_process_running, window_open = self._check_application_state()
206 return self._is_running_based_on_checks(is_process_running, window_open)
207
208 def not_running_msg(self):
209 """Returns a string with diagnostic information
210
211 Returns
212 - count of window titles
213 - list of potential matches for window titles (including those seen earlier)
214 - count of processes running
215 - list of potential matches for processes (including those seen earlier)
216 - check_window_title
217 - timeout limit
218 - time elapsed waiting
219 """
220 window_title_str = ""
221 if IS_WINDOWS and self.check_window_title:
222 opened_window_titles = common.get_opened_windows_titles()
223 window_title_count = len(opened_window_titles)
224 interesting_window_titles = []
225
226 # Include currently seen interesting titles
227 for window_title in opened_window_titles:
228 for candidate in self.candidate_search:
229 if candidate in window_title.lower():
230 interesting_window_titles.append(window_title)
231 break
232
233 # Also include titles we saw earlier but don't see now
234 missing_titles = self.seen_window_titles - \
235 set(opened_window_titles)
236 if missing_titles:
237 interesting_window_titles.extend(
238 [f"[PREVIOUSLY SEEN] {title}" for title in missing_titles])
239
240 window_title_str = f"currently {window_title_count} window titles, interesting:\n" + \
241 "\n".join(
242 f" - {title}" for title in interesting_window_titles)
243
244 interesting_processes = []
245 process_count = 0
246 current_processes = set()
247
248 for process in psutil.process_iter(['name', 'cmdline']):
249 process_count += 1
250 name = process.info['name'] or ''
251 cmdline = process.info['cmdline'] or []
252 name_and_cmdline = f"{name}: {' '.join(cmdline)[:MAX_PATH_DISPLAY]}"
253 current_processes.add(name_and_cmdline)
254
255 for candidate in self.candidate_search:
256 if candidate in name_and_cmdline.lower():
257 interesting_processes.append(name_and_cmdline)
258 break
259
260 # Also include processes we saw earlier but don't see now
261 missing_processes = self.seen_processes - current_processes
262 if missing_processes:
263 interesting_processes.extend(
264 [f"[PREVIOUSLY SEEN] {proc}" for proc in missing_processes])
265
266 process_str = f"currently {process_count} processes, interesting:\n" + \
267 "\n".join(f" - {proc}" for proc in interesting_processes)
268
269 return f"{window_title_str}\n{process_str}" \
270 f"\ncheck_window_title: {self.check_window_title}" \
271 f"\ntimeout: {self.timeout}" \
272 f"\ntime elapsed: {round(self.elapsed_time, 2)}"
273
274
275 @pytest.mark.xdist_group('gui')
276 class ExternalCommandTestCase(common.BleachbitTestCase):
277 """Test case for the context menu command"""
278
279 @classmethod
280 def setUpClass(cls):
281 """Set up the test case"""
282 cls.old_language = common.get_env('LANGUAGE')
283 cls._lang_env = common.set_temporary_env('LANGUAGE', 'en')
284 cls._lang_env.__enter__()
285 super().setUpClass()
286 cls._test_options_env = None
287 # override, not a committed set: never hits the shared file, so it
288 # can't leak to other tests (subprocesses get --no-delete-confirmation)
289 options.set_override('delete_confirmation', False)
290 if 'BLEACHBIT_TEST_OPTIONS_DIR' not in os.environ:
291 # Set environment variable for child process.
292 cls._test_options_env = common.set_temporary_env(
293 'BLEACHBIT_TEST_OPTIONS_DIR', cls.tempdir)
294 cls._test_options_env.__enter__()
295
296 @classmethod
297 def tearDownClass(cls):
298 """Tear down the test case"""
299 if cls._test_options_env:
300 cls._test_options_env.__exit__(None, None, None)
301 cls._lang_env.__exit__(None, None, None)
302 super().tearDownClass()
303
304 def assertRunning(self, expect_running=True, check_window_title=True, timeout=START_TIMEOUT_SECONDS):
305 """Assert whether BleachBit GUI processes are running or not
306
307 Args:
308 expect_running: If True (default), assert that processes ARE running.
309 If False, assert that processes are NOT running.
310 check_window_title: Whether to also check for window title (Windows only)
311 timeout: Maximum time to wait for process to be running (only used when expect_running=True)
312 """
313 tracker = ApplicationRunningTracker(
314 check_window_title=check_window_title,
315 timeout=timeout if expect_running else 0
316 )
317 is_running = tracker.is_application_running(
318 expect_running=expect_running)
319
320 if expect_running and not is_running:
321 self.fail(
322 f"Expected BleachBit GUI process to be running, but none found\n{tracker.not_running_msg()}")
323 elif not expect_running and is_running:
324 self.fail("BleachBit GUI process is still running")
325
326 def _context_helper(self, fn_prefix, allow_opened_window=False):
327 """Unit test for 'Shred with BleachBit' Windows Explorer context menu command
328
329 Called from
330 - test_windows_explorer_context_menu_natural
331 - test_context_menu_command_while_the_app_is_running
332
333 This test is more likely an integration test as it imitates user behavior.
334 It could be interpreted as TestCLI->test_gui_no-uac_shred_exit
335 but it is more explicit to have it here as a separate case.
336 It covers a single case where one file is shred without delete confirmation dialog.
337 """
338
339 file_to_shred = self.mkstemp(prefix=fn_prefix)
340 self.assertExists(file_to_shred)
341 if not allow_opened_window:
342 self.assertRunning(False)
343 shred_command_string = self._get_shred_command_string(file_to_shred)
344 self._run_shred_command(shred_command_string,
345 cwd=bleachbit.bleachbit_exe_path)
346 self.assertNotExists(file_to_shred)
347
348 if not allow_opened_window:
349 self.assertRunning(False)
350
351 def _get_shred_command_string(self, file_to_shred):
352 """Build the command string like the context menu command"""
353 shred_command_string = (
354 # Disable confirmation for automated tests.
355 f'{sys.executable} bleachbit.py --no-delete-confirmation --no-first-start '
356 f'--context-menu "{file_to_shred}"' # The pathname must be last.
357 )
358 return shred_command_string
359
360 def _run_shred_command(self, shred_command_string, cwd=None):
361 """Run the shred command
362
363 In case of privilege escalation, the child process
364 will launch an elevated process, so the child will exit.
365 We must wait for the grandchild to finish.
366 """
367 process = subprocess.Popen(shred_command_string,
368 shell=True, cwd=cwd)
369 try:
370 # It may close too quickly to detect the window title.
371 self.assertRunning(check_window_title=False)
372 returncode = wait_for_process_tree_windows(process, timeout=60)
373 except subprocess.TimeoutExpired:
374 process.kill()
375 process.wait()
376 self.fail("Shred command timed out")
377 finally:
378 # Ensure process is cleaned up to avoid ResourceWarning
379 if process.poll() is None:
380 process.kill()
381 process.wait()
382 self.assertEqual(
383 returncode, 0, f"Shred command failed with return code {returncode}")
384
385 def test_windows_explorer_context_menu_natural(self):
386 """Test shredding a file with the context menu command in a natural way"""
387 # First, test the simple case of a pathname without embedded spaces.
388 # Then, test a pathname with a space.
389 self.assertRunning(False)
390 if not HAVE_GTK:
391 self.skipTest('GTK is not available')
392 for fn_prefix in ('shred_target_no_spaces', 'shred target with spaces'):
393 self._context_helper(fn_prefix)
394 self.assertRunning(False)
395
396 @common.skipUnlessWindows
397 def test_windows_explorer_context_menu_privilege_escalation(self):
398 """Test shredding a file with the context menu command with privilege escalation"""
399 if bleachbit.Windows.path_on_network(bleachbit.bleachbit_exe_path):
400 self.skipTest('Escalation is not attempted on network paths.')
401 if not HAVE_GTK:
402 self.skipTest('GTK is not available')
403 self.assertRunning(False)
404 for fn_prefix in ('shred_target_no_spaces', 'shred target with spaces'):
405 self._test_as_non_admin_with_context_menu_path(fn_prefix)
406 self.assertRunning(False)
407
408 @common.skipUnlessWindows
409 def test_context_menu_command_while_the_app_is_running(self):
410 """Test the context menu command while the application is running"""
411 self.assertRunning(False)
412 if not HAVE_GTK:
413 self.skipTest('GTK is not available')
414 # Start an idle process that will keep running.
415 # The --no-uac flag prevents launching grandchild process.
416 # The --no-load-cleaners makes it faster.
417 args = [sys.executable, 'bleachbit.py',
418 '--gui', '--no-load-cleaners', '--no-check-online-updates', '--no-uac']
419 p = subprocess.Popen(args, shell=False)
420 try:
421 # Let the first process start up before launching the second process.
422 self.assertRunning(check_window_title=True)
423 try:
424 # Run a second process that will shred a file.
425 self._context_helper('while_app_is_running',
426 allow_opened_window=True)
427 finally:
428 self.assertRunning()
429 finally:
430 # Ensure the process is always killed, even if assertions fail
431 if p.poll() is None: # Check if process is still running
432 p.kill()
433 p.wait()
434 self.assertRunning(False)
435
436 def _test_as_non_admin_with_context_menu_path(self, fn_prefix):
437 """
438 This tests covers elevate_privileges in the case where we pretend that we are not admin.
439 """
440 self.assertTrue(IS_WINDOWS)
441 file_to_shred = self.mkstemp(prefix=fn_prefix)
442 self.assertExists(file_to_shred)
443
444 original = bleachbit.Windows.shell.ShellExecuteEx
445
446 def shell_execute_synchronous(lpVerb='', lpFile='', lpParameters='', nShow=''):
447 """
448 We need a synchronous call the ShellExecuteEx, so we can assert after it finishes.
449 """
450 from win32com.shell import shell, shellcon
451 import win32event
452 import win32file
453 bleachbit.Windows.shell.ShellExecuteEx = original
454 rc = shell.ShellExecuteEx(lpVerb=lpVerb,
455 lpFile=lpFile,
456 lpParameters=lpParameters,
457 nShow=nShow,
458 fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
459 )
460 hproc = rc['hProcess']
461 win32event.WaitForSingleObject(hproc, win32event.INFINITE)
462 # Close the process handle to prevent ResourceWarning
463 win32file.CloseHandle(hproc)
464 return rc
465
466 # We redirect the ShellExecuteEx call like this because if we do it in a mock we enter recursion
467 # because we call ShellExecuteEx in shell_execute_synchronous
468 bleachbit.Windows.shell.ShellExecuteEx = shell_execute_synchronous
469 with mock.patch('bleachbit.Windows.shell.IsUserAnAdmin', return_value=False):
470 # Do not actually exit the process during the test.
471 with mock.patch('bleachbit.GuiApplication.sys.exit'):
472 # Mock the command line arguments to be inherited to the child process.
473 custom_argv = [
474 'dummy-arg',
475 '--no-delete-confirmation',
476 '--context-menu',
477 file_to_shred, # The pathname must be last
478 ]
479 with mock.patch('bleachbit.Windows.sys.argv', custom_argv):
480 Bleachbit(auto_exit=True, shred_paths=[
481 file_to_shred], uac=True)
482
483 self.assertNotExists(file_to_shred)
484
485 def test_is_bleachbit_running_process(self):
486 """Test process-matching helper without depending on live processes."""
487 # Path as seen in CI
488 py_dir = r'C:\\projects\\bleachbit\\vcpkg_installed\\x86-windows\\tools\\python3\\'
489 py_exe = os.path.join(py_dir, 'python.exe')
490 tests = (
491 # Test runner.
492 (False, 'python.exe',
493 [
494 py_exe,
495 os.path.join(py_dir, 'coverage.exe'),
496 'run',
497 '--include=bleachbit/*',
498 '-m',
499 'tests.TestAll',
500 ]
501 ),
502 # D-Bus session bus.
503 (False, 'gdbus.exe',
504 [os.path.join(py_dir, 'gdbus.exe'), '_win32_run_session_bus']
505 ),
506 # This is the cleaning process.
507 (True, 'cmd.exe',
508 [
509 'C:\\Windows\\system32\\cmd.exe',
510 '/c',
511 py_exe,
512 'bleachbit.py',
513 '--no-delete-confirmation',
514 '--no-first-start',
515 '--context-menu' # followed by a pathname to delete
516 ]
517 ),
518 # This is the cleaning process as seen in CI with shell=True where arguments are grouped.
519 (True, 'cmd.exe',
520 [
521 'C:\\Windows\\system32\\cmd.exe',
522 '/c',
523 f'{py_exe} bleachbit.py --no-delete-confirmation --no-first-start --context-menu C:\\Users\\runneradmin\\AppData'
524 ]
525 ),
526 # This is the idle process.
527 (True, 'python.exe',
528 [py_exe, 'bleachbit.py', '--gui', '--no-load-cleaners',
529 '--no-check-online-updates', '--no-uac']
530 ),
531 )
532 for expected, process_name, cmdline in tests:
533 self.assertEqual(
534 expected,
535 is_bleachbit_running_process(process_name, cmdline)
536 )
537
538 def test_wait_for_grandchild_process(self):
539 """Test that wait_for_process_tree_windows waits for grandchild processes"""
540 marker_file = self.mkstemp(prefix='grandchild_marker_')
541 os.remove(marker_file)
542 self.assertNotExists(marker_file)
543
544 grandchild_script = os.path.join(self.tempdir, 'grandchild.py')
545 with open(grandchild_script, 'w', encoding='utf-8') as f:
546 f.write(f'''import time
547 import sys
548 time.sleep(2)
549 with open({repr(marker_file)}, "w") as f:
550 f.write("grandchild completed")
551 sys.exit(0)
552 ''')
553
554 child_script = os.path.join(self.tempdir, 'child.py')
555 with open(child_script, 'w', encoding='utf-8') as f:
556 f.write(f'''import subprocess
557 import sys
558 import time
559 p = subprocess.Popen([sys.executable, {repr(grandchild_script)}])
560 time.sleep(0.5)
561 p.wait()
562 sys.exit(0)
563 ''')
564
565 process = subprocess.Popen([sys.executable, child_script])
566
567 start_time = time.time()
568 returncode = wait_for_process_tree_windows(process, timeout=10)
569 elapsed = time.time() - start_time
570
571 self.assertEqual(returncode, 0)
572 self.assertExists(marker_file)
573 self.assertGreater(elapsed, 1.5)