Debian Codegraph @

tests/TestProcess.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 Test case for the module Process
9 """
10 import os
11 import sys
12 from unittest import mock
13
14 # While POSIX systems may not always have psutil,
15 # the test environment (and Windows) always should have it.
16 import psutil
17
18 from bleachbit import IS_WINDOWS
19 from bleachbit.General import get_real_username, resolve_exe, sudo_mode
20 from bleachbit.Process import (
21 _enumerate_proc_fs,
22 _enumerate_ps_aux,
23 enumerate_processes,
24 is_process_running,
25 ProcessInfo,
26 )
27 from tests import common
28
29
30 class ProcessTestCase(common.BleachbitTestCase):
31
32 def test_enumerate_processes(self):
33 """Test enumerate_processes()"""
34 # FIXME: also check the private functions like _enumerate_proc_fs
35 processes = list(enumerate_processes())
36 self.assertGreater(len(processes), 0)
37
38 for proc in processes:
39 self.assertIsInstance(proc, ProcessInfo)
40 self.assertIsInstance(proc.pid, int)
41 self.assertGreaterEqual(proc.pid, 0, proc)
42 self.assertIsInstance(proc.name, str)
43 self.assertGreater(len(proc.name), 0)
44 self.assertIsInstance(proc.same_user, bool)
45
46 @mock.patch('subprocess.check_output')
47 @common.skipIfWindows
48 @common.also_with_sudo
49 def test_enumerate_ps_aux(self, mock_check_output):
50 username = get_real_username()
51 ps_out = f"""USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
52 root 703 0.0 0.0 2471428 2792 ?? Ss 20May16 0:01.30 SubmitDiagInfo
53 alocaluseraccount 681 0.0 0.0 2471568 856 ?? S 20May16 0:00.81 DiskUnmountWatcher
54 alocaluseraccount 666 0.0 0.0 2507092 3488 ?? S 20May16 0:17.47 SpotlightNetHelper
55 root 665 0.0 0.0 2497508 512 ?? Ss 20May16 0:11.30 check_afp
56 alocaluseraccount 646 0.0 0.1 2502484 5656 ?? S 20May16 0:03.62 DataDetectorsDynamicData
57 alocaluseraccount 632 0.0 0.0 2471288 320 ?? S 20May16 0:02.79 mdflagwriter
58 alocaluseraccount 616 0.0 0.0 2497596 520 ?? S 20May16 0:00.41 familycircled
59 alocaluseraccount 573 0.0 0.0 3602328 2440 ?? S 20May16 0:39.64 storedownloadd
60 alocaluseraccount 572 0.0 0.0 2531184 3116 ?? S 20May16 0:02.93 LaterAgent
61 {username} 561 0.0 0.0 2471492 584 ?? S 20May16 0:00.21 USBAgent
62 alocaluseraccount 535 0.0 0.0 2496656 524 ?? S 20May16 0:00.33 storelegacy
63 root 531 0.0 0.0 2501712 588 ?? Ss 20May16 0:02.40 suhelperd
64 alocaluseraccount 530 0.0 0.0 2496700 530 ?? S 20May16 0:04.44 Google Chrome Helper
65 """
66 mock_check_output.return_value = ps_out
67
68 result = list(_enumerate_ps_aux())
69 expected = [
70 ProcessInfo(703, 'SubmitDiagInfo', False),
71 ProcessInfo(681, 'DiskUnmountWatcher', False),
72 ProcessInfo(666, 'SpotlightNetHelper', False),
73 ProcessInfo(665, 'check_afp', False),
74 ProcessInfo(646, 'DataDetectorsDynamicData', False),
75 ProcessInfo(632, 'mdflagwriter', False),
76 ProcessInfo(616, 'familycircled', False),
77 ProcessInfo(573, 'storedownloadd', False),
78 ProcessInfo(572, 'LaterAgent', False),
79 ProcessInfo(561, 'USBAgent', True),
80 ProcessInfo(535, 'storelegacy', False),
81 ProcessInfo(531, 'suhelperd', False),
82 ProcessInfo(530, 'Google Chrome Helper', False),
83 ]
84 self.assertEqual(result, expected)
85 mock_check_output.assert_called_once()
86 call = mock_check_output.call_args
87 self.assertEqual(call.args[0], [resolve_exe('ps'), 'aux', '-c'])
88 self.assertTrue(call.kwargs.get('universal_newlines'))
89 # the child's env is sanitized (LD_*/DYLD_* dropped when root)
90 self.assertIn('env', call.kwargs)
91
92 mock_check_output.return_value = 'invalid-input'
93 with self.assertRaises(RuntimeError):
94 list(_enumerate_ps_aux())
95
96 @common.skipUnlessLinux
97 def test_enumerate_proc_fs_comm_with_spaces(self):
98 """/proc fallback keeps a comm field with spaces intact"""
99 stat_line = "1234 (Web Content) S 1 1234 1234 0 -1 4194304 0 0 0 0"
100
101 def fake_open(path, *args, **kwargs):
102 if path == '/proc/1234/stat':
103 return mock.mock_open(read_data=stat_line)()
104 raise FileNotFoundError(path)
105
106 with mock.patch('glob.iglob', return_value=['/proc/1234/exe']), \
107 mock.patch('os.path.realpath', side_effect=PermissionError(13, 'denied')), \
108 mock.patch('builtins.open', side_effect=fake_open), \
109 mock.patch('os.stat') as mock_stat, \
110 mock.patch('bleachbit.General.get_real_uid', return_value=1000):
111 mock_stat.return_value.st_uid = 1000
112 result = list(_enumerate_proc_fs())
113
114 self.assertEqual(result, [ProcessInfo(1234, 'Web Content', True)])
115
116 @common.also_with_sudo
117 def test_is_process_running_self(self):
118 """Test that this process is running"""
119 exe_names = [psutil.Process().name()]
120 parent = psutil.Process().parent()
121 if parent:
122 exe_names.append(parent.name())
123
124 if IS_WINDOWS:
125 exe_names.extend([e.swapcase() for e in exe_names])
126
127 # Under sudo the test process (and its parent) run as root, while
128 # 'same_user' intentionally compares against the real (non-root)
129 # user, so the current process is not considered 'same_user'.
130 # The require_same_user=True assertion is only valid when the
131 # current process actually runs as the real user.
132 check_same_user = not sudo_mode()
133
134 for exe_name in exe_names:
135 self.assertTrue(is_process_running(exe_name, False))
136 if check_same_user:
137 self.assertTrue(is_process_running(exe_name, True))
138
139 @common.also_with_sudo
140 def test_is_process_running_does_not_exist(self):
141 """Test is_process_running() with processes that do not exist"""
142 this_proc_name = psutil.Process().name()
143 tests = [
144 'does_not_exist',
145 '',
146 '*',
147 this_proc_name + 'x',
148 'x' + this_proc_name,
149 this_proc_name[1:]
150 ]
151 # if current process is 'python3', then not unlikely 'python' could
152 # be running too, so omit: this test `psutil.Process().name()[:-1]`
153 if not this_proc_name == 'python3':
154 tests.append(this_proc_name[:-1])
155 if not IS_WINDOWS:
156 tests.append(this_proc_name.swapcase())
157 for exename in tests:
158 for require_same_user in (False, True):
159 with self.subTest(exename=exename, require_same_user=require_same_user):
160 self.assertFalse(is_process_running(exename, require_same_user),
161 f'is_running({exename}, {require_same_user})')
162
163 @common.skipUnlessLinux
164 @common.also_with_sudo
165 def test_is_process_running_linux(self):
166 """Unit test for method is_process_running()"""
167 # Do not use get_executable() here because of how it
168 # handles symlinks.
169 # sys.executable may look like /usr/bin/python3
170 # When running under `env -i`, then sys.executable is empty.
171 exe = None
172 if sys.executable:
173 exe = os.path.basename(os.path.realpath(sys.executable))
174 else:
175 try:
176 with open('/proc/self/stat', 'r', encoding='utf-8') as f:
177 exe = f.read().split()[1].strip('()')
178 except (IOError, IndexError):
179 self.skipTest(
180 "Could not determine current process name from /proc/self/stat")
181 tests = [
182 # (expected, exe, require_same_user)
183 (True, exe, False), # Check the actual process name
184 (True, exe, True), # Check the actual process name
185 ]
186 # These processes may be running but not by the current user.
187 non_user_exes = ('polkitd', 'bluetoothd', 'NetworkManager',
188 'gdm3', 'snapd', 'systemd-journald')
189 tests += [(False, name, True) for name in non_user_exes]
190 # These do not exist.
191 tests += [
192 (False, 'does-not-exist', True),
193 (False, 'does-not-exist', False),
194 ]
195 for expected, exename, require_same_user in tests:
196 with self.subTest(exename=exename, require_same_user=require_same_user):
197 self.assertEqual(is_process_running(exename, require_same_user), expected,
198 f'is_running({exename}, {require_same_user})')
199
200 @common.skipUnlessMac
201 @common.also_with_sudo
202 def test_is_process_running_macos(self):
203 """Unit test for is_process_running() on macOS.
204
205 On macOS, psutil reports the process name as the app-bundle
206 executable name (truncated to 15 chars, like 'comm'), while
207 the 'exe' basename may give the full name. Both are yielded by
208 _enumerate_psutil_posix, so is_process_running should find the
209 process by either name.
210 """
211 proc = psutil.Process()
212 psutil_name = proc.name() # 'Process'
213 exe = proc.exe() # '/Library/Developer/.../Python' (long string)
214 exe_basename = os.path.basename(exe) if exe else psutil_name
215 self.assertTrue(psutil_name, 'psutil did not return a process name')
216
217 # Names by which the current process should be detectable.
218 detectable_names = {psutil_name}
219 if exe_basename != psutil_name:
220 detectable_names.add(exe_basename)
221
222 check_same_user = not sudo_mode()
223 for name in detectable_names:
224 self.assertTrue(is_process_running(name, False),
225 f'is_running({name}, False)')
226 if check_same_user:
227 self.assertTrue(is_process_running(name, True),
228 f'is_running({name}, True)')
229
230 # macOS system daemons that run as root, so they should be
231 # running but not as the same (real) user.
232 non_user_exes = ('bluetoothd', 'logd', 'launchd')
233 for name in non_user_exes:
234 with self.subTest(exename=name, require_same_user=True):
235 self.assertTrue(is_process_running(name, False),
236 f'expected {name} to be running on macOS')
237 self.assertFalse(is_process_running(name, True),
238 f'{name} should not be same_user')
239
240 # These do not exist.
241 for exename in ('sol.exe', 'systemd', 'kthreadd', ''):
242 for require_same_user in (False, True):
243 with self.subTest(exename=exename,
244 require_same_user=require_same_user):
245 self.assertFalse(is_process_running(exename, require_same_user),
246 f'is_running({exename}, {require_same_user})')
247
248 def test_missing_psutil(self):
249 """Process should be importable without psutil and set _has_psutil=False."""
250 with common.mock_missing_package(
251 'psutil',
252 clear_prefixes=('bleachbit.Process',)):
253 import bleachbit.Process as Process
254 self.assertFalse(Process._has_psutil)
255
256 @common.skipUnlessWindows
257 def test_is_process_running_windows(self):
258 """Test is_process_running() on Windows"""
259 # winlogon.exe runs on Windows XP and Windows 7
260 # explorer.exe did not run in CI, but it does as of 2025-01-25.
261 # svchost.exe runs both as system and current user on Windows 11
262 # svchost.exe does not always run as the same user in CI.
263 tests = ((True, 'winlogon.exe', False),
264 (True, 'WinLogOn.exe', False),
265 (False, 'doesnotexist.exe', False),
266 (True, 'explorer.exe', True),
267 (True, 'svchost.exe', False),
268 (True, 'services.exe', False),
269 (False, 'services.exe', True),
270 (True, 'wininit.exe', False),
271 (False, 'wininit.exe', True))
272
273 for expected, exename, require_same_user in tests:
274 with self.subTest(exename=exename, require_same_user=require_same_user):
275 result = is_process_running(exename, require_same_user)
276 self.assertEqual(
277 expected, result, f'Expecting is_process_running({exename}, {require_same_user}) = {expected}, got {result}')
278
279 def test_missing_psutil_import(self):
280 """Process should be importable without psutil and set _has_psutil=False."""
281 with common.mock_missing_package(
282 'psutil',
283 clear_prefixes=('bleachbit.Process',)):
284 import bleachbit.Process as Process
285 self.assertFalse(Process._has_psutil)
286 if IS_WINDOWS:
287 with self.assertRaises(RuntimeError):
288 list(Process.enumerate_processes())