Debian Codegraph @

tests/TestGuiStartup.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 GuiStartup
9 """
10
11 import os
12 import shutil
13 import stat
14 import subprocess
15 from unittest import mock
16
17 from bleachbit import IS_WINDOWS
18 import bleachbit
19 from bleachbit import GuiStartup
20 from bleachbit.Cleaner import register_cleaners
21 from bleachbit.GuiStartup import _has_selected_warning_option, _get_posix_permission_issues, _get_windows_permission_issues
22 from bleachbit.Options import options
23 from tests import common
24
25
26 class StubOptions:
27 """Minimal stand-in for bleachbit.Options for testing."""
28
29 def __init__(self, *, first_start=True, shred=False, old_version=None):
30 """Seed stub with values."""
31 self.values = {'first_start': first_start, 'shred': shred}
32 self._old_version = old_version
33
34 def get(self, key):
35 """Return stored option value."""
36 return self.values.get(key)
37
38 def set(self, key, value):
39 """Set a option value."""
40 self.values[key] = value
41
42 def get_tree(self, parent, child):
43 """Return whether a tree option is selected."""
44 return False
45
46
47 class GuiStartupTestCase(common.BleachbitTestCase):
48 """Tests for GuiStartup helper logic."""
49
50 def test_first_start_message_clears_flag(self):
51 """Ensure first-start hint is emitted and flag gets cleared."""
52 stub_options = StubOptions()
53
54 with mock.patch.object(GuiStartup, 'options', stub_options), \
55 mock.patch.object(GuiStartup, 'unset_sslkeylogfile', return_value=False):
56 messages = GuiStartup.get_startup_messages(auto_exit=False)
57
58 self.assertTrue(
59 any('Access the application menu' in msg for msg, _ in messages))
60 self.assertFalse(stub_options.get('first_start'))
61
62 def test_has_selected_warning_option(self):
63 """Test the function _has_selected_warning_option()"""
64 # Register cleaners to populate backends
65 list(register_cleaners())
66 # Each test case starts with fresh options, so with
67 # nothing selected, it should return False.
68 self.assertFalse(_has_selected_warning_option())
69 # Enable a safe option.
70 options.set_tree('system', 'tmp', True)
71 self.assertFalse(_has_selected_warning_option())
72 # Enable an option with a warning.
73 options.set_tree('system', 'empty_space', True)
74 self.assertTrue(_has_selected_warning_option())
75 # Clean up
76 options.set_tree('system', 'tmp', False)
77 options.set_tree('system', 'empty_space', False)
78
79 def test_missing_requests(self):
80 """Missing requests should be reported but not crash GuiStartup."""
81 with common.mock_missing_package(
82 'requests',
83 clear_prefixes=('bleachbit.Network', 'bleachbit.Update', 'bleachbit.GuiStartup')):
84 import bleachbit.GuiStartup as GuiStartup
85 missing = GuiStartup._get_missing_dependencies()
86 self.assertIn('requests', missing)
87
88 @common.skipIfWindows
89 def test_is_config_writable(self):
90 """Test read-only configuration file"""
91 o = bleachbit.Options.Options()
92 o.close()
93 self.assertExists(bleachbit.options_file)
94
95 if common.have_root():
96 # root bypasses file permission checks, so use chattr +i
97 subprocess.run(
98 ['chattr', '+i', bleachbit.options_file], check=True)
99 else:
100 os.chmod(bleachbit.options_file, stat.S_IRUSR |
101 stat.S_IRGRP | stat.S_IROTH)
102 try:
103 issues = GuiStartup._get_config_permission_issues()
104 finally:
105 if common.have_root():
106 subprocess.run(
107 ['chattr', '-i', bleachbit.options_file], check=True)
108 os.unlink(bleachbit.options_file)
109
110 self.assertNotExists(bleachbit.options_file)
111 self.assertIsInstance(issues, list)
112 self.assertGreater(len(issues), 0)
113 self.assertTrue(any('Write error' in issue for issue in issues),
114 f"Expected 'Write error' in issues: {issues}")
115
116 def test_config_permission_issues_normal(self):
117 """Test that a normal writable config file reports no issues."""
118 o = bleachbit.Options.Options()
119 o.close()
120 self.assertExists(bleachbit.options_file)
121 issues = GuiStartup._get_config_permission_issues()
122 os.unlink(bleachbit.options_file)
123 self.assertNotExists(bleachbit.options_file)
124 self.assertFalse(issues)
125
126 def test_config_permission_nonissue_missing_file(self):
127 """A missing config file must not be reported as an error.
128
129 Unlike another test, this scenario has an options directory
130 that allows creating the missing config file.
131 """
132 if os.path.exists(bleachbit.options_file):
133 os.unlink(bleachbit.options_file)
134 self.assertNotExists(bleachbit.options_file)
135 issues = GuiStartup._get_config_permission_issues()
136 self.assertFalse(issues)
137
138 @common.skipIfWindows
139 def test_config_permission_issue_non_writeable_options_dir(self):
140 """Config does not exist and options dir is not writeable"""
141 non_writable_dir = self.mkdir('not_writeable_options')
142 non_writable_file = os.path.join(non_writable_dir, 'bleachbit.ini')
143 use_chattr = common.have_root()
144 try:
145 if use_chattr:
146 # Root bypasses chmod, so use chattr +i instead
147 subprocess.run(['chattr', '+i', non_writable_dir], check=True)
148 else:
149 os.chmod(non_writable_dir, stat.S_IRUSR | stat.S_IXUSR)
150 self.assertNotExists(non_writable_file)
151 with mock.patch('bleachbit.options_dir', non_writable_dir), \
152 mock.patch('bleachbit.options_file', non_writable_file):
153 issues = GuiStartup._get_config_permission_issues()
154 finally:
155 if use_chattr:
156 subprocess.run(['chattr', '-i', non_writable_dir], check=True)
157 else:
158 os.chmod(non_writable_dir, stat.S_IRWXU)
159 shutil.rmtree(non_writable_dir)
160 self.assertIsInstance(issues, list)
161 self.assertGreater(len(issues), 0)
162 self.assertTrue(any('Write error' in issue for issue in issues),
163 f"Expected 'Write error' in issues: {issues}")
164
165 @common.also_with_sudo
166 def test_permission_issues_normal_file(self):
167 """Test ownership check on a normal file owned by the user."""
168 path = self.write_file('check_me')
169 fstat = os.stat(path)
170 if IS_WINDOWS:
171 has_error, lines = _get_windows_permission_issues(path)
172 else:
173 has_error, lines = _get_posix_permission_issues(fstat, path)
174 self.assertFalse(has_error)
175 self.assertTrue(any('File owner:' in line for line in lines))
176 self.assertTrue(any('Current user:' in line for line in lines))
177
178 @common.skipUnlessWindows
179 def test_get_windows_user_info(self):
180 """Test _get_windows_user_info function."""
181 current_sid, current_name, group_sids = GuiStartup._get_windows_user_info()
182 self.assertIsNotNone(current_sid)
183 self.assertIsNotNone(current_name)
184 self.assertIsNotNone(group_sids)
185 self.assertIsInstance(current_sid, str)
186 self.assertIsInstance(current_name, str)
187 self.assertIsInstance(group_sids, set)
188 self.assertEqual(current_name, os.environ.get('USERNAME', ''))
189
190 @common.skipUnlessWindows
191 def test_get_windows_file_owner(self):
192 """Test _get_windows_file_owner function."""
193 owner_sid_str, owner_name = GuiStartup._get_windows_file_owner(
194 self.tempdir)
195 self.assertIsNotNone(owner_sid_str)
196 self.assertIsNotNone(owner_name)
197 self.assertIsInstance(owner_sid_str, str)
198 self.assertIsInstance(owner_name, str)
199 # Elevated processes get Administrators as the owner, others get the
200 # user, so accept either, like _get_windows_permission_issues does.
201 current_sid, _name, group_sids = GuiStartup._get_windows_user_info()
202 self.assertIn(owner_sid_str, {current_sid} | group_sids)
203
204 @common.skipUnlessWindows
205 def test_lookup_account_name_or_sid_unresolvable(self):
206 """An unresolvable SID falls back to its string form (issue #2271).
207
208 Reproduces the dual-boot / shared NTFS scenario where
209 ``LookupAccountSid`` fails because the SID belongs to an
210 account from the other Windows installation. The helper must
211 not raise; it should return the SID string so the ownership
212 comparison can still proceed by SID.
213 """
214 import win32security
215 bogus = 'S-1-5-21-1234567890-1234567890-1234567890-1234'
216 sid = win32security.ConvertStringSidToSid(bogus)
217 name, _ = GuiStartup._lookup_account_name_or_sid(sid)
218 self.assertEqual(name, bogus)