| 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 Network |
| 9 |
""" |
| 10 |
|
| 11 |
# standard imports |
| 12 |
import http.server |
| 13 |
import ipaddress |
| 14 |
import logging |
| 15 |
import os |
| 16 |
import threading |
| 17 |
import unittest |
| 18 |
import warnings |
| 19 |
from unittest.mock import MagicMock, Mock, patch |
| 20 |
|
| 21 |
# Suppress urllib3's NotOpenSSLWarning (raised when the ssl module is |
| 22 |
# not OpenSSL, e.g. macOS LibreSSL) before importing requests, which |
| 23 |
# would otherwise become an error under PYTHONWARNINGS=error. |
| 24 |
warnings.filterwarnings("ignore", message="urllib3 v2 only supports OpenSSL") |
| 25 |
|
| 26 |
# third party imports |
| 27 |
import requests |
| 28 |
|
| 29 |
# first party imports |
| 30 |
import bleachbit |
| 31 |
from tests import common |
| 32 |
from bleachbit import IS_WINDOWS |
| 33 |
from bleachbit.FileUtilities import delete |
| 34 |
from bleachbit.Network import (download_url_to_fn, fetch_url, get_gtk_version, |
| 35 |
get_ip_for_url, get_user_agent, unset_sslkeylogfile) |
| 36 |
|
| 37 |
logger = logging.getLogger(__name__) |
| 38 |
|
| 39 |
|
| 40 |
def response_to_error_msg(response): |
| 41 |
"""Convert response to error message""" |
| 42 |
return "URL: {url}\n" + \ |
| 43 |
f"Status: {response.status_code} {response.reason}\n" + \ |
| 44 |
f"Response headers: {dict(response.headers)}\n" + \ |
| 45 |
f"Response content: {response.text}" |
| 46 |
|
| 47 |
|
| 48 |
class _StatusCodeHandler(http.server.BaseHTTPRequestHandler): |
| 49 |
"""Reply with the HTTP status code named in the request path. |
| 50 |
|
| 51 |
A request for /status/404 responds with 404. Serving the codes |
| 52 |
locally keeps the tests off external services. |
| 53 |
""" |
| 54 |
|
| 55 |
# do_GET is the handler name required by http.server |
| 56 |
# pylint: disable-next=invalid-name |
| 57 |
def do_GET(self): |
| 58 |
try: |
| 59 |
status_code = int(self.path.rsplit('/', 1)[-1]) |
| 60 |
except ValueError: |
| 61 |
status_code = 400 |
| 62 |
body = b'BleachBit test server\n' |
| 63 |
self.send_response(status_code) |
| 64 |
self.send_header('Content-Type', 'text/plain') |
| 65 |
self.send_header('Content-Length', str(len(body))) |
| 66 |
self.end_headers() |
| 67 |
self.wfile.write(body) |
| 68 |
|
| 69 |
def log_message(self, *args): |
| 70 |
"""Silence the default per-request logging to stderr.""" |
| 71 |
|
| 72 |
|
| 73 |
class NetworkTestCase(common.BleachbitTestCase): |
| 74 |
"""Test case for module Network""" |
| 75 |
status_generator_url = None |
| 76 |
|
| 77 |
@classmethod |
| 78 |
def setUpClass(cls): |
| 79 |
super().setUpClass() |
| 80 |
cls._httpd = http.server.ThreadingHTTPServer( |
| 81 |
('127.0.0.1', 0), _StatusCodeHandler) |
| 82 |
cls._server_thread = threading.Thread( |
| 83 |
target=cls._httpd.serve_forever, daemon=True) |
| 84 |
cls._server_thread.start() |
| 85 |
host, port = cls._httpd.server_address |
| 86 |
cls.status_generator_url = f'http://{host}:{port}/status/{{}}' |
| 87 |
logger.info('Local status server: %s', cls.status_generator_url) |
| 88 |
|
| 89 |
@classmethod |
| 90 |
def tearDownClass(cls): |
| 91 |
cls._httpd.shutdown() |
| 92 |
cls._server_thread.join(timeout=5) |
| 93 |
cls._httpd.server_close() |
| 94 |
super().tearDownClass() |
| 95 |
|
| 96 |
def test_unset_sslkeylogfile(self): |
| 97 |
"""Test the function unset_sslkeylogfile().""" |
| 98 |
with common.set_temporary_env('SSLKEYLOGFILE', 'ssl.log'): |
| 99 |
self.assertEqual(unset_sslkeylogfile(True), IS_WINDOWS) |
| 100 |
self.assertFalse(unset_sslkeylogfile(True)) |
| 101 |
|
| 102 |
def test_download_url_to_fn(self): |
| 103 |
"""Unit test for function download_url_to_fn()""" |
| 104 |
# Test different HTTP status codes |
| 105 |
# 200: success |
| 106 |
# 404: not found (non-retryable error) |
| 107 |
# 500: server error (retryable error) |
| 108 |
tests = ((self.status_generator_url.format(200), True), |
| 109 |
(self.status_generator_url.format(404), False), |
| 110 |
(self.status_generator_url.format(500), False)) |
| 111 |
fn = os.path.join(self.tempdir, 'download') |
| 112 |
on_error_called = [False] |
| 113 |
|
| 114 |
def on_error(msg1, msg2): |
| 115 |
# Only print a simplified error message to avoid excessive output |
| 116 |
error_type = 'HTTP status' if 'HTTP status code' in str( |
| 117 |
msg2) else 'Connection' |
| 118 |
print( |
| 119 |
f'test on_error: {error_type} error for {msg1.split(":")[-1].strip()}') |
| 120 |
on_error_called[0] = True |
| 121 |
for (url, expected_rc) in tests: |
| 122 |
with self.subTest(url=url, expected_rc=expected_rc): |
| 123 |
self.assertNotExists(fn) |
| 124 |
on_error_called = [False] |
| 125 |
rc = download_url_to_fn(url, fn, None, |
| 126 |
on_error=on_error, timeout=20) |
| 127 |
err_msg = f'test_download_url_to_fn({url}) returned {rc} instead of {expected_rc}' |
| 128 |
self.assertEqual(rc, expected_rc, err_msg) |
| 129 |
if expected_rc: |
| 130 |
self.assertExists(fn) |
| 131 |
self.assertNotEqual(rc, on_error_called[0]) |
| 132 |
# minimal parameters |
| 133 |
rc = download_url_to_fn(url, fn) |
| 134 |
self.assertEqual(rc, expected_rc, err_msg) |
| 135 |
delete(fn, ignore_missing=True) |
| 136 |
|
| 137 |
@common.skipIfWindows |
| 138 |
def test_download_url_to_fn_creates_private_dir(self): |
| 139 |
"""download_url_to_fn() must create missing directories mode 0o700""" |
| 140 |
new_dir = os.path.join(self.tempdir, 'not', 'yet', 'created') |
| 141 |
fn = os.path.join(new_dir, 'download') |
| 142 |
self.assertNotExists(new_dir) |
| 143 |
|
| 144 |
rc = download_url_to_fn(self.status_generator_url.format(200), fn) |
| 145 |
self.assertTrue(rc) |
| 146 |
self.assertExists(fn) |
| 147 |
for created_dir in (new_dir, os.path.dirname(new_dir), |
| 148 |
os.path.dirname(os.path.dirname(new_dir))): |
| 149 |
mode = os.stat(created_dir).st_mode & 0o777 |
| 150 |
self.assertEqual(mode, 0o700, |
| 151 |
f'{created_dir} has mode {oct(mode)}, expected 0o700') |
| 152 |
|
| 153 |
def test_download_url_to_fn_refuses_symlink(self): |
| 154 |
"""download_url_to_fn() must not write the download through a symlink""" |
| 155 |
filename = self.write_file('download_target', text='keepme') |
| 156 |
fake_response = Mock() |
| 157 |
fake_response.status_code = 200 |
| 158 |
fake_response.content = b'attacker payload' |
| 159 |
with patch('bleachbit.Network.fetch_url', return_value=fake_response), \ |
| 160 |
patch('bleachbit.FileUtilities.os.path.islink', |
| 161 |
side_effect=lambda p: p == filename): |
| 162 |
with self.assertRaises(OSError): |
| 163 |
download_url_to_fn('https://example.invalid/x', filename) |
| 164 |
with open(filename, encoding='utf-8') as f: |
| 165 |
self.assertEqual(f.read(), 'keepme') |
| 166 |
|
| 167 |
def test_get_gtk_version(self): |
| 168 |
"""Unit test for get_gtk_version()""" |
| 169 |
gtk_ver = get_gtk_version() |
| 170 |
if gtk_ver is None: |
| 171 |
self.skipTest("GTK is not installed") |
| 172 |
self.assertIsInstance(gtk_ver, str) |
| 173 |
self.assertRegex(gtk_ver, r"^\d+\.\d+\.\d+$") |
| 174 |
|
| 175 |
def test_get_ip_for_url(self): |
| 176 |
"""Unit test for get_ip_for_url()""" |
| 177 |
for good_url in ('https://www.example.com', bleachbit.update_check_url): |
| 178 |
ip_str = get_ip_for_url(good_url) |
| 179 |
_ = ipaddress.ip_address(ip_str) |
| 180 |
for bad_url in (None, '', 'https://test.invalid'): |
| 181 |
ret = get_ip_for_url(bad_url) |
| 182 |
self.assertEqual(ret[0], '(', |
| 183 |
f'get_ip_for_url({bad_url})={ret}') |
| 184 |
|
| 185 |
def test_get_user_agent(self): |
| 186 |
"""Unit test for method get_user_agent()""" |
| 187 |
agent = get_user_agent() |
| 188 |
logger.debug("user agent = '%s'", agent) |
| 189 |
self.assertIsString(agent) |
| 190 |
|
| 191 |
def test_fetch_url_nonretry(self): |
| 192 |
"""Unit test for fetch_url() without retry""" |
| 193 |
status_codes = (200, 404) |
| 194 |
for status_code in status_codes: |
| 195 |
url = self.status_generator_url.format(status_code) |
| 196 |
with self.subTest(status_code=status_code): |
| 197 |
response = fetch_url(url, max_retries=0, timeout=5) |
| 198 |
error_msg = response_to_error_msg(response) |
| 199 |
self.assertEqual(response.status_code, status_code, |
| 200 |
error_msg) |
| 201 |
|
| 202 |
def test_fetch_url_headers(self): |
| 203 |
"""Unit test for fetch_url() header handling""" |
| 204 |
with patch('bleachbit.Network.requests.Session') as mock_session: |
| 205 |
session_instance = MagicMock() |
| 206 |
session_instance.get.return_value = Mock() |
| 207 |
mock_session.return_value.__enter__.return_value = session_instance |
| 208 |
|
| 209 |
tests = [ |
| 210 |
# (custom_headers, expected_custom_key) |
| 211 |
(None, None), |
| 212 |
({'X-BleachBit-Version': '5.1.0'}, 'X-BleachBit-Version'), |
| 213 |
] |
| 214 |
for custom_headers, expected_custom_key in tests: |
| 215 |
with self.subTest(custom_headers=custom_headers): |
| 216 |
response = fetch_url('https://example.com', max_retries=0, timeout=5, |
| 217 |
headers=custom_headers) |
| 218 |
kwargs = session_instance.get.call_args.kwargs |
| 219 |
headers = kwargs['headers'] |
| 220 |
self.assertEqual( |
| 221 |
response, session_instance.get.return_value) |
| 222 |
self.assertIsInstance(headers, dict) |
| 223 |
self.assertIn('User-Agent', headers) |
| 224 |
self.assertEqual(headers['User-Agent'], get_user_agent()) |
| 225 |
self.assertNotIn('X-OS-Type', headers) |
| 226 |
if expected_custom_key: |
| 227 |
self.assertIn(expected_custom_key, headers) |
| 228 |
self.assertEqual(headers[expected_custom_key], |
| 229 |
custom_headers[expected_custom_key]) |
| 230 |
else: |
| 231 |
self.assertNotIn('X-BleachBit-Version', headers) |
| 232 |
|
| 233 |
def test_fetch_url_retry(self): |
| 234 |
"""Unit test for fetch_url() with retry""" |
| 235 |
url = self.status_generator_url.format(500) |
| 236 |
with self.assertRaises(requests.exceptions.RetryError): |
| 237 |
fetch_url(url, max_retries=1, timeout=5) |
| 238 |
|
| 239 |
def test_fetch_url_invalid(self): |
| 240 |
"""Unit test for fetch_url() with invalid URL""" |
| 241 |
url = 'https://test.invalid' |
| 242 |
with self.assertRaises(requests.exceptions.RequestException): |
| 243 |
fetch_url(url) |
| 244 |
|
| 245 |
|
| 246 |
class MissingPackagesTestCase(unittest.TestCase): |
| 247 |
"""Test behavior when optional third-party packages are missing.""" |
| 248 |
|
| 249 |
def test_missing_requests(self): |
| 250 |
"""Network should be importable without requests.""" |
| 251 |
with common.mock_missing_package( |
| 252 |
'requests', 'urllib3', |
| 253 |
clear_prefixes=('bleachbit.Network', 'bleachbit.Update')): |
| 254 |
import bleachbit.Network as Network |
| 255 |
self.assertFalse(Network.HAVE_REQUESTS) |
| 256 |
with self.assertRaises(Network.RequestException): |
| 257 |
Network.fetch_url('https://example.com') |
| 258 |
|
| 259 |
def test_missing_urllib3(self): |
| 260 |
"""Missing urllib3 should set HAVE_URLLIB3 to False.""" |
| 261 |
with common.mock_missing_package( |
| 262 |
'urllib3', |
| 263 |
clear_prefixes=('bleachbit.Network',)): |
| 264 |
import bleachbit.Network as Network |
| 265 |
self.assertFalse(Network.HAVE_URLLIB3) |