Debian Codegraph @

tests/TestUpdate.py

raw
1 # vim: ts=4:sw=4:expandtab
2
3 # BleachBit
4 # Copyright (C) 2008-2025 Andrew Ziem
5 # https://www.bleachbit.org
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
21 """
22 Test case for module Update
23 """
24
25
26 # standard imports
27 import http.client
28 import os
29 import os.path
30 from unittest.mock import Mock, patch
31 import xml.dom.minidom
32
33 # first party imports
34 from tests import common
35 import bleachbit
36 from bleachbit import logger, personal_cleaners_dir
37 from bleachbit.Network import fetch_url, RequestException
38 from bleachbit.Update import check_updates, update_winapp2
39
40
41 class UpdateTestCase(common.BleachbitTestCase):
42 """Test case for module Update"""
43
44 def test_check_updates_mock(self):
45 """Unit test for function check_updates() using mock"""
46 wa = '<winapp2 url="http://katana.oooninja.com/bleachbit/winapp2.ini" sha512="ce9e18252f608c8aff28811e372124d29a86404f328d3cd51f1f220578744bb8b15f55549eabfe8f1a80657fc940f6d6deece28e0532b3b0901a4c74110f7ba7"/>'
47 update_tests = [
48 ('<updates><stable ver="0.8.4">https://084</stable><beta ver="0.8.5beta">https://085beta</beta>%s</updates>' % wa,
49 [('0.8.4', 'https://084'), ('0.8.5beta', 'https://085beta')]),
50 ('<updates><stable ver="0.8.4">https://084</stable>%s</updates>' % wa,
51 [('0.8.4', 'https://084')]),
52 ('<updates><beta ver="0.8.5beta">https://085beta</beta>%s</updates>' % wa,
53 [('0.8.5beta', 'https://085beta')]),
54 ('<updates></updates>', [])]
55
56 with patch('bleachbit.Update.fetch_url') as mock_fetch:
57 # Configure mock responses
58 mock_response = Mock()
59 mock_response.status_code = 200
60 mock_response.content = b''
61
62 for xml_text, expected in update_tests:
63 # Set up mock response content
64 mock_response.text = xml_text
65 mock_response.content = xml_text.encode()
66 mock_fetch.return_value = mock_response
67
68 # Run test
69 updates = check_updates(True, False, None, None)
70 self.assertEqual(updates, expected)
71
72 # check_updates() must send update-specific headers
73 mock_fetch.assert_called()
74 _, fetch_kwargs = mock_fetch.call_args
75 sent_headers = fetch_kwargs['headers']
76 self.assertIn('X-BleachBit-Version', sent_headers)
77 self.assertIn('X-OS-Type', sent_headers)
78 self.assertIn('X-OS-Version', sent_headers)
79 self.assertIn('X-Locale', sent_headers)
80 if 'X-GTK-Version' in sent_headers:
81 self.assertIsInstance(sent_headers['X-GTK-Version'], str)
82
83 def test_check_updates_rejects_dtd(self):
84 """Update XML that declares a DTD is rejected"""
85 xml_text = ('<?xml version="1.0"?><!DOCTYPE u [<!ENTITY x "y">]>'
86 '<updates><stable ver="1">http://x</stable></updates>')
87 with patch('bleachbit.Update.fetch_url') as mock_fetch:
88 resp = Mock()
89 resp.status_code = 200
90 resp.text = xml_text
91 resp.content = xml_text.encode()
92 mock_fetch.return_value = resp
93 self.assertEqual(check_updates(True, False, None, None), [])
94
95 def test_check_updates_encoding_declaration(self):
96 """Update XML with an encoding declaration still parses"""
97 xml_text = ('<?xml version="1.0" encoding="UTF-8"?>'
98 '<updates><stable ver="9.9">https://999</stable></updates>')
99 with patch('bleachbit.Update.fetch_url') as mock_fetch:
100 resp = Mock()
101 resp.status_code = 200
102 resp.text = xml_text
103 resp.content = xml_text.encode()
104 mock_fetch.return_value = resp
105 self.assertEqual(check_updates(True, False, None, None),
106 [('9.9', 'https://999')])
107
108 def test_check_updates_rejects_insecure_url(self):
109 """A stable/beta update URL that is not https is ignored"""
110 xml_text = ('<updates><stable ver="1">http://insecure.example</stable>'
111 '<beta ver="2">https://secure.example</beta></updates>')
112 with patch('bleachbit.Update.fetch_url') as mock_fetch:
113 resp = Mock()
114 resp.status_code = 200
115 resp.text = xml_text
116 resp.content = xml_text.encode()
117 mock_fetch.return_value = resp
118 updates = check_updates(True, False, None, None)
119 self.assertEqual(updates, [('2', 'https://secure.example')])
120
121 def test_check_updates_real_network(self):
122 """Unit test for function check_updates() using real network"""
123 for update in check_updates(True, False, None, None):
124 if not update:
125 continue
126 ver, url = update
127 self.assertIsInstance(ver, (type(None), str))
128 self.assertIsInstance(url, (type(None), str))
129
130 def test_check_updates_bad_url(self):
131 """Unit test for function check_updates() with bad network address"""
132 # expect connection failure
133 preserve_url = bleachbit.update_check_url
134 for url in ('http://localhost/doesnotexist', 'https://httpstat.us/500'):
135 bleachbit.update_check_url = url
136 self.assertEqual(
137 check_updates(True, False, None, None),
138 [])
139 bleachbit.update_check_url = preserve_url
140
141 def test_update_url(self):
142 """Check that the real update URL returns XML"""
143 try:
144 response = fetch_url(bleachbit.update_check_url)
145 except RequestException as e:
146 self.skipTest(f'real network unavailable: {e}')
147 else:
148 self.assertEqual(response.status_code, 200)
149 self.assertTrue(response.text.startswith('<?xml version='))
150 xml.dom.minidom.parseString(response.text)
151
152 def test_update_winapp2(self):
153 fn = os.path.join(personal_cleaners_dir, 'winapp2.ini')
154 if os.path.exists(fn):
155 logger.info('deleting %s', fn)
156 os.unlink(fn)
157 self.addCleanup(lambda: os.path.exists(fn) and os.remove(fn))
158
159 url = 'https://download.bleachbit.org/winapp2/winapp2-2021-11-22.ini'
160
161 def expect_failure():
162 raise AssertionError('Call should have failed')
163
164 def on_success():
165 succeeded['r'] = True
166
167 succeeded = {'r': False} # scope
168
169 # bad hash
170 self.assertRaises(RuntimeError, update_winapp2, url,
171 "notahash", print, expect_failure)
172
173 # blank hash, download file
174 try:
175 update_winapp2(url, None, print, on_success)
176 except RuntimeError as e:
177 self.skipTest(f'real network unavailable: {e}')
178 self.assertTrue(succeeded['r'])
179
180 # blank hash, do not download again
181 update_winapp2(url, None, print, on_success)
182 update_winapp2(url, None, print, expect_failure)
183
184 def test_update_winapp2_insecure_url_rejected(self):
185 """An insecure winapp2 URL is refused before download, even with a hash"""
186 with patch('bleachbit.Update.download_url_to_fn') as mock_dl:
187 update_winapp2('http://example.invalid/winapp2.ini', None,
188 print, print)
189 update_winapp2('http://example.invalid/winapp2.ini', 'a' * 128,
190 print, print)
191 mock_dl.assert_not_called()
192
193 def test_environment(self):
194 """Check the sanity of the environment"""
195 self.assertTrue(hasattr(http.client, 'HTTPSConnection'))