Debian Codegraph @

tests/TestGtkShim.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 GtkShim
10 """
11
12 import ctypes
13 import os
14 import subprocess
15 import sys
16 import unittest
17 from unittest import mock
18
19 from tests.common import pytest
20
21 from tests import common
22 from bleachbit import IS_WINDOWS
23 from bleachbit.General import get_executable
24 from bleachbit.GtkShim import (
25 _build_error_html,
26 _fix_arg,
27 _handle_gtk_import_error,
28 _patched_argv,
29 _show_windows_error_dialog,
30 path_has_lib_or_bin,
31 )
32
33
34 class PathHasLibOrBinTestCase(unittest.TestCase):
35 """Test path_has_lib_or_bin() detection logic."""
36
37 def test_path_has_lib_or_bin(self):
38 """Test path_has_lib_or_bin() with various paths."""
39 tests = [
40 # (path, expected_result)
41 # Standalone 'bin' directory triggers detection
42 (r'C:\bin', 'bin'),
43 (r'C:\bin\xlib', 'bin'),
44 (r'C:\libx\bin', 'bin'),
45 (r'C:\bin\bin', 'bin'),
46 (r'C:\Users\username\Downloads\bin\BleachBit-Portable', 'bin'),
47 # Standalone 'lib' directory triggers detection
48 (r'C:\lib', 'lib'),
49 (r'C:\lib\xbin', 'lib'),
50 (r'C:\binx\lib', 'lib'),
51 (r'C:\lib\lib', 'lib'),
52 (r'C:\Users\username\Downloads\lib\BleachBit-Portable', 'lib'),
53 (r'C:\ProgramData\chocolatey\lib\bleachbit.portable\BleachBit-Portable', 'lib'),
54 # Detection is case-insensitive
55 (r'C:\Users\BIN\app', 'bin'),
56 (r'C:\Users\Lib\app', 'lib'),
57 # 'binx' is not 'bin'
58 (r'C:\Users\username\Downloads\binx\BleachBit-Portable', None),
59 # 'xbin' is not 'bin'
60 (r'C:\Users\username\Downloads\xbin\BleachBit-Portable', None),
61 # 'libfoo' is not 'lib'
62 (r'C:\ProgramData\libfoo\app', None),
63 # Normal portable path without lib or bin
64 (r'C:\Users\username\Downloads\BleachBit-5.0.0-portable\BleachBit-Portable', None),
65 # Empty path returns None
66 ('', None),
67 # 'lib' or 'bin' embedded in longer names should not match
68 (r'C:\calibre\library\app', None),
69 (r'C:\cabinet\app', None),
70 ]
71 case_functions = (
72 lambda x: x.lower(),
73 lambda x: x.upper(),
74 lambda x: x.title(),
75 lambda x: x.title().swapcase(),
76 )
77 for path, expected in tests:
78 with self.subTest(path=path, expected=expected):
79 joined = os.path.join(path, 'bleachbit.exe')
80 for func in case_functions:
81 self.assertEqual(path_has_lib_or_bin(
82 func(joined)), expected)
83
84
85 class BuildErrorHtmlTestCase(unittest.TestCase):
86 """Tests for _build_error_html()."""
87
88 def test_unknown_error_includes_traceback_and_sysinfo(self):
89 """Unknown-error HTML must include traceback and system information."""
90 html = _build_error_html(
91 RuntimeError('something broke'),
92 traceback_text='Traceback (most recent call last):...',
93 )
94 self.assertIn('Error: something broke', html)
95 self.assertIn('Traceback (most recent call last):...', html)
96 self.assertIn('System information:\n', html)
97 self.assertIn('textarea', html)
98 self.assertIn('Copy to clipboard', html)
99 self.assertIn("function copyBugReport()", html)
100 self.assertIn('get-help', html)
101 self.assertEqual(html.count('<textarea'), 1)
102 self.assertEqual(html.count('<pre>'), 0)
103
104 def test_unknown_error_escapes_html_in_error_message(self):
105 """Error message containing HTML special chars must be escaped."""
106 html = _build_error_html(
107 RuntimeError('<script>alert(1)</script>'),
108 )
109 self.assertNotIn('<script>', html)
110 self.assertIn('&lt;script&gt;', html)
111
112 def test_html_structure(self):
113 """Output must be valid minimal HTML with required elements."""
114 html = _build_error_html(
115 Exception('test'),
116 )
117 self.assertIn('<!DOCTYPE html>', html)
118 self.assertIn('<html', html)
119 self.assertIn('BleachBit cannot start', html)
120
121
122 class ShowWindowsErrorDialogTestCase(unittest.TestCase):
123 """Tests for _show_windows_error_dialog() (non-Windows stubs)."""
124
125 @common.skipUnlessWindows
126 def test_yes_writes_html_file(self):
127 """Selecting Yes must write the HTML file and open the browser."""
128 with mock.patch.object(
129 ctypes.windll.user32, 'MessageBoxW', return_value=6
130 ), mock.patch('webbrowser.open') as mock_open:
131 _show_windows_error_dialog('BleachBit', '<html>test</html>')
132 mock_open.assert_called_once()
133 html_path = mock_open.call_args[0][0].replace('file:///', '')
134 self.addCleanup(os.remove, html_path)
135 with open(html_path, encoding='utf-8') as f:
136 self.assertIn('test', f.read())
137
138 @common.skipUnlessWindows
139 def test_no_does_not_write_file(self):
140 """Selecting No must not open the browser."""
141 with mock.patch.object(
142 ctypes.windll.user32, 'MessageBoxW', return_value=7
143 ), mock.patch('webbrowser.open') as mock_open:
144 _show_windows_error_dialog('BleachBit', '<html/>')
145 mock_open.assert_not_called()
146
147
148 class HandleGtkImportErrorTestCase(unittest.TestCase):
149 """Tests for _handle_gtk_import_error()."""
150
151 @common.skipIfWindows
152 def test_noop_on_non_windows(self):
153 """Must do nothing on non-Windows platforms."""
154 with mock.patch('bleachbit.GtkShim._show_windows_error_dialog') as m:
155 _handle_gtk_import_error(ValueError('test'))
156 m.assert_not_called()
157
158 @common.skipUnlessWindows
159 def test_unknown_error_includes_traceback_in_html(self):
160 """Unknown errors must produce HTML with traceback section."""
161 with mock.patch('bleachbit.GtkShim._show_windows_error_dialog') as m, \
162 mock.patch('sys.frozen', True, create=True), \
163 mock.patch('sys.executable', r'C:\Users\user\Apps\BleachBit\bleachbit.exe'):
164 try:
165 raise RuntimeError('something broke')
166 except RuntimeError as e:
167 _handle_gtk_import_error(e)
168 m.assert_called_once()
169 _title, html = m.call_args[0]
170 self.assertIn('Traceback', html)
171 self.assertIn('System information', html)
172
173
174 class FixArgTestCase(unittest.TestCase):
175 """Tests for _fix_arg()."""
176
177 def test_ascii_unchanged(self):
178 """ASCII strings must pass through unchanged."""
179 self.assertEqual(_fix_arg('hello'), 'hello')
180
181 @pytest.mark.no_xdist
182 def test_surrogate_replaced(self):
183 """Unpaired surrogates must be replaced with the replacement character."""
184 arg = 'prefix' + chr(0xD800) + 'suffix'
185 fixed = _fix_arg(arg)
186 self.assertNotIn(chr(0xD800), fixed)
187 self.assertIn('\ufffd', fixed)
188
189 def test_valid_unicode_unchanged(self):
190 """Valid Unicode characters must pass through unchanged."""
191 self.assertEqual(_fix_arg('\u2014em-dash'), '\u2014em-dash')
192 self.assertEqual(_fix_arg('\U0001F525'), '\U0001F525')
193
194
195 class PatchedArgvTestCase(unittest.TestCase):
196 """Tests for _patched_argv()."""
197
198 def test_transform_applied(self):
199 """Transform function must be applied to all argv elements."""
200 original = sys.argv[:]
201 with _patched_argv(lambda a: a.swapcase()):
202 self.assertEqual(sys.argv, [a.swapcase() for a in original])
203 self.assertEqual(sys.argv, original)
204
205 def test_restored_on_exception(self):
206 """sys.argv must be restored even when exception occurs."""
207 original = sys.argv[:]
208
209 def boom():
210 with _patched_argv(lambda a: 'x'):
211 raise RuntimeError('boom')
212 self.assertRaises(RuntimeError, boom)
213 self.assertEqual(sys.argv, original)
214
215 def test_restores_reference_identity(self):
216 """sys.argv must be restored to the exact same object reference."""
217 original = sys.argv
218 with _patched_argv(lambda a: a):
219 pass
220 self.assertIs(sys.argv, original)
221
222
223 class TryImportGtkTestCase(unittest.TestCase):
224 """Test GTK import flow with surrogate paths in argv."""
225
226 def test_surrogate_in_argv(self):
227 """Must not crash for surrogates in sys.argv."""
228 bad_path = os.path.join(
229 'c:\\', 'temp', 'surrogate') + chr(0xD800) + 'beta_test0'
230
231 if IS_WINDOWS:
232 script = f'''
233 import ctypes
234 import sys
235 from unittest import mock
236 sys.argv = ['bleachbit.py', {bad_path!r}]
237 with mock.patch.object(ctypes.windll.user32, 'MessageBoxW', return_value=7):
238 from bleachbit.GtkShim import is_gtk_available
239 success = is_gtk_available()
240 print(f"OK success={{success}}")
241 '''
242 else:
243 script = f'''
244 import sys
245 sys.argv = ['bleachbit.py', {bad_path!r}]
246 from bleachbit.GtkShim import is_gtk_available
247 success = is_gtk_available()
248 print(f"OK success={{success}}")
249 '''
250
251 result = subprocess.run(
252 [get_executable(), '-c', script],
253 capture_output=True, text=True,
254 timeout=30, check=False,
255 )
256
257 self.assertEqual(result.returncode, 0,
258 f'stderr: {result.stderr}')
259 self.assertIn('OK success=', result.stdout,
260 'surrogate argv caused GTK import to crash')
261
262 @common.skipIfWindows
263 def test_no_display_does_not_import_gtk_libraries(self):
264 """A failed display precondition must not import gi.repository."""
265 script = '''
266 import sys
267 import bleachbit.GtkShim as shim
268 if shim.is_gtk_available():
269 sys.exit('is_gtk_available() is true without a display')
270 if shim.gtk_may_be_available():
271 sys.exit('gtk_may_be_available() is true without a display')
272 from bleachbit.GtkShim import Gtk
273 if Gtk is not None:
274 sys.exit('Gtk is not None without a display')
275 imported = [n for n in sys.modules if n.startswith('gi.repository')]
276 if imported:
277 sys.exit(f'imported GTK libraries: {imported}')
278 print('OK')
279 '''
280 env = os.environ.copy()
281 env.pop('DISPLAY', None)
282 env.pop('WAYLAND_DISPLAY', None)
283 env.pop('XDG_RUNTIME_DIR', None)
284 result = subprocess.run(
285 [get_executable(), '-c', script],
286 capture_output=True, text=True, env=env, timeout=30,
287 check=False,
288 )
289 self.assertEqual(result.returncode, 0,
290 f'stderr: {result.stderr}')
291 self.assertIn('OK', result.stdout, f'stderr: {result.stderr}')
292
293
294 class GtkAvailabilityTestCase(unittest.TestCase):
295 """Test actual and preflight GTK availability states."""
296
297 def test_require_gtk_reports_deferred_import_failure(self):
298 """A deferred import failure raises RuntimeError and reports the reason."""
299 import bleachbit.GtkShim as shim # pylint: disable=import-outside-toplevel
300
301 with mock.patch.multiple(
302 shim,
303 _gtk_preconditions_met=True,
304 _gtk_libraries_imported=False,
305 _gtk_libraries_available=False,
306 _gtk_unavailable_reason=None,
307 ), mock.patch.object(
308 shim, '_import_gtk_libraries',
309 return_value=(False, 'simulated GTK import failure'),
310 ):
311 self.assertTrue(shim.gtk_may_be_available())
312 self.assertFalse(shim.is_gtk_available())
313 with self.assertRaisesRegex(
314 RuntimeError, 'simulated GTK import failure',
315 ):
316 shim.require_gtk()
317
318
319 if __name__ == '__main__':
320 unittest.main()