Debian Codegraph @

tests/TestMemory.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 module Memory
9 """
10
11 import os
12 import re
13 from contextlib import contextmanager
14 from unittest import mock
15
16 from tests import common
17 from bleachbit import General, logger
18 from bleachbit.FileUtilities import exe_exists
19 from bleachbit.Memory import (
20 _memory_child_script,
21 _parse_meminfo_free,
22 _run_memory_child_fork,
23 _run_memory_child_systemd_scope,
24 count_swap_linux,
25 disable_swap_linux,
26 enable_swap_linux,
27 get_proc_swaps,
28 get_swap_size_linux,
29 get_swap_uuid,
30 make_self_oom_target_linux,
31 parse_swapoff,
32 physical_free, physical_free_darwin,
33 report_free,
34 wipe_memory,
35 wipe_swap_linux)
36
37
38 class MemoryTestCase(common.BleachbitTestCase):
39 """Test case for module Memory"""
40
41 @staticmethod
42 @contextmanager
43 def _mock_systemd_scope_common():
44 """Common mocks for _run_memory_child_systemd_scope(): systemd-run
45 is present and the real UID is 1000."""
46 with mock.patch('bleachbit.FileUtilities.exe_exists',
47 return_value=True):
48 with mock.patch('bleachbit.Memory.General.get_real_uid',
49 return_value=1000):
50 yield
51
52 def _assert_fork_exit_status(self, waitpid_status, expected):
53 """Run _run_memory_child_fork() under the standard parent-path mocks
54 and assert it returns ``expected`` for the given waitpid status."""
55 # Mock _() to avoid lazy translation setup, which calls
56 # subprocess.Popen and would break under mocked os.fork/os.waitpid.
57 with mock.patch('bleachbit.Memory._', side_effect=lambda s: s):
58 with mock.patch('bleachbit.Memory.General.get_real_uid',
59 return_value=1000):
60 with mock.patch('os.fork', return_value=1234):
61 with mock.patch('os.waitpid',
62 return_value=(1234, waitpid_status)):
63 self.assertEqual(_run_memory_child_fork(), expected)
64
65 def _assert_wipe_memory_happy_path(self, scope_return, fork_return,
66 fork_called):
67 """Exercise wipe_memory() through its mocked happy path and verify
68 the generator yields two progress values then 0, with swap
69 re-enabled. ``scope_return`` and ``fork_return`` select which child
70 runner is used; ``fork_called`` asserts whether the fork fallback
71 is expected to run."""
72 with mock.patch('bleachbit.Memory._', side_effect=lambda s: s):
73 with mock.patch('bleachbit.FileUtilities.exe_exists',
74 return_value=True):
75 with mock.patch('bleachbit.Memory.get_proc_swaps',
76 return_value=''):
77 with mock.patch('bleachbit.Memory.disable_swap_linux',
78 return_value=['/dev/sda1']):
79 with mock.patch('bleachbit.Memory.wipe_swap_linux'):
80 with mock.patch(
81 'bleachbit.Memory._run_memory_child_systemd_scope',
82 return_value=scope_return):
83 with mock.patch(
84 'bleachbit.Memory._run_memory_child_fork',
85 return_value=fork_return) as mock_fork:
86 with mock.patch(
87 'bleachbit.Memory.enable_swap_linux') as mock_enable:
88 gen = wipe_memory()
89 self.assertTrue(next(gen))
90 self.assertTrue(next(gen))
91 self.assertEqual(next(gen), 0)
92 self.assertTrue(mock_enable.called)
93 self.assertEqual(mock_fork.called,
94 fork_called)
95
96 @common.skipUnlessLinux
97 def test_get_proc_swaps(self):
98 """Test for method get_proc_swaps"""
99 if not exe_exists(General.resolve_exe('swapon')):
100 self.skipTest('swapon not found')
101 ret = get_proc_swaps()
102 self.assertGreater(len(ret), 10)
103 if not re.search(r'Filename\s+Type\s+Size', ret):
104 raise RuntimeError(
105 "Unexpected first line in swap summary '%s'" % ret)
106
107 @common.skipIfWindows
108 def test_make_self_oom_target_linux(self):
109 """Test for method make_self_oom_target_linux"""
110
111 # preserve
112 euid = os.geteuid()
113
114 # Minimally test there is no traceback
115 make_self_oom_target_linux()
116
117 # restore
118 os.seteuid(euid)
119
120 @common.skipUnlessLinux
121 def test_count_linux_swap(self):
122 """Test for method count_linux_swap"""
123 n_swaps = count_swap_linux()
124 self.assertIsInteger(n_swaps)
125 self.assertTrue(0 <= n_swaps < 10)
126
127 @common.skipIfWindows
128 def test_physical_free_darwin(self):
129 self.assertEqual(physical_free_darwin(lambda:
130 """Mach Virtual Memory Statistics: (page size of 4096 bytes)
131 Pages free: 836891.
132 Pages active: 588004.
133 Pages inactive: 16985.
134 Pages speculative: 89776.
135 Pages throttled: 0.
136 Pages wired down: 468097.
137 Pages purgeable: 58313.
138 "Translation faults": 3109985921.
139 Pages copy-on-write: 25209334.
140 Pages zero filled: 537180873.
141 Pages reactivated: 132264973.
142 Pages purged: 11567935.
143 File-backed pages: 184609.
144 Anonymous pages: 510156.
145 Pages stored in compressor: 784977.
146 Pages occupied by compressor: 96724.
147 Decompressions: 66048421.
148 Compressions: 90076786.
149 Pageins: 758631430.
150 Pageouts: 30477017.
151 Swapins: 19424481.
152 Swapouts: 20258188.
153 """), 3427905536)
154 self.assertRaises(RuntimeError, physical_free_darwin,
155 lambda: "Invalid header")
156
157 @common.skipIfWindows
158 def test_physical_free_darwin_uses_absolute_path(self):
159 """physical_free_darwin() must invoke vm_stat via its absolute path, not PATH lookup"""
160 sample = ("Mach Virtual Memory Statistics: (page size of 4096 bytes)\n"
161 "Pages free: 1.\n")
162 with mock.patch('bleachbit.Memory.subprocess.check_output',
163 return_value=sample) as mock_check_output:
164 physical_free_darwin()
165 mock_check_output.assert_called_once()
166 call = mock_check_output.call_args
167 self.assertEqual(call.args[0], [General.resolve_exe('vm_stat')])
168 self.assertTrue(call.kwargs.get('text'))
169 # the child's env is sanitized (LD_*/DYLD_* dropped when root)
170 self.assertIn('env', call.kwargs)
171
172 @common.skipUnlessLinux
173 def test_physical_free(self):
174 """Test for method physical_free"""
175 ret = physical_free()
176 self.assertIsInteger(
177 ret, 'physical_free() returns variable type %s' % type(ret))
178 self.assertGreater(physical_free(), 0)
179 report_free()
180
181 def test_parse_meminfo_free_swapcached_not_matched(self):
182 """SwapCached must not be counted as free
183
184 Regression test that is a follow up to edba5e55"""
185 meminfo = (
186 "MemFree: 1000 kB\n"
187 "SwapCached: 500 kB\n"
188 "Cached: 2000 kB\n"
189 )
190 free_bytes, num_matches = _parse_meminfo_free(meminfo)
191 self.assertEqual(num_matches, 2)
192 self.assertEqual(free_bytes, (1000 + 2000) * 1024)
193
194 @common.skipUnlessLinux
195 def test_parse_meminfo_free_real_proc(self):
196 """The real /proc/meminfo must match exactly MemFree and Cached and
197 nothing else, so future false positives (e.g. SwapCached) are caught.
198
199 macOS does not have /proc.
200 """
201 with open('/proc/meminfo', encoding='utf-8') as f:
202 contents = f.read()
203 free_bytes, num_matches = _parse_meminfo_free(contents)
204 self.assertEqual(num_matches, 2)
205 self.assertGreater(free_bytes, 0)
206
207 @common.skipUnlessLinux
208 def test_get_swap_size_linux(self):
209 """Test for get_swap_size_linux()"""
210 if not exe_exists(General.resolve_exe('swapon')):
211 self.skipTest('swapon not found')
212 with open('/proc/swaps', encoding='utf-8') as f:
213 swapdev = f.read().split('\n')[1].split(' ')[0]
214 if 0 == len(swapdev):
215 self.skipTest('no active swap device detected')
216 size = get_swap_size_linux(swapdev)
217 self.assertIsInteger(size)
218 self.assertGreater(size, 1024 ** 2)
219 logger.debug("size of swap '%s': %d B (%d MB)",
220 swapdev, size, size / (1024 ** 2))
221 with open('/proc/swaps', encoding='utf-8') as f:
222 proc_swaps = f.read()
223 size2 = get_swap_size_linux(swapdev, proc_swaps)
224 self.assertEqual(size, size2)
225
226 @common.skipIfWindows
227 def test_get_swap_uuid(self):
228 """Test for method get_swap_uuid"""
229 if not exe_exists(General.resolve_exe('blkid')):
230 self.skipTest('blkid not found')
231 self.assertEqual(get_swap_uuid('/dev/doesnotexist'), None)
232
233 def test_parse_swapoff(self):
234 """Test for method parse_swapoff"""
235 tests = (
236 # Ubuntu 15.10 has format "swapoff /dev/sda3"
237 ('swapoff /dev/sda3', '/dev/sda3'),
238 ('swapoff for /dev/sda6', '/dev/sda6'),
239 ('swapoff on /dev/mapper/lubuntu-swap_1', '/dev/mapper/lubuntu-swap_1'))
240
241 for test in tests:
242 self.assertEqual(parse_swapoff(test[0]), test[1])
243
244 @common.skipIfWindows
245 def test_disable_swap_linux(self):
246 """Test for disable_swap_linux() with mocks"""
247 # No swap active - early return
248 with mock.patch('bleachbit.Memory.count_swap_linux', return_value=0):
249 self.assertIsNone(disable_swap_linux())
250
251 # Command failure
252 with mock.patch('bleachbit.Memory.count_swap_linux', return_value=1):
253 with mock.patch('bleachbit.Memory.General.run_external', return_value=(1, '', 'swapoff failed')):
254 self.assertRaisesRegex(
255 RuntimeError, 'swapoff failed', disable_swap_linux)
256
257 # Unexpected output
258 with mock.patch('bleachbit.Memory.count_swap_linux', return_value=1):
259 with mock.patch('bleachbit.Memory.General.run_external', return_value=(0, 'unexpected\n', '')):
260 self.assertRaisesRegex(
261 RuntimeError, 'Unexpected output', disable_swap_linux)
262
263 # Parse success
264 with mock.patch('bleachbit.Memory.count_swap_linux', return_value=1):
265 with mock.patch('bleachbit.Memory.General.run_external', return_value=(0, 'swapoff /dev/sda3\n', '')):
266 devices = disable_swap_linux()
267 self.assertEqual(devices, ['/dev/sda3'])
268
269 @common.skipIfWindows
270 def test_enable_swap_linux(self):
271 """Test for enable_swap_linux() with mocks"""
272 # Success
273 with mock.patch('bleachbit.Memory._', side_effect=lambda s: s):
274 with mock.patch('bleachbit.Memory.General.run_external', return_value=(0, '', '')) as mock_run:
275 enable_swap_linux()
276 self.assertEqual(mock_run.call_args.args[0], [
277 General.resolve_exe('swapon'), '-a'])
278
279 # Failure
280 with mock.patch('bleachbit.Memory._', side_effect=lambda s: s):
281 with mock.patch('bleachbit.Memory.General.run_external', return_value=(1, '', 'swapon failed')):
282 self.assertRaisesRegex(
283 RuntimeError, 'swapon failed', enable_swap_linux)
284
285 @common.skipIfWindows
286 def test_get_swap_size_linux_errors(self):
287 """Test for get_swap_size_linux() error paths"""
288 # Malformed header
289 self.assertRaisesRegex(
290 RuntimeError, 'Unexpected first line',
291 get_swap_size_linux, '/dev/sda1', 'bad header\n')
292
293 # Missing device
294 proc_swaps = 'Filename\tType\tSize\tUsed\tPriority\n/dev/sda2\tpartition\t123\t0\t-2\n'
295 self.assertRaisesRegex(
296 RuntimeError, 'cannot find size of swap device',
297 get_swap_size_linux, '/dev/sda1', proc_swaps)
298
299 @common.skipIfWindows
300 def test_wipe_swap_linux(self):
301 """Test for wipe_swap_linux() with mocks"""
302 # devices is None - early return
303 wipe_swap_linux(None, '')
304
305 # Swap still in use
306 with mock.patch('bleachbit.Memory.count_swap_linux', return_value=1):
307 self.assertRaisesRegex(
308 RuntimeError, 'Cannot wipe swap while it is in use',
309 wipe_swap_linux, ['/dev/sda1'], '')
310
311 # Safety limit exceeded
312 safety_limit = 29 * 1024 ** 3
313 with mock.patch('bleachbit.Memory.count_swap_linux', return_value=0):
314 with mock.patch('bleachbit.Memory.get_swap_size_linux', return_value=safety_limit + 1):
315 self.assertRaisesRegex(
316 RuntimeError, 'larger .* than expected',
317 wipe_swap_linux, ['/dev/sda1'], '')
318
319 # UUID preservation
320 with mock.patch('bleachbit.Memory.count_swap_linux', return_value=0):
321 with mock.patch('bleachbit.Memory.get_swap_size_linux', return_value=1024 ** 2):
322 with mock.patch('bleachbit.Memory.get_swap_uuid', return_value='abc-123'):
323 with mock.patch('bleachbit.Memory.wipe_write'):
324 with mock.patch('bleachbit.Memory.General.run_external', return_value=(0, '', '')) as mock_run:
325 wipe_swap_linux(['/dev/sda1'], '')
326 args = mock_run.call_args[0][0]
327 self.assertIn('-U', args)
328 self.assertIn('abc-123', args)
329
330 # mkswap failure
331 with mock.patch('bleachbit.Memory.count_swap_linux', return_value=0):
332 with mock.patch('bleachbit.Memory.get_swap_size_linux', return_value=1024 ** 2):
333 with mock.patch('bleachbit.Memory.get_swap_uuid', return_value=None):
334 with mock.patch('bleachbit.Memory.wipe_write'):
335 with mock.patch('bleachbit.Memory.General.run_external', return_value=(1, '', 'mkswap failed')):
336 self.assertRaisesRegex(
337 RuntimeError, 'mkswap failed',
338 wipe_swap_linux, ['/dev/sda1'], '')
339
340 @common.skipUnlessLinux
341 def test_wipe_memory(self):
342 """Test for wipe_memory() with mocks"""
343 # Command missing
344 with mock.patch('bleachbit.FileUtilities.exe_exists', return_value=False):
345 gen = wipe_memory()
346 self.assertRaisesRegex(
347 RuntimeError,
348 f"Command {General.resolve_exe('swapon')} not found",
349 next, gen)
350
351 # Happy path via the fork fallback (systemd-run path disabled)
352 self._assert_wipe_memory_happy_path(
353 scope_return=None, fork_return=0, fork_called=True)
354
355 # Happy path via the systemd scope (fork fallback not used)
356 self._assert_wipe_memory_happy_path(
357 scope_return=0, fork_return=None, fork_called=False)
358
359 @common.skipIfWindows
360 def test_memory_child_script(self):
361 """Test for _memory_child_script()"""
362 script = _memory_child_script(1000)
363 self.assertIn('make_self_oom_target_linux(1000)', script)
364 self.assertIn('fill_memory_linux()', script)
365 # None uid renders as the literal None
366 script_none = _memory_child_script(None)
367 self.assertIn('make_self_oom_target_linux(None)', script_none)
368
369 @common.skipIfWindows
370 def test_run_memory_child_systemd_scope_missing(self):
371 """_run_memory_child_systemd_scope() returns None without systemd-run"""
372 with mock.patch('bleachbit.FileUtilities.exe_exists', return_value=False):
373 self.assertIsNone(_run_memory_child_systemd_scope())
374
375 @common.skipIfWindows
376 def test_run_memory_child_systemd_scope_unique_unit(self):
377 """_run_memory_child_systemd_scope() uses a PID-suffixed unit name"""
378 captured = {}
379
380 def fake_run(args, env=None, **kwargs):
381 captured['args'] = args
382 captured['kwargs'] = kwargs
383 proc = mock.Mock()
384 proc.returncode = 0
385 proc.stderr = ''
386 return proc
387
388 with self._mock_systemd_scope_common():
389 with mock.patch('bleachbit.Memory.subprocess.run', side_effect=fake_run):
390 _run_memory_child_systemd_scope()
391 unit_args = [a for a in captured['args'] if a.startswith('--unit=')]
392 self.assertEqual(len(unit_args), 1)
393 self.assertIn(f'bleachbit-wipe-memory-{os.getpid()}', unit_args[0])
394
395 @common.skipIfWindows
396 def test_run_memory_child_systemd_scope_sanitizes_env(self):
397 """The root child gets a fixed PYTHONPATH and a safe cwd, not the inherited env"""
398 import bleachbit.Memory as Memory_mod
399 pkg_parent = os.path.dirname(
400 os.path.dirname(os.path.abspath(Memory_mod.__file__)))
401 captured = {}
402
403 def fake_run(args, env=None, **kwargs):
404 captured['env'] = env
405 captured['kwargs'] = kwargs
406 proc = mock.Mock()
407 proc.returncode = 0
408 proc.stderr = ''
409 return proc
410
411 with self._mock_systemd_scope_common():
412 with mock.patch.dict(os.environ,
413 {'PYTHONPATH': '/tmp/attacker'}):
414 with mock.patch('bleachbit.Memory.subprocess.run',
415 side_effect=fake_run):
416 _run_memory_child_systemd_scope()
417 self.assertEqual(captured['env']['PYTHONPATH'], pkg_parent)
418 self.assertNotIn('/tmp/attacker', captured['env']['PYTHONPATH'])
419 self.assertEqual(captured['kwargs'].get('cwd'), pkg_parent)
420
421 @common.skipIfWindows
422 def test_run_memory_child_systemd_scope_signal(self):
423 """_run_memory_child_systemd_scope() normalizes signal exit codes"""
424 # subprocess.run reports -N when its direct child is killed by signal N.
425 # A shell instead exposes this as status 128+N (for SIGKILL, 137), so
426 # do not model a shell-observed 137 as subprocess signal termination.
427 mock_proc = mock.Mock()
428 mock_proc.returncode = -9
429 mock_proc.stderr = ''
430 with self._mock_systemd_scope_common():
431 with mock.patch('bleachbit.Memory.subprocess.run', return_value=mock_proc):
432 self.assertEqual(_run_memory_child_systemd_scope(), 9)
433 # Normal exit
434 mock_proc.returncode = 0
435 with self._mock_systemd_scope_common():
436 with mock.patch('bleachbit.Memory.subprocess.run', return_value=mock_proc):
437 self.assertEqual(_run_memory_child_systemd_scope(), 0)
438
439 @common.skipIfWindows
440 def test_run_memory_child_systemd_scope_without_oom_policy(self):
441 """Retry without OOMPolicy when scope units do not support it"""
442 unsupported_proc = mock.Mock()
443 unsupported_proc.returncode = 1
444 unsupported_proc.stderr = 'Unknown property OOMPolicy\n'
445 success_proc = mock.Mock()
446 success_proc.returncode = 0
447 success_proc.stderr = ''
448 with self._mock_systemd_scope_common():
449 with mock.patch(
450 'bleachbit.Memory.subprocess.run',
451 side_effect=(unsupported_proc, success_proc)) as mock_run:
452 self.assertEqual(_run_memory_child_systemd_scope(), 0)
453 self.assertEqual(mock_run.call_count, 2)
454 self.assertIn('--property=OOMPolicy=kill',
455 mock_run.call_args_list[0].args[0])
456 self.assertNotIn('--property=OOMPolicy=kill',
457 mock_run.call_args_list[1].args[0])
458
459 @common.skipIfWindows
460 def test_run_memory_child_systemd_scope_runtime_failure(self):
461 """_run_memory_child_systemd_scope() falls back when systemd-run fails
462
463 A non-zero, non-signal exit code means systemd-run itself failed
464 (e.g. no systemd as PID 1, no D-Bus session) and the child never
465 ran -- the function returns None so the caller can fall back to
466 fork().
467 """
468 mock_proc = mock.Mock()
469 mock_proc.returncode = 1
470 mock_proc.stderr = 'Failed to start transient scope unit: Access denied\n'
471 with self._mock_systemd_scope_common():
472 with mock.patch('bleachbit.Memory.subprocess.run', return_value=mock_proc) as mock_run:
473 with mock.patch('bleachbit.Memory.logger') as mock_logger:
474 self.assertIsNone(_run_memory_child_systemd_scope())
475 mock_run.assert_called_once()
476 self.assertTrue(
477 mock_run.call_args.kwargs.get('capture_output'))
478 debug_msgs = [
479 call.args[0] % call.args[1:]
480 if call.args else ''
481 for call in mock_logger.debug.call_args_list
482 ]
483 self.assertTrue(
484 any('Access denied' in msg for msg in debug_msgs),
485 debug_msgs)
486 # A high exit code (e.g. 137) is treated as a plain failure, not a
487 # signal, since subprocess.run already reports signals as -N.
488 mock_proc.returncode = 137
489 mock_proc.stderr = ''
490 with self._mock_systemd_scope_common():
491 with mock.patch('bleachbit.Memory.subprocess.run', return_value=mock_proc):
492 self.assertIsNone(_run_memory_child_systemd_scope())
493
494 @common.skipIfWindows
495 def test_run_memory_child_fork_child_path(self):
496 """_run_memory_child_fork() child path calls the right functions and exits"""
497 with mock.patch('bleachbit.Memory.General.get_real_uid', return_value=1000):
498 with mock.patch('bleachbit.Memory.make_self_oom_target_linux') as mock_oom:
499 with mock.patch('bleachbit.Memory.fill_memory_linux') as mock_fill:
500 with mock.patch('os.fork', return_value=0):
501 with mock.patch('os._exit') as mock_exit:
502 _run_memory_child_fork()
503 mock_oom.assert_called_once_with(1000)
504 mock_fill.assert_called_once()
505 mock_exit.assert_called_once_with(0)
506
507 @common.skipIfWindows
508 def test_run_memory_child_fork_normal_exit(self):
509 """_run_memory_child_fork() returns 0 when child exits normally"""
510 self._assert_fork_exit_status(0, 0)
511
512 @common.skipIfWindows
513 def test_run_memory_child_fork_signal(self):
514 """_run_memory_child_fork() returns signal number when child is killed"""
515 self._assert_fork_exit_status(9, 9)
516
517 @common.skipIfWindows
518 def test_run_memory_child_fork_nonzero_exit(self):
519 """_run_memory_child_fork() returns a non-zero exit code"""
520 self._assert_fork_exit_status(1 << 8, 1)
521
522 @common.skipIfWindows
523 def test_run_memory_child_fork_uid_exception(self):
524 """_run_memory_child_fork() falls back to None when get_real_uid fails"""
525 with mock.patch('bleachbit.Memory.General.get_real_uid', side_effect=Exception('boom')):
526 with mock.patch('bleachbit.Memory.make_self_oom_target_linux') as mock_oom:
527 with mock.patch('bleachbit.Memory.fill_memory_linux'):
528 with mock.patch('os.fork', return_value=0):
529 with mock.patch('os._exit'):
530 _run_memory_child_fork()
531 mock_oom.assert_called_once_with(None)
532
533 @common.skipIfWindows
534 def test_swap_off_swap_on(self):
535 """Test for disabling and enabling swap"""
536 if not common.have_root():
537 self.skipTest('not enough privileges')
538 disable_swap_linux()
539 enable_swap_linux()