File size: 17,262 Bytes
4d127e7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 | """
Tests for the generic HTTP transport boilerplate.
Every test runs against a local loopback server or a closed local port — no public
internet. These pin normalized response records, streaming downloads, partial-file
hygiene, session reuse, timeout normalization, and genuine async event-loop
responsiveness.
"""
from __future__ import annotations
#
###################################################################################################
###################################################################################################
################################################################################################### Standard Modules
#
import asyncio
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
#
###################################################################################################
###################################################################################################
################################################################################################### My Modules
#
from candlefetcher.util import http
from candlefetcher.util.http import HttpResponse, async_download, async_get, sync_download, sync_get
#
###################################################################################################
###################################################################################################
################################################################################################### Loopback Server
#
_LARGE_BODY = bytes(range(256)) * (1024 * 32) # 8 MiB across many stream chunks
class _LoopbackHandler(BaseHTTPRequestHandler):
"""
Deterministic loopback server covering success, statuses, delays, and streams.
"""
server_version = 'Loopback/1'
def log_message(self, format:str, *args:object) -> None:
"""Silence per-request console noise; tests assert on responses, not server logs."""
#
def do_GET(self) -> None:
"""Serve the fixture selected by the request path."""
if (self.path == '/text'):
body = 'hello candles'.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/plain; charset=utf-8')
self.send_header('X-Probe-Header', 'probe-value')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
#
elif (self.path == '/binary'):
body = bytes(range(256)) * 8
self.send_response(200)
self.send_header('Content-Type', 'application/octet-stream')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
#
elif (self.path == '/empty'):
self.send_response(200)
self.send_header('Content-Length', '0')
self.end_headers()
#
elif (self.path == '/large'):
self.send_response(200)
self.send_header('Content-Length', str(len(_LARGE_BODY)))
self.end_headers()
for offset in range(0, len(_LARGE_BODY), 64 * 1024):
self.wfile.write(_LARGE_BODY[offset:offset + (64 * 1024)])
#
#
elif (self.path == '/slow'):
time.sleep(1.0)
self.send_response(200)
self.send_header('Content-Length', '2')
self.end_headers()
self.wfile.write(b'ok')
#
elif (self.path == '/not-found'):
self.send_response(404)
self.send_header('Content-Length', '0')
self.end_headers()
#
elif (self.path == '/server-error'):
self.send_response(503)
self.send_header('Content-Length', '0')
self.end_headers()
#
else:
self.send_response(400)
self.send_header('Content-Length', '0')
self.end_headers()
#
#
#
@pytest.fixture(scope='module')
def loopback_server() -> 'tuple[str, object]':
"""Start one shared loopback server for the whole module and yield its base URL."""
server = ThreadingHTTPServer(('127.0.0.1', 0), _LoopbackHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield (f'http://127.0.0.1:{server.server_address[1]}', server)
server.shutdown()
server.server_close()
thread.join(timeout=5.0)
#
def _closed_port() -> int:
"""Reserve one ephemeral port, close it, and return a guaranteed-refused port."""
probe = socket.socket()
probe.bind(('127.0.0.1', 0))
port = probe.getsockname()[1]
probe.close()
return (port)
#
###################################################################################################
###################################################################################################
################################################################################################### Response Record
#
def test_response_record_helpers() -> None:
"""The response record exposes text decoding, ok-ness, and case-insensitive headers."""
response = HttpResponse(
status_code = 200,
headers = {'Content-Type': 'text/plain', 'X-MBX-USED-WEIGHT-1M': '118'},
content = 'data'.encode('utf-8'),
url = 'http://fixture/x',
)
assert (response.ok)
assert (response.text == 'data')
assert (response.header('content-type') == 'text/plain')
assert (response.header('X-MBX-USED-WEIGHT-1M') == '118')
assert (response.header('missing') is None)
failed = HttpResponse(0, {}, b'', 'http://fixture/x', error='connection refused')
assert (not failed.ok)
assert (failed.text == '')
#
def test_normalize_headers_defaults_user_agent() -> None:
"""Header normalization supplies the project user agent when none is given."""
assert (http._normalize_headers(None) == {'User-Agent': 'CandleFetcher'})
assert (http._normalize_headers({'X-A': '1'}) == {'X-A': '1'})
#
###################################################################################################
###################################################################################################
################################################################################################### Sync GET
#
def test_sync_get_text_success(loopback_server:'tuple[str, object]') -> None:
"""Sync GET returns status, headers, and decoded body."""
base_url, _ = loopback_server
response = sync_get(f'{base_url}/text', timeout=5.0)
assert (response.status_code == 200)
assert (response.ok)
assert (response.text == 'hello candles')
assert (response.header('X-Probe-Header') == 'probe-value')
assert (response.url == f'{base_url}/text')
#
def test_sync_get_binary_and_empty(loopback_server:'tuple[str, object]') -> None:
"""Binary bodies round-trip exactly and empty bodies stay empty."""
base_url, _ = loopback_server
binary = sync_get(f'{base_url}/binary', timeout=5.0)
empty = sync_get(f'{base_url}/empty', timeout=5.0)
assert (binary.content == bytes(range(256)) * 8)
assert (empty.status_code == 200)
assert (empty.content == b'')
#
def test_sync_get_http_error_statuses(loopback_server:'tuple[str, object]') -> None:
"""HTTP error statuses become response records, not exceptions."""
base_url, _ = loopback_server
missing = sync_get(f'{base_url}/not-found', timeout=5.0)
broken = sync_get(f'{base_url}/server-error', timeout=5.0)
assert (missing.status_code == 404)
assert (not missing.ok)
assert (broken.status_code == 503)
#
def test_sync_get_connection_refused() -> None:
"""Connection failures normalize to a status-0 record with the error text."""
response = sync_get(f'http://127.0.0.1:{_closed_port()}/x', timeout=2.0)
assert (response.status_code == 0)
assert (response.error is not None)
assert (not response.ok)
assert (response.content == b'')
#
def test_sync_get_timeout(loopback_server:'tuple[str, object]') -> None:
"""Server delays beyond the timeout normalize to a status-0 record."""
base_url, _ = loopback_server
response = sync_get(f'{base_url}/slow', timeout=0.2)
assert (response.status_code == 0)
assert (response.error is not None)
assert ('imeout' in response.error or 'timed out' in response.error.lower())
#
###################################################################################################
###################################################################################################
################################################################################################### Async GET
#
@pytest.mark.asyncio
async def test_async_get_matches_sync_semantics(loopback_server:'tuple[str, object]') -> None:
"""Async GET produces the same normalized record shape as sync GET."""
base_url, _ = loopback_server
response = await async_get(f'{base_url}/text', timeout=5.0)
assert (response.status_code == 200)
assert (response.ok)
assert (response.text == 'hello candles')
assert (response.header('X-Probe-Header') == 'probe-value')
#
@pytest.mark.asyncio
async def test_async_get_with_reused_session(loopback_server:'tuple[str, object]') -> None:
"""A caller-supplied session is reused and never closed by the helper."""
base_url, _ = loopback_server
async with http.async_session() as session:
first = await async_get(f'{base_url}/text', timeout=5.0, session=session)
second = await async_get(f'{base_url}/binary', timeout=5.0, session=session)
assert (first.ok)
assert (second.status_code == 200)
assert (second.content == bytes(range(256)) * 8)
#
#
@pytest.mark.asyncio
async def test_async_get_connection_refused() -> None:
"""Async connection failures normalize to the same status-0 record."""
response = await async_get(f'http://127.0.0.1:{_closed_port()}/x', timeout=2.0)
assert (response.status_code == 0)
assert (response.error is not None)
assert (not response.ok)
#
@pytest.mark.asyncio
async def test_async_get_timeout(loopback_server:'tuple[str, object]') -> None:
"""Async timeouts normalize to a status-0 record without raising."""
base_url, _ = loopback_server
response = await async_get(f'{base_url}/slow', timeout=0.2)
assert (response.status_code == 0)
assert (response.error is not None)
#
@pytest.mark.asyncio
async def test_async_get_cancellation_propagates(loopback_server:'tuple[str, object]') -> None:
"""Cancelling an in-flight async GET propagates CancelledError to the caller."""
base_url, _ = loopback_server
task = asyncio.ensure_future(async_get(f'{base_url}/slow', timeout=10.0))
await asyncio.sleep(0.1)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
#
#
@pytest.mark.asyncio
async def test_async_get_does_not_block_event_loop(loopback_server:'tuple[str, object]') -> None:
"""Waiting on a slow server leaves the loop responsive between heartbeats."""
base_url, _ = loopback_server
heartbeats = 0
max_gap = 0.0
last = time.monotonic()
async def heartbeat() -> None:
nonlocal heartbeats, max_gap, last
for _ in range(30):
await asyncio.sleep(0.01)
current = time.monotonic()
max_gap = max(max_gap, current - last)
last = current
heartbeats += 1
#
#
await asyncio.gather(heartbeat(), async_get(f'{base_url}/slow', timeout=10.0))
assert (heartbeats == 30)
# A blocking transport would stall the loop for the full one-second server delay.
assert (max_gap < 0.5)
#
###################################################################################################
###################################################################################################
################################################################################################### Sync Downloads
#
def test_sync_download_streams_large_file(loopback_server:'tuple[str, object]', tmp_path:Path) -> None:
"""Sync streaming downloads write the complete body through the part path."""
base_url, _ = loopback_server
part = tmp_path / 'large.zip.part'
response = sync_download(f'{base_url}/large', part, timeout=30.0)
assert (response.status_code == 200)
assert (response.content == b'')
assert (part.read_bytes() == _LARGE_BODY)
#
def test_sync_download_http_error_removes_partial(loopback_server:'tuple[str, object]', tmp_path:Path) -> None:
"""Failed sync downloads never leave a partial file behind."""
base_url, _ = loopback_server
part = tmp_path / 'missing.zip.part'
response = sync_download(f'{base_url}/not-found', part, timeout=5.0)
assert (response.status_code == 404)
assert (not part.exists())
#
def test_sync_download_connection_error_removes_partial(tmp_path:Path) -> None:
"""Transport failures during sync download clean up their partial file."""
part = tmp_path / 'refused.zip.part'
response = sync_download(f'http://127.0.0.1:{_closed_port()}/x', part, timeout=2.0)
assert (response.status_code == 0)
assert (response.error is not None)
assert (not part.exists())
#
###################################################################################################
###################################################################################################
################################################################################################### Async Downloads
#
@pytest.mark.asyncio
async def test_async_download_streams_large_file(loopback_server:'tuple[str, object]', tmp_path:Path) -> None:
"""Async streaming downloads write the complete body with genuine async I/O."""
base_url, _ = loopback_server
part = tmp_path / 'large.zip.part'
response = await async_download(f'{base_url}/large', part, timeout=30.0)
assert (response.status_code == 200)
assert (part.read_bytes() == _LARGE_BODY)
#
@pytest.mark.asyncio
async def test_async_download_http_error_removes_partial(loopback_server:'tuple[str, object]', tmp_path:Path) -> None:
"""Failed async downloads never leave a partial file behind."""
base_url, _ = loopback_server
part = tmp_path / 'missing.zip.part'
response = await async_download(f'{base_url}/not-found', part, timeout=5.0)
assert (response.status_code == 404)
assert (not part.exists())
#
@pytest.mark.asyncio
async def test_async_download_cancellation_removes_partial(loopback_server:'tuple[str, object]', tmp_path:Path) -> None:
"""Cancelling mid-download propagates and removes the partial file."""
base_url, _ = loopback_server
part = tmp_path / 'cancelled.zip.part'
task = asyncio.ensure_future(async_download(f'{base_url}/large', part, timeout=30.0))
await asyncio.sleep(0.05)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
#
await asyncio.sleep(0)
assert (not part.exists())
#
@pytest.mark.asyncio
async def test_async_download_does_not_block_event_loop(loopback_server:'tuple[str, object]', tmp_path:Path) -> None:
"""Streaming a slow large body keeps the loop responsive throughout."""
base_url, _ = loopback_server
part = tmp_path / 'slow-stream.zip.part'
heartbeats = 0
max_gap = 0.0
last = time.monotonic()
async def heartbeat() -> None:
nonlocal heartbeats, max_gap, last
for _ in range(30):
await asyncio.sleep(0.01)
current = time.monotonic()
max_gap = max(max_gap, current - last)
last = current
heartbeats += 1
#
#
await asyncio.gather(heartbeat(), async_download(f'{base_url}/large', part, timeout=30.0))
assert (heartbeats == 30)
assert (max_gap < 0.5)
assert (part.read_bytes() == _LARGE_BODY)
#
@pytest.mark.asyncio
async def test_async_download_with_reused_session(loopback_server:'tuple[str, object]', tmp_path:Path) -> None:
"""Downloads accept a caller-supplied session and leave it open for reuse."""
base_url, _ = loopback_server
part = tmp_path / 'session.zip.part'
async with http.async_session() as session:
response = await async_download(f'{base_url}/binary', part, timeout=10.0, session=session)
follow_up = await session.get(f'{base_url}/text', timeout=5.0)
assert (response.status_code == 200)
assert (part.read_bytes() == bytes(range(256)) * 8)
assert (follow_up.status_code == 200)
#
#
###################################################################################################
###################################################################################################
###################################################################################################
#
|