Debian Codegraph @

tests/TestSystemInformation.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 module SystemInformation
10 """
11
12 import os
13 import re
14 from unittest import mock
15
16
17 from tests import common
18 from bleachbit import IS_POSIX, FS_SCAN_RE_FLAGS
19 from bleachbit.SystemInformation import get_system_information, get_version, anonymize_system_information
20
21
22 class SystemInformationTestCase(common.BleachbitTestCase):
23 """Test Case for module SystemInformation"""
24
25 def test_get_system_information(self):
26 """Test get_system_information"""
27 # at least it does not crash
28 ret = get_system_information()
29 self.assertIsString(ret)
30
31 def test_get_system_information_mac_version_name(self):
32 """macOS dropped the '10.' version prefix starting with 11
33 (Big Sur), so the release name must be looked up by the FIRST
34 version component for modern versions, falling back to the
35 second component only for the old '10.x' scheme. A modern
36 version's second component must never be misread as an old-
37 scheme release code (e.g. '26.6.2' must show 'Tahoe', not
38 misread the '6' as the old code for 'Snow Leopard')."""
39 cases = {
40 '26.6.2': 'Tahoe',
41 '15.1.0': 'Sequoia',
42 '14.0': 'Sonoma',
43 '10.15.7': 'Catalina',
44 '10.6.8': 'Snow Leopard',
45 '10.6': 'Snow Leopard',
46 }
47 for version, expected_name in cases.items():
48 with mock.patch('platform.mac_ver', return_value=(version, ('', '', ''), '')), \
49 mock.patch('bleachbit.SystemInformation.IS_MAC', True), \
50 mock.patch('bleachbit.SystemInformation.IS_LINUX', False):
51 ret = get_system_information()
52 self.assertIn(
53 f'platform.mac_ver() = {version} ({expected_name})', ret,
54 f'version {version} should show {expected_name}')
55
56 @common.skipUnlessWindows
57 def test_get_system_information_invalid_unicode_userprofile(self):
58 invalid_userprofile = 'C:\\Users\\invalid\ud803'
59 original_getenv = os.getenv
60
61 def getenv(name, default=None):
62 if name == 'USERPROFILE':
63 return invalid_userprofile
64 return original_getenv(name, default)
65
66 with mock.patch('bleachbit.SystemInformation.os.getenv', side_effect=getenv):
67 ret = get_system_information()
68
69 encoded = ret.encode('utf-8')
70 self.assertIn(b'C:\\Users\\invalid\\ud803', encoded)
71
72 def test_get_version(self):
73 """Test get_version"""
74 ret = get_version()
75 self.assertIsString(ret)
76 # check it is in a.b.c.d or a.b.c format
77 self.assertRegex(ret, r'^\d+\.\d+\.\d+(\.\d+)?$')
78 ret = get_version(four_parts=True)
79 self.assertIsString(ret)
80 # check it is in a.b.c.d format
81 self.assertRegex(ret, r'^\d+\.\d+\.\d+\.\d+$')
82
83 @common.skipIfWindows
84 def test_anonymize_system_information_posix_non_root(self):
85 """Test anonymization on POSIX with a non-root home directory."""
86 home_dir = os.path.expanduser('~')
87 if home_dir in ('/root', '/'):
88 self.skipTest('requires a non-root POSIX home directory')
89
90 test_input = f"""BleachBit version = 5.1.0
91 local_cleaners_dir = {home_dir}/.local/share/bleachbit/cleaners
92 options_dir = {home_dir}/.config/bleachbit
93 os.getenv(LOGNAME) = testuser
94 os.getenv(USER) = testuser
95 os.getenv(SUDO_UID) = 1000"""
96
97 result = anonymize_system_information(test_input)
98
99 self.assertIn(
100 'local_cleaners_dir = ~/.local/share/bleachbit/cleaners', result)
101 self.assertIn('options_dir = ~/.config/bleachbit', result)
102 self.assertNotIn(home_dir, result)
103 self.assertNotIn(home_dir.lower(), result.lower())
104 self.assertIn('os.getenv(LOGNAME) = *non-root*', result)
105 self.assertIn('os.getenv(USER) = *non-root*', result)
106 self.assertIn('os.getenv(SUDO_UID) = 1000', result)
107
108 @common.skipUnlessWindows
109 def test_anonymize_system_information_windows(self):
110 """Test anonymization on Windows with environment variables."""
111 home_dir = os.path.expanduser('~')
112 test_input = f"""os.getenv(APPDATA) = {home_dir.upper()}\\AppData\\Roaming
113 os.getenv(USERPROFILE) = {home_dir.lower()}
114 os.getenv(LocalAppData) = {home_dir}\\AppData\\Local"""
115
116 result = anonymize_system_information(test_input)
117
118 self.assertIn(
119 'os.getenv(APPDATA) = %userprofile%\\AppData\\Roaming', result)
120 self.assertIn(
121 'os.getenv(USERPROFILE) = %userprofile%', result)
122 self.assertIn(
123 'os.getenv(LocalAppData) = %userprofile%\\AppData\\Local', result)
124 self.assertIsNone(re.search(re.escape(home_dir),
125 result, flags=FS_SCAN_RE_FLAGS))
126
127 @common.skipUnlessWindows
128 def test_anonymize_system_information_windows_short_path(self):
129 """Test anonymization handles Windows short (8.3) paths."""
130 # Create a directory with Unicode characters that will have a short path
131 username = '我可以喝漂白剂而不伤及自身'
132 unicode_dir = self.mkdir(username)
133
134 short_path = None
135 try:
136 import win32api
137 short_path = win32api.GetShortPathName(unicode_dir)
138 except (ImportError, OSError):
139 self.skipTest('win32api not available or short path not supported')
140
141 if short_path == unicode_dir:
142 self.skipTest('Short path generation not enabled on this system')
143
144 self.assertTrue(os.path.samefile(unicode_dir, short_path))
145
146 with mock.patch('bleachbit.SystemInformation.os.path.expanduser', return_value=unicode_dir):
147 from bleachbit.SystemInformation import _get_home_dirs_to_anonymize
148 home_dirs = _get_home_dirs_to_anonymize()
149
150 self.assertIn(short_path, home_dirs)
151 self.assertTrue(os.path.samefile(home_dirs[0], home_dirs[1]))
152
153 test_input = f"os.getenv(TMP) = {short_path}\\AppData\\Local\\Temp"
154 with mock.patch('bleachbit.SystemInformation._get_home_dirs_to_anonymize',
155 return_value=[unicode_dir, short_path]):
156 anonymized = anonymize_system_information(test_input)
157
158 self.assertIn('%userprofile%', anonymized)
159 self.assertNotIn(username, anonymized)
160 self.assertNotIn(short_path, anonymized)
161 self.assertNotIn(unicode_dir, anonymized)
162
163 def test_anonymize_system_information_preserves_non_sensitive_data(self):
164 """Test that non-sensitive data remains unchanged during anonymization."""
165 test_unchanged = """BleachBit version = 5.1.0
166 gi.version = 3.55.0
167 GTK version = 3.24.51"""
168
169 result = anonymize_system_information(test_unchanged)
170 self.assertEqual(test_unchanged, result)
171
172 def test_anonymize_system_information_preserves_root(self):
173 """Root username should not be mislabeled as non-root."""
174 test_input = """BleachBit version = 5.1.0
175 local_cleaners_dir = /root/.local/share/bleachbit/cleaners
176 options_dir = /root/.config/bleachbit
177 personal_cleaners_dir = /root/.config/bleachbit/cleaners
178 os.getenv(LOGNAME) = root
179 os.getenv(USER) = root
180 os.getenv(SUDO_UID) = 1000
181 os.path.expanduser(~") = /root"""
182 result = anonymize_system_information(test_input)
183 self.assertEqual(test_input, result)
184
185 def test_anonymize_system_information_masks_real_home_dir(self):
186 """Preserve /root while anonymizing the real non-root home directory."""
187 # Mixing /root and user-specific paths is a normal scenario when
188 # running from source `sudo python3 bleachbit.py`.
189 test_input = """personal_cleaners_dir = /root/.config/bleachbit/cleaners
190 system_cleaners_dir = /home/regularuser/software/bleachbit/cleaners
191 __file__ = /home/regularuser/software/bleachbit/bleachbit/SystemInformation.py"""
192 home_token = '~' if IS_POSIX else '%userprofile%'
193
194 with mock.patch('bleachbit.SystemInformation._get_home_dirs_to_anonymize',
195 return_value=['/home/regularuser']):
196 result = anonymize_system_information(test_input)
197
198 self.assertIn(
199 f'system_cleaners_dir = {home_token}/software/bleachbit/cleaners', result)
200 self.assertIn(
201 f'__file__ = {home_token}/software/bleachbit/bleachbit/SystemInformation.py', result)
202 self.assertNotIn('/home/regularuser', result)
203
204 def test_anonymize_preserves_structure(self):
205 """Test that anonymization preserves the structure of system information"""
206 # This is the only anonymization test with the real get_system_information().
207 original = get_system_information()
208 anonymized = anonymize_system_information(original)
209
210 # Both should have the same number of lines
211 self.assertEqual(len(original.split('\n')),
212 len(anonymized.split('\n')))
213
214 # Both should have the same number of equal signs (key-value delimiters)
215 self.assertEqual(original.count(' = '), anonymized.count(' = '))
216
217 # Both should be non-empty strings
218 self.assertIsString(original)
219 self.assertIsString(anonymized)
220 self.assertGreater(len(anonymized), 0)