Debian Codegraph @

tests/TestGuiChaff.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 GuiChaff
10 """
11
12
13 import tempfile
14 import threading
15 import time
16 import unittest
17 from unittest.mock import patch
18
19 from tests import common
20 from tests.common import pytest
21
22 from bleachbit.GtkShim import Gtk, GLib, Gio, is_gtk_available
23 from bleachbit.Options import options
24
25 HAVE_GTK = is_gtk_available()
26 if HAVE_GTK:
27 from bleachbit.GuiApplication import Bleachbit
28 from bleachbit.GuiChaff import (STOP_MODE_FILE_COUNT,
29 STOP_MODE_TOTAL_SIZE,
30 STOP_MODE_FREE_SPACE,
31 MAX_FILE_COUNT,
32 _make_should_stop,
33 _make_progress_cb)
34
35
36 @unittest.skipUnless(HAVE_GTK, 'requires GTK+ module')
37 @pytest.mark.xdist_group('gui')
38 class GuiChaffTestCase(common.BleachbitTestCase):
39 """Test case for module GuiChaff"""
40 app = Bleachbit(auto_exit=False, uac=False) if HAVE_GTK else None
41
42 @classmethod
43 def setUpClass(cls):
44 super().setUpClass()
45 # override, not set(): a plain set() is reverted by the per-test
46 # tearDown reload after the first test in the class
47 options.set_override('font_check_completed', True)
48
49 # Try to register the application, catch the error if already registered
50 glib_errors = []
51 try:
52 cls.app.register()
53 cls.app.hold() # Keep application alive during tests
54 with common.capture_glib_exceptions() as errs:
55 cls.app.activate()
56 cls.refresh_gui()
57 glib_errors.extend(errs)
58 except GLib.GError as e:
59 if not "already exported" in str(e):
60 raise
61 # Application already registered, just hold it
62 cls.app.hold()
63 # Try to get the default application and activate it
64 default_app = Gio.Application.get_default()
65 if default_app:
66 with common.capture_glib_exceptions() as errs:
67 default_app.activate()
68 cls.refresh_gui()
69 glib_errors.extend(errs)
70 if glib_errors:
71 _exc_type, exc_value, exc_tb = glib_errors[0]
72 raise exc_value.with_traceback(exc_tb)
73 cls.refresh_gui()
74
75 @classmethod
76 def tearDownClass(cls):
77 """Close the GUI"""
78 super().tearDownClass()
79 # Destroy the visible window on whichever application holds it.
80 # When running after TestGUI, the default application is TestGUI's
81 # instance and cls.app is an unregistered duplicate, so check both.
82 for app in (cls.app, Gio.Application.get_default()):
83 if app and getattr(app, '_window', None):
84 app._window.destroy()
85 app._window = None
86
87 @classmethod
88 def refresh_gui(cls, delay=0):
89 while Gtk.events_pending():
90 Gtk.main_iteration_do(blocking=False)
91 time.sleep(delay)
92
93 def setUp(self):
94 """Set up test fixtures before each test method."""
95 super().setUp()
96 from bleachbit.GuiChaff import ChaffDialog
97 # Pass the GtkWindow object
98 self.dialog = ChaffDialog(parent=self.app._window)
99
100 def tearDown(self):
101 """Clean up test fixtures after each test method."""
102 super().tearDown()
103 self.dialog.destroy()
104
105 def test_dialog_creation(self):
106 """Test that dialog is created with expected widgets"""
107 self.assertIsNotNone(self.dialog)
108 # Test combo box
109 self.assertIsNotNone(self.dialog.inspiration_combo)
110 self.assertEqual(self.dialog.inspiration_combo.get_active(), 0)
111 # Test stop mode combo
112 self.assertIsNotNone(self.dialog.stop_mode_combo)
113 self.assertEqual(self.dialog.stop_mode_combo.get_active(), 0)
114 # Test stop value spinner
115 self.assertIsNotNone(self.dialog.stop_value_spin)
116 self.assertEqual(self.dialog.stop_value_spin.get_value_as_int(), 100)
117 # Test folder chooser
118 self.assertIsNotNone(self.dialog.choose_folder_button)
119 self.assertEqual(
120 self.dialog.choose_folder_button.get_filename(),
121 tempfile.gettempdir())
122
123 def test_combo_options(self):
124 """Test that combo box has correct options"""
125 expected_options = ('2600 Magazine', "Hillary Clinton's emails")
126 self.assertEqual(
127 self.dialog.inspiration_combo_options, expected_options)
128 for i, option in enumerate(expected_options):
129 self.dialog.inspiration_combo.set_active(i)
130 self.assertEqual(
131 self.dialog.inspiration_combo.get_active_text(),
132 option)
133
134 def test_stop_value_spinner_file_count(self):
135 """Test stop value spinner limits for file count mode"""
136 self.dialog.stop_mode_combo.set_active(STOP_MODE_FILE_COUNT)
137 self.dialog.stop_value_spin.set_value(1)
138 self.assertEqual(self.dialog.stop_value_spin.get_value_as_int(), 1)
139 self.dialog.stop_value_spin.set_value(MAX_FILE_COUNT)
140 self.assertEqual(
141 self.dialog.stop_value_spin.get_value_as_int(), MAX_FILE_COUNT)
142 # Test out of bounds values
143 self.dialog.stop_value_spin.set_value(0)
144 self.assertEqual(self.dialog.stop_value_spin.get_value_as_int(), 1)
145 self.dialog.stop_value_spin.set_value(MAX_FILE_COUNT + 1)
146 self.assertEqual(
147 self.dialog.stop_value_spin.get_value_as_int(), MAX_FILE_COUNT)
148
149 def test_stop_value_spinner_total_size(self):
150 """Test stop value spinner limits for total size mode"""
151 self.dialog.stop_mode_combo.set_active(STOP_MODE_TOTAL_SIZE)
152 self.dialog.stop_value_spin.set_value(1)
153 self.assertEqual(self.dialog.stop_value_spin.get_value_as_int(), 1)
154 self.dialog.stop_value_spin.set_value(999999)
155 self.assertEqual(
156 self.dialog.stop_value_spin.get_value_as_int(), 999999)
157
158 def test_stop_value_spinner_free_space(self):
159 """Test stop value spinner limits for free space mode"""
160 self.dialog.stop_mode_combo.set_active(STOP_MODE_FREE_SPACE)
161 self.dialog.stop_value_spin.set_value(1)
162 self.assertEqual(self.dialog.stop_value_spin.get_value_as_int(), 1)
163 self.dialog.stop_value_spin.set_value(99)
164 self.assertEqual(self.dialog.stop_value_spin.get_value_as_int(), 99)
165 # Test out of bounds
166 self.dialog.stop_value_spin.set_value(0)
167 self.assertEqual(self.dialog.stop_value_spin.get_value_as_int(), 1)
168 self.dialog.stop_value_spin.set_value(100)
169 self.assertEqual(self.dialog.stop_value_spin.get_value_as_int(), 99)
170
171 def test_stop_mode_changed(self):
172 """Test that changing stop mode updates the label and adjustment"""
173 self.dialog.stop_mode_combo.set_active(STOP_MODE_TOTAL_SIZE)
174 self.refresh_gui()
175 self.assertIn('MB', self.dialog.stop_value_label.get_text())
176
177 self.dialog.stop_mode_combo.set_active(STOP_MODE_FREE_SPACE)
178 self.refresh_gui()
179 self.assertIn('%', self.dialog.stop_value_label.get_text())
180
181 self.dialog.stop_mode_combo.set_active(STOP_MODE_FILE_COUNT)
182 self.refresh_gui()
183 self.assertIn('files', self.dialog.stop_value_label.get_text().lower())
184
185 @patch('bleachbit.GuiChaff.make_files_thread')
186 @patch('bleachbit.Chaff.download_models')
187 @patch('bleachbit.Chaff.have_models')
188 def test_make_files(self, mock_have_models, mock_download_models, mock_make_files):
189 """Test make files functionality with automatic download"""
190 # Set up mocks
191 mock_have_models.return_value = False # Need to download models
192 mock_download_models.return_value = True
193
194 self.dialog.choose_folder_button.set_filename(self.tempdir)
195 self.dialog.stop_value_spin.set_value(10)
196 self.dialog.inspiration_combo.set_active(0)
197
198 # Simulate clicking make button
199 self.dialog.make_button.clicked()
200 self.refresh_gui(0.1)
201
202 # Verify models were downloaded
203 mock_download_models.assert_called_once()
204
205 # Verify make_files_thread was called with correct arguments
206 mock_make_files.assert_called_once()
207 args = mock_make_files.call_args[0]
208 self.assertEqual(args[0], 0) # stop_mode (file count)
209 self.assertEqual(args[1], 10) # stop_value
210 self.assertEqual(args[2], 0) # inspiration (2600)
211 self.assertEqual(args[3], self.tempdir) # output_folder
212 self.assertIsInstance(args[6], threading.Event) # abort_event
213
214 @patch('bleachbit.GuiChaff.make_files_thread')
215 @patch('bleachbit.Chaff.download_models')
216 @patch('bleachbit.Chaff.have_models')
217 def test_make_files_download_fails(self, mock_have_models, mock_download_models, mock_make_files):
218 """Test handling when download fails"""
219 mock_have_models.return_value = False # Need to download models
220 mock_download_models.return_value = False # Download fails
221
222 self.dialog.choose_folder_button.set_filename(self.tempdir)
223 self.dialog.stop_value_spin.set_value(10)
224 self.dialog.inspiration_combo.set_active(0)
225
226 # Simulate clicking make button
227 self.dialog.make_button.clicked()
228 self.refresh_gui(0.1)
229
230 # Verify models download was attempted
231 mock_download_models.assert_called_once()
232
233 # Verify make_files_thread was NOT called because download failed
234 mock_make_files.assert_not_called()
235
236 @patch('bleachbit.GuiChaff.make_files_thread')
237 @patch('bleachbit.Chaff.have_models')
238 def test_make_files_models_exist(self, mock_have_models, mock_make_files):
239 """Test making files when models already exist"""
240 mock_have_models.return_value = True # Models already exist
241
242 self.dialog.choose_folder_button.set_filename(self.tempdir)
243 self.dialog.stop_value_spin.set_value(10)
244 self.dialog.inspiration_combo.set_active(0)
245
246 # Simulate clicking make button
247 self.dialog.make_button.clicked()
248 self.refresh_gui(0.1)
249
250 # Verify make_files_thread was called with correct arguments
251 mock_make_files.assert_called_once()
252 self.assertIsInstance(mock_make_files.call_args, tuple)
253 args = mock_make_files.call_args[0]
254 self.assertEqual(args[0], 0) # stop_mode (file count)
255 self.assertEqual(args[1], 10) # stop_value
256 self.assertEqual(args[2], 0) # inspiration (2600)
257 self.assertEqual(args[3], self.tempdir) # output_folder
258 self.assertIsInstance(args[6], threading.Event) # abort_event
259
260 def test_progress_cb_keyword_args(self):
261 """Regression test: _make_progress_cb must accept keyword args from Chaff.py
262
263 Chaff.py calls on_progress(fraction, generated_file_names=..., cumulative_size=...)
264 so the callbacks must accept those keyword names.
265 """
266
267 collected = []
268
269 def on_progress(fraction):
270 collected.append(fraction)
271
272 for stop_mode in (STOP_MODE_FILE_COUNT, STOP_MODE_TOTAL_SIZE, STOP_MODE_FREE_SPACE):
273 cb = _make_progress_cb(stop_mode, 100, self.tempdir, on_progress)
274 # Must accept keyword arguments as Chaff.py passes them
275 cb(0.5, generated_file_names=['/tmp/fake'], cumulative_size=12345)
276 self.assertEqual(len(collected), 1, f'stop_mode={stop_mode}')
277 collected.clear()
278
279 def test_should_stop_keyword_args(self):
280 """Regression test: _make_should_stop must accept keyword args from Chaff.py
281
282 Chaff.py calls should_stop(generated_file_names, cumulative_size=...)
283 so the callbacks must accept those parameter names.
284 """
285
286 abort_event = threading.Event()
287
288 for stop_mode in (STOP_MODE_FILE_COUNT, STOP_MODE_TOTAL_SIZE, STOP_MODE_FREE_SPACE):
289 should_stop, _file_count = _make_should_stop(
290 stop_mode, 100, self.tempdir, abort_event)
291 # Must accept keyword argument as Chaff.py passes it
292 result = should_stop(['/tmp/fake'], cumulative_size=12345)
293 self.assertIsInstance(result, bool)
294
295 @patch('bleachbit.GuiChaff.make_files_thread')
296 @patch('bleachbit.Chaff.have_models')
297 def test_abort_button(self, mock_have_models, mock_make_files):
298 """Test that abort button sets the abort event"""
299 mock_have_models.return_value = True
300
301 self.dialog.choose_folder_button.set_filename(self.tempdir)
302 self.dialog.stop_value_spin.set_value(10)
303 self.dialog.inspiration_combo.set_active(0)
304
305 # Initially, the abort button should be disabled.
306 self.assertFalse(self.dialog.abort_button.get_sensitive())
307
308 # Start generation
309 self.dialog.make_button.clicked()
310 self.refresh_gui(0.1)
311
312 # The abort button should now be enabled.
313 self.assertTrue(self.dialog.abort_button.get_sensitive())
314
315 # Click abort.
316 self.dialog.abort_button.clicked()
317 self.refresh_gui()
318
319 # Verify that the abort event was set.
320 abort_event = mock_make_files.call_args[0][6]
321 self.assertIsInstance(abort_event, threading.Event)
322 self.assertTrue(abort_event.is_set())
323
324 @patch('bleachbit.GuiChaff.make_files_thread')
325 @patch('bleachbit.Chaff.have_models')
326 def test_make_files_error(self, mock_have_models, mock_make_files):
327 """Test that error from make_files_thread shows in infobar"""
328 mock_have_models.return_value = True
329
330 self.dialog.choose_folder_button.set_filename(self.tempdir)
331 self.dialog.stop_value_spin.set_value(10)
332 self.dialog.inspiration_combo.set_active(0)
333
334 self.dialog.make_button.clicked()
335 self.refresh_gui(0.1)
336
337 # Get the on_progress callback passed to the thread
338 on_progress = mock_make_files.call_args[0][5]
339 on_progress(1.0, msg=None, is_done=True, error='Test error')
340 self.refresh_gui(0.1)
341
342 self.assertTrue(self.dialog.infobar.get_visible())
343 self.assertIn('Test error', self.dialog.infobar_label.get_text())
344 self.assertEqual(
345 self.dialog.infobar.get_message_type(), Gtk.MessageType.ERROR)
346 self.assertFalse(self.dialog.progressbar.get_visible())
347 self.assertFalse(self.dialog.abort_button.get_sensitive())
348 self.assertTrue(self.dialog.make_button.get_sensitive())