Debian Codegraph @

tests/TestDeepScan.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 DeepScan
10 """
11
12 # standard imports
13 import os
14 import shutil
15 import unittest
16 from unittest import mock
17
18 from tests.common import pytest
19
20 # first party imports
21 from tests import common
22 from tests import TestCleaner
23 from tests.common import SPECIAL_TEST_STRINGS
24 from bleachbit import IS_MAC, IS_WINDOWS, FS_CASE_SENSITIVE
25 from bleachbit.Options import options
26 from bleachbit.DeepScan import DeepScan, Search, normalized_walk
27
28 if IS_WINDOWS:
29 from tests.TestWindows import WindowsLinksMixIn
30 else:
31 WindowsLinksMixIn = object
32
33
34 class DeepScanTestCase(common.BleachbitTestCase, WindowsLinksMixIn):
35 """Test Case for module DeepScan"""
36
37 def _test_encoding(self, fn):
38 """Test encoding"""
39
40 fullpath = self.write_file(fn + ".bak")
41
42 # Add Unicode paths to encourage a crash.
43 subdir = os.path.join(self.tempdir, 'ɡælɪk.dir')
44 os.mkdir(subdir)
45 subfile = os.path.join(subdir, 'ɡælɪk.file')
46 common.touch_file(subfile)
47
48 searches = {self.tempdir: []}
49 searches[self.tempdir].append(
50 Search(command='delete', regex=r'\.[Bb][Aa][Kk]$'))
51 ds = DeepScan(searches)
52 found = False
53 for cmd in ds.scan():
54 if cmd == True:
55 # True is used to yield to GTK+, but it is not
56 # needed in this test.
57 continue
58 self.assertExists(cmd.path)
59 if cmd.path == fullpath:
60 found = True
61 self.assertTrue(found, "Did not find '%s'" % fullpath)
62
63 os.unlink(fullpath)
64 self.assertNotExists(fullpath)
65
66 shutil.rmtree(subdir)
67
68 @pytest.mark.no_xdist
69 def test_encoding(self):
70 """Test encoding"""
71 for test in SPECIAL_TEST_STRINGS:
72 self._test_encoding(test)
73
74 def test_DeepScan(self):
75 """Unit test for class DeepScan. Preview real files."""
76 path = os.path.expanduser('~')
77 searches = {path: []}
78 for regex in ('^Makefile$', '~$', 'bak$', '^Thumbs.db$', '^Thumbs.db:encryptable$'):
79 searches[path].append(Search(command='delete', regex=regex))
80 ds = DeepScan(searches)
81 for cmd in ds.scan():
82 if True == cmd:
83 # it's yielding control to the GTK idle loop
84 continue
85 self.assertLExists(cmd.path)
86
87 def test_skip_whitelisted_directory(self):
88 """DeepScan should not search whitelisted directories."""
89 # Reminder: each test case gets a new options directory,
90 # so we do not need to restore the old keep list (whitelist).
91 keep_dir = self.mkdir('keep')
92 search_dir = self.mkdir('search')
93 keep_file = self.write_file(os.path.join(keep_dir, 'skip.bbtestbak'))
94 search_file = self.write_file(
95 os.path.join(search_dir, 'find.bbtestbak'))
96
97 options.set_whitelist_paths([('folder', keep_dir)])
98 searches = {
99 self.tempdir: [
100 Search(command='delete', regex=r'\.bbtestbak$')
101 ]
102 }
103 paths = [
104 cmd.path
105 for cmd in DeepScan(searches).scan()
106 if cmd is not True
107 ]
108 self.assertNotIn(keep_file, paths)
109 self.assertIn(search_file, paths)
110
111 @common.skipUnlessWindows
112 def test_scan_does_not_follow_junction(self):
113 """DeepScan must not descend into a junction"""
114 scan_root = self.mkdir('scanroot')
115 victim = self.mkdir('victim')
116 self.write_file(os.path.join(victim, 'target.bbtestbak'))
117 self._create_win_junction(victim, os.path.join(scan_root, 'link'))
118
119 searches = {scan_root: [
120 Search(command='delete', regex=r'\.bbtestbak$')]}
121 paths = [cmd.path for cmd in DeepScan(
122 searches).scan() if cmd is not True]
123 self.assertEqual(paths, [], 'DeepScan followed a junction: %s' % paths)
124
125 def _get_compiled_search(self, wholeregex_substr):
126 """Return the CompiledSearch for the deepscan action whose
127 wholeregex contains the given substring (e.g. 'node_modules',
128 'venv')."""
129 import xml.etree.ElementTree as ET
130 from bleachbit.DeepScan import CompiledSearch
131
132 xml_path = os.path.join(
133 os.path.dirname(__file__), '..', 'cleaners', 'deepscan.xml')
134 root = ET.parse(xml_path).getroot()
135 wholeregex = None
136 nwholeregex = None
137 for action in root.iter('action'):
138 if action.get('wholeregex') and wholeregex_substr in action.get('wholeregex'):
139 wholeregex = action.get('wholeregex')
140 nwholeregex = action.get('nwholeregex')
141 break
142 self.assertIsNotNone(wholeregex)
143 self.assertIsNotNone(nwholeregex)
144 return CompiledSearch(Search(command='delete', wholeregex=wholeregex, nwholeregex=nwholeregex))
145
146 def test_node_modules_excludes_dot_dirs(self):
147 """node_modules option should exclude system/cache/editor directories."""
148 cs = self._get_compiled_search('node_modules')
149 excluded = [
150 ('/home/neo/.nvm/versions/node/v22.22.3/lib/node_modules/corepack', 'README.md'),
151 ('/home/trinity/.vscode/extensions/ms-python.python-2026.4.0-linux-x64/out/client/node_modules', 'sudo-prompt.js'),
152 ('/home/morpheus/.npm/_npx/15b07286cbcc3329/node_modules',
153 '.package-lock.json'),
154 ('/home/smith/.cache/typescript/5.9/node_modules', '.package-lock.json'),
155 (r'C:\Users\glados\.windsurf\extensions\ms-python.python-2026.4.0-universal\out\client\node_modules', 'unicode.js'),
156 (r'C:\Users\glados\.cursor\projects\empty-window\canvases\node_modules', 'cursor.js'),
157 (r'C:\Users\glados\AppData\Local\Programs\myapp\node_modules', 'file.js'),
158 (r'C:\Users\glados\AppData\Local\ApertureScience\MainframeCore\node_modules\central-processing', 'index.js'),
159 (r'C:\Users\Alice\AppData\Local\Programs\BeeperTexts\resources\app.asar.unpacked\node_modules\@beeper',
160 'beeper_client_sdk_napi_binding.node'),
161 (r'C:\Users\bob\AppData\Local\Programs\Microsoft VS Code\7e7950df89\resources\app',
162 'node_modules.asar'),
163 (r'C:\Users\mallory\AppData\Local\Programs\Microsoft VS Code\fcf604774b\resources\app',
164 'node_modules.asar'),
165 ('/home/trent/projects/important/node_modules_backup', 'README.md'),
166 ('/home/trent/projects/important', 'node_modules.asar'),
167 (r'C:\Users\charlie\Documents\important', 'node_modules.asar'),
168 (r'C:\Users\charlie\Documents\important\node_modules_backup', 'aes.js'),
169 ]
170 for dirpath, filename in excluded:
171 with self.subTest(dirpath=dirpath, filename=filename):
172 self.assertIsNone(
173 cs.match(dirpath, filename),
174 f"Should exclude {dirpath}/{filename}")
175
176 def test_node_modules_matches_ordinary_dirs(self):
177 """node_modules option should match ordinary user project directories."""
178 cs = self._get_compiled_search('node_modules')
179 matched = [
180 ('/home/sfalken/games/wopr/node_modules/joshua/ai', 'core.js'),
181 (r'C:\Users\esnowden\Documents\nsa\prism\node_modules\crypto-js', 'aes.js'),
182 (r'C:\Users\chunkylover53\Documents\work-from-home\node_modules\click-button-automator\node_modules\is-buffer', 'index.js'),
183 ('/home/chunkylover53/Downloads/donut-radar/node_modules/react-dom', 'bar.js'),
184 ]
185 for dirpath, filename in matched:
186 with self.subTest(dirpath=dirpath, filename=filename):
187 self.assertIsNotNone(
188 cs.match(dirpath, filename),
189 f"Should match {dirpath}/{filename}")
190
191 def test_venv_excludes_system_and_editor_dirs(self):
192 """venv option should exclude system/cache/editor directories and non-venv paths."""
193 cs = self._get_compiled_search('venv')
194 excluded = [
195 # venv cannot be directly under home
196 ('/home/username/.venv', 'pyvenv.cfg'),
197 # Python standard library venv module (not a virtual environment)
198 ('/home/username/.local/share/uv/python/cpython-3.12.11-linux-x86_64-gnu/lib/python3.12/venv',
199 '__init__.py'),
200 ('/home/username/.pyenv/versions/3.12.7/lib/python3.12/venv', '__init__.py'),
201 # pipx-managed venvs (managed by pipx, like npm cache)
202 ('/home/username/.local/share/pipx/venvs/duplicity', 'pyvenv.cfg'),
203 # typeshed stubs bundled with editor extensions
204 ('/home/username/.vscode/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/third_party/typeshed/stdlib/3/venv',
205 '__init__.pyi'),
206 # pyenv build patches
207 ('/home/username/.pyenv/plugins/python-build/share/python-build/patches/3.5.2/Python-3.5.2',
208 'venv.patch'),
209 # Windows: editor extensions and AppData
210 (r'C:\Users\glados\.vscode\extensions\ms-python.python-2026.4.0-universal\python_files\lib\jedilsp\jedi\third_party\typeshed\stdlib\3\venv',
211 '__init__.pyi'),
212 (r'C:\Users\glados\AppData\Local\ApertureScience\MainframeCore\venv', 'pyvenv.cfg'),
213 # Files/directories that contain venv (but not a venv directory)
214 ('/home/aturing/npl/ace_project/tools/', 'bootstrap_ace_venv.sh'),
215 ('/home/vonneumann/edvac/logs/', 'venv_build.log'),
216 ('/home/aturing/npl/ace_project/venv_tools/',
217 'requirements_numerics.txt'),
218 (r'C:\Users\charlie\Documents\important\venv_backup', 'pyvenv.cfg'),
219 # .venv bundled inside an AppData\Local application directory
220 (r'C:\Users\charlie\AppData\Local\AnkiProgramFiles\.venv\Lib\site-packages\PyQt6',
221 'QtCore.pyd'),
222 # Python standard library venv module under uv-managed Python (Windows)
223 (r'C:\Users\charlie\AppData\Roaming\uv\python\cpython-3.13.5-windows-x86_64-none\Lib\venv',
224 '__main__.py'),
225 ]
226 if IS_WINDOWS:
227 # Windows is case insensitive
228 # venv cannot be directly under home
229 excluded.append((r'c:\users\username\.VENV', 'pyvenv.cfg'))
230 for dirpath, filename in excluded:
231 with self.subTest(dirpath=dirpath, filename=filename):
232 self.assertIsNone(
233 cs.match(dirpath, filename),
234 f"Should exclude {dirpath}/{filename}")
235
236 def test_venv_matches_ordinary_dirs(self):
237 """venv option should match ordinary user project virtual environments."""
238 cs = self._get_compiled_search('venv')
239 matched = [
240 ('/home/genisys/t800/.venv/yolo-v666', 'pyvenv.cfg'),
241 ('/home/stark/jarvis/venv/yolo14', 'pyvenv.cfg'),
242 (r'C:\Users\esnowden\Documents\nsa\prism\venv', 'pyvenv.cfg'),
243 ]
244 if IS_WINDOWS:
245 # case insensitive
246 matched.append(
247 (r'C:\USERS\esnowden\Documents\nsa\prism\.VENV', 'pyvenv.cfg'))
248 matched.append(
249 (r'c:\USERS\pinky\world_domination\VENV\site-packages\hypnosisis', '__init__.py'))
250 for dirpath, filename in matched:
251 with self.subTest(dirpath=dirpath, filename=filename):
252 self.assertIsNotNone(
253 cs.match(dirpath, filename),
254 f"Should match {dirpath}/{filename}")
255
256 def _test_delete(self, command):
257 """Delete files in a test environment"""
258
259 # make some files
260 f_del = self.write_file('foo.txt.bbtestbak')
261 f_keep = self.write_file('foo.txt')
262 subdir = os.path.join(self.tempdir, 'sub')
263 os.mkdir(subdir)
264 f_del2 = self.write_file(os.path.join(subdir, 'bar.ini.bbtestbak'))
265 f_del3 = self.write_file(os.path.join(subdir, 'bar.ini.bbtestBAK'))
266
267 # sanity check
268 self.assertExists(f_del)
269 self.assertExists(f_keep)
270 self.assertExists(f_del2)
271
272 # run deep scan
273 def run_deep_scan(regex):
274 astr = '<action command="{}" search="deep" cache="false" path="{}" {}/>'.format(
275 command, self.tempdir, regex)
276 cleaner = TestCleaner.action_to_cleaner(astr)
277 from bleachbit.Worker import backends, Worker
278 backends['test'] = cleaner
279 operations = {'test': ['option1']}
280 from bleachbit import CLI
281 ui = CLI.CliCallback()
282 worker = Worker(ui, True, operations)
283 list(worker.run())
284 del backends['test']
285
286 # validate results
287 run_deep_scan(r'regex="\.bbtestbak$" wholeregex="sub.*\.bbtestbak$"')
288 self.assertExists(f_del)
289 self.assertExists(f_keep)
290 self.assertFalse(os.path.exists(f_del2))
291 if FS_CASE_SENSITIVE:
292 self.assertExists(f_del3)
293 else:
294 self.assertFalse(os.path.exists(f_del3))
295
296 # validate results
297 run_deep_scan(r'regex="\.bbtestbak$"')
298 self.assertFalse(os.path.exists(f_del))
299 self.assertExists(f_keep)
300
301 # cleanup
302 os.unlink(f_keep)
303 if FS_CASE_SENSITIVE:
304 os.unlink(f_del3)
305 os.rmdir(subdir)
306
307 def test_delete(self):
308 self._test_delete('delete')
309
310 def test_shred(self):
311 self._test_delete('shred')
312
313 @unittest.skipUnless(IS_MAC, 'Not on Darwin')
314 def test_normalized_walk_darwin(self):
315
316 with mock.patch('os.walk') as mock_walk:
317 mock_walk.return_value = [
318 ('/foo', ('bar',), ['ba\u0300z']),
319 ('/foo/bar', (), ['spam', 'eggs']),
320 ]
321 self.assertEqual(list(normalized_walk('.')), [
322 ('/foo', ('bar',), ['b\u00e0z']),
323 ('/foo/bar', (), ['spam', 'eggs']),
324 ])
325
326 with mock.patch('os.walk') as mock_walk:
327 expected = [
328 ('/foo', ('bar',), ['baz']),
329 ('/foo/bar', (), ['spam', 'eggs']),
330 ]
331 mock_walk.return_value = expected
332 self.assertEqual(list(normalized_walk('.')), expected)