| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import errno |
| 4 |
import importlib.util |
| 5 |
import logging |
| 6 |
import os |
| 7 |
import platform |
| 8 |
import socket |
| 9 |
import sys |
| 10 |
import typing |
| 11 |
import warnings |
| 12 |
from collections.abc import Sequence |
| 13 |
from functools import wraps |
| 14 |
from importlib.abc import Loader, MetaPathFinder |
| 15 |
from importlib.machinery import ModuleSpec |
| 16 |
from types import ModuleType, TracebackType |
| 17 |
|
| 18 |
import pytest |
| 19 |
|
| 20 |
try: |
| 21 |
try: |
| 22 |
import brotlicffi as brotli # type: ignore[import-not-found] |
| 23 |
except ImportError: |
| 24 |
import brotli # type: ignore[import-not-found] |
| 25 |
except ImportError: |
| 26 |
brotli = None |
| 27 |
|
| 28 |
try: |
| 29 |
if sys.version_info >= (3, 14): |
| 30 |
from compression import zstd as _unused_module_zstd # noqa: F401 |
| 31 |
else: |
| 32 |
from backports import zstd as _unused_module_zstd # noqa: F401 |
| 33 |
except ImportError: |
| 34 |
HAS_ZSTD = False |
| 35 |
else: |
| 36 |
HAS_ZSTD = True |
| 37 |
|
| 38 |
from urllib3.connectionpool import ConnectionPool |
| 39 |
from urllib3.exceptions import HTTPWarning |
| 40 |
|
| 41 |
try: |
| 42 |
import urllib3.contrib.pyopenssl as pyopenssl |
| 43 |
except ImportError: |
| 44 |
pyopenssl = None # type: ignore[assignment] |
| 45 |
|
| 46 |
|
| 47 |
_RT = typing.TypeVar("_RT") # return type |
| 48 |
_TestFuncT = typing.TypeVar("_TestFuncT", bound=typing.Callable[..., typing.Any]) |
| 49 |
|
| 50 |
|
| 51 |
# We need a host that will not immediately close the connection with a TCP |
| 52 |
# Reset. |
| 53 |
if platform.system() == "Windows": |
| 54 |
# Reserved loopback subnet address |
| 55 |
TARPIT_HOST = "127.0.0.0" |
| 56 |
else: |
| 57 |
# Reserved internet scoped address |
| 58 |
# https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml |
| 59 |
TARPIT_HOST = "240.0.0.0" |
| 60 |
|
| 61 |
# (Arguments for socket, is it IPv6 address?) |
| 62 |
VALID_SOURCE_ADDRESSES = [(("::1", 0), True), (("127.0.0.1", 0), False)] |
| 63 |
# RFC 5737: 192.0.2.0/24 is for testing only. |
| 64 |
# RFC 3849: 2001:db8::/32 is for documentation only. |
| 65 |
INVALID_SOURCE_ADDRESSES = [(("192.0.2.255", 0), False), (("2001:db8::1", 0), True)] |
| 66 |
|
| 67 |
# We use timeouts in three different ways in our tests |
| 68 |
# |
| 69 |
# 1. To make sure that the operation timeouts, we can use a short timeout. |
| 70 |
# 2. To make sure that the test does not hang even if the operation should succeed, we |
| 71 |
# want to use a long timeout, even more so on CI where tests can be really slow |
| 72 |
# 3. To test our timeout logic by using two different values, eg. by using different |
| 73 |
# values at the pool level and at the request level. |
| 74 |
SHORT_TIMEOUT = 0.001 |
| 75 |
LONG_TIMEOUT = 0.1 |
| 76 |
if os.environ.get("CI") or os.environ.get("GITHUB_ACTIONS") == "true": |
| 77 |
LONG_TIMEOUT = 0.5 |
| 78 |
|
| 79 |
DUMMY_POOL = ConnectionPool("dummy") |
| 80 |
|
| 81 |
|
| 82 |
def _can_resolve(host: str) -> bool: |
| 83 |
"""Returns True if the system can resolve host to an address.""" |
| 84 |
try: |
| 85 |
socket.getaddrinfo(host, None, socket.AF_UNSPEC) |
| 86 |
return True |
| 87 |
except socket.gaierror: |
| 88 |
return False |
| 89 |
|
| 90 |
|
| 91 |
# Some systems might not resolve "localhost." correctly. |
| 92 |
# See https://github.com/urllib3/urllib3/issues/1809 and |
| 93 |
# https://github.com/urllib3/urllib3/pull/1475#issuecomment-440788064. |
| 94 |
RESOLVES_LOCALHOST_FQDN = _can_resolve("localhost.") |
| 95 |
|
| 96 |
|
| 97 |
def clear_warnings(cls: type[Warning] = HTTPWarning) -> None: |
| 98 |
new_filters = [] |
| 99 |
for f in warnings.filters: |
| 100 |
if issubclass(f[2], cls): |
| 101 |
continue |
| 102 |
new_filters.append(f) |
| 103 |
warnings.filters[:] = new_filters # type: ignore[index] |
| 104 |
|
| 105 |
|
| 106 |
def setUp() -> None: |
| 107 |
clear_warnings() |
| 108 |
warnings.simplefilter("ignore", HTTPWarning) |
| 109 |
|
| 110 |
|
| 111 |
def notWindows() -> typing.Callable[[_TestFuncT], _TestFuncT]: |
| 112 |
"""Skips this test on Windows""" |
| 113 |
return pytest.mark.skipif( |
| 114 |
platform.system() == "Windows", |
| 115 |
reason="Test does not run on Windows", |
| 116 |
) |
| 117 |
|
| 118 |
|
| 119 |
def onlyBrotli() -> typing.Callable[[_TestFuncT], _TestFuncT]: |
| 120 |
return pytest.mark.skipif( |
| 121 |
brotli is None, reason="only run if brotli library is present" |
| 122 |
) |
| 123 |
|
| 124 |
|
| 125 |
def notBrotli() -> typing.Callable[[_TestFuncT], _TestFuncT]: |
| 126 |
return pytest.mark.skipif( |
| 127 |
brotli is not None, reason="only run if a brotli library is absent" |
| 128 |
) |
| 129 |
|
| 130 |
|
| 131 |
def onlyZstd() -> typing.Callable[[_TestFuncT], _TestFuncT]: |
| 132 |
return pytest.mark.skipif( |
| 133 |
not HAS_ZSTD, |
| 134 |
reason="only run if backports.zstd library is installed or Python 3.14 and later", |
| 135 |
) |
| 136 |
|
| 137 |
|
| 138 |
def notZstd() -> typing.Callable[[_TestFuncT], _TestFuncT]: |
| 139 |
return pytest.mark.skipif( |
| 140 |
HAS_ZSTD, |
| 141 |
reason="only run if backports.zstd library is not installed and Python 3.13 and earlier", |
| 142 |
) |
| 143 |
|
| 144 |
|
| 145 |
_requires_network_has_route = None |
| 146 |
|
| 147 |
|
| 148 |
def requires_network() -> typing.Callable[[_TestFuncT], _TestFuncT]: |
| 149 |
"""Helps you skip tests that require the network""" |
| 150 |
|
| 151 |
def _is_unreachable_err(err: Exception) -> bool: |
| 152 |
return getattr(err, "errno", None) in ( |
| 153 |
errno.ENETUNREACH, |
| 154 |
errno.EHOSTUNREACH, # For OSX |
| 155 |
) |
| 156 |
|
| 157 |
def _has_route() -> bool: |
| 158 |
try: |
| 159 |
sock = socket.create_connection((TARPIT_HOST, 80), 0.0001) |
| 160 |
sock.close() |
| 161 |
return True |
| 162 |
except TimeoutError: |
| 163 |
return True |
| 164 |
except OSError as e: |
| 165 |
if _is_unreachable_err(e): |
| 166 |
return False |
| 167 |
else: |
| 168 |
raise |
| 169 |
|
| 170 |
def _skip_if_no_route(f: _TestFuncT) -> _TestFuncT: |
| 171 |
"""Skip test exuction if network is unreachable""" |
| 172 |
|
| 173 |
@wraps(f) |
| 174 |
def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any: |
| 175 |
global _requires_network_has_route |
| 176 |
if _requires_network_has_route is None: |
| 177 |
_requires_network_has_route = _has_route() |
| 178 |
if not _requires_network_has_route: |
| 179 |
pytest.skip("Can't run the test because the network is unreachable") |
| 180 |
return f(*args, **kwargs) |
| 181 |
|
| 182 |
return typing.cast(_TestFuncT, wrapper) |
| 183 |
|
| 184 |
def _decorator_requires_internet( |
| 185 |
decorator: typing.Callable[[_TestFuncT], _TestFuncT], |
| 186 |
) -> typing.Callable[[_TestFuncT], _TestFuncT]: |
| 187 |
"""Mark a decorator with the "requires_internet" mark""" |
| 188 |
|
| 189 |
def wrapper(f: _TestFuncT) -> typing.Any: |
| 190 |
return pytest.mark.requires_network(decorator(f)) |
| 191 |
|
| 192 |
return wrapper |
| 193 |
|
| 194 |
return _decorator_requires_internet(_skip_if_no_route) |
| 195 |
|
| 196 |
|
| 197 |
def resolvesLocalhostFQDN() -> typing.Callable[[_TestFuncT], _TestFuncT]: |
| 198 |
"""Test requires successful resolving of 'localhost.'""" |
| 199 |
return pytest.mark.skipif( |
| 200 |
not RESOLVES_LOCALHOST_FQDN, |
| 201 |
reason="Can't resolve localhost.", |
| 202 |
) |
| 203 |
|
| 204 |
|
| 205 |
def withPyOpenSSL(test: typing.Callable[..., _RT]) -> typing.Callable[..., _RT]: |
| 206 |
@wraps(test) |
| 207 |
def wrapper(*args: typing.Any, **kwargs: typing.Any) -> _RT: |
| 208 |
if not pyopenssl: |
| 209 |
pytest.skip("pyopenssl not available, skipping test.") |
| 210 |
return test(*args, **kwargs) |
| 211 |
|
| 212 |
pyopenssl.inject_into_urllib3() |
| 213 |
result = test(*args, **kwargs) |
| 214 |
pyopenssl.extract_from_urllib3() |
| 215 |
return result |
| 216 |
|
| 217 |
return wrapper |
| 218 |
|
| 219 |
|
| 220 |
class _ListHandler(logging.Handler): |
| 221 |
def __init__(self) -> None: |
| 222 |
super().__init__() |
| 223 |
self.records: list[logging.LogRecord] = [] |
| 224 |
|
| 225 |
def emit(self, record: logging.LogRecord) -> None: |
| 226 |
self.records.append(record) |
| 227 |
|
| 228 |
|
| 229 |
class LogRecorder: |
| 230 |
def __init__(self, target: logging.Logger = logging.root) -> None: |
| 231 |
super().__init__() |
| 232 |
self._target = target |
| 233 |
self._handler = _ListHandler() |
| 234 |
|
| 235 |
@property |
| 236 |
def records(self) -> list[logging.LogRecord]: |
| 237 |
return self._handler.records |
| 238 |
|
| 239 |
def install(self) -> None: |
| 240 |
self._target.addHandler(self._handler) |
| 241 |
|
| 242 |
def uninstall(self) -> None: |
| 243 |
self._target.removeHandler(self._handler) |
| 244 |
|
| 245 |
def __enter__(self) -> list[logging.LogRecord]: |
| 246 |
self.install() |
| 247 |
return self.records |
| 248 |
|
| 249 |
def __exit__( |
| 250 |
self, |
| 251 |
exc_type: type[BaseException] | None, |
| 252 |
exc_value: BaseException | None, |
| 253 |
traceback: TracebackType | None, |
| 254 |
) -> typing.Literal[False]: |
| 255 |
self.uninstall() |
| 256 |
return False |
| 257 |
|
| 258 |
|
| 259 |
class ImportBlockerLoader(Loader): |
| 260 |
def __init__(self, fullname: str) -> None: |
| 261 |
self._fullname = fullname |
| 262 |
|
| 263 |
def load_module(self, fullname: str) -> ModuleType: |
| 264 |
raise ImportError(f"import of {fullname} is blocked") |
| 265 |
|
| 266 |
def exec_module(self, module: ModuleType) -> None: |
| 267 |
raise ImportError(f"import of {self._fullname} is blocked") |
| 268 |
|
| 269 |
|
| 270 |
class ImportBlocker(MetaPathFinder): |
| 271 |
""" |
| 272 |
Block Imports |
| 273 |
|
| 274 |
To be placed on ``sys.meta_path``. This ensures that the modules |
| 275 |
specified cannot be imported, even if they are a builtin. |
| 276 |
""" |
| 277 |
|
| 278 |
def __init__(self, *namestoblock: str) -> None: |
| 279 |
self.namestoblock = namestoblock |
| 280 |
|
| 281 |
def find_module( |
| 282 |
self, fullname: str, path: typing.Sequence[bytes | str] | None = None |
| 283 |
) -> Loader | None: |
| 284 |
if fullname in self.namestoblock: |
| 285 |
return ImportBlockerLoader(fullname) |
| 286 |
return None |
| 287 |
|
| 288 |
def find_spec( |
| 289 |
self, |
| 290 |
fullname: str, |
| 291 |
path: Sequence[bytes | str] | None, |
| 292 |
target: ModuleType | None = None, |
| 293 |
) -> ModuleSpec | None: |
| 294 |
loader = self.find_module(fullname, path) |
| 295 |
if loader is None: |
| 296 |
return None |
| 297 |
|
| 298 |
return importlib.util.spec_from_loader(fullname, loader) |
| 299 |
|
| 300 |
|
| 301 |
class ModuleStash(MetaPathFinder): |
| 302 |
""" |
| 303 |
Stashes away previously imported modules |
| 304 |
|
| 305 |
If we reimport a module the data from coverage is lost, so we reuse the old |
| 306 |
modules |
| 307 |
""" |
| 308 |
|
| 309 |
def __init__( |
| 310 |
self, namespace: str, modules: dict[str, ModuleType] = sys.modules |
| 311 |
) -> None: |
| 312 |
self.namespace = namespace |
| 313 |
self.modules = modules |
| 314 |
self._data: dict[str, ModuleType] = {} |
| 315 |
|
| 316 |
def stash(self) -> None: |
| 317 |
if self.namespace in self.modules: |
| 318 |
self._data[self.namespace] = self.modules.pop(self.namespace) |
| 319 |
|
| 320 |
for module in list(self.modules.keys()): |
| 321 |
if module.startswith(self.namespace + "."): |
| 322 |
self._data[module] = self.modules.pop(module) |
| 323 |
|
| 324 |
def pop(self) -> None: |
| 325 |
self.modules.pop(self.namespace, None) |
| 326 |
|
| 327 |
for module in list(self.modules.keys()): |
| 328 |
if module.startswith(self.namespace + "."): |
| 329 |
self.modules.pop(module) |
| 330 |
|
| 331 |
self.modules.update(self._data) |