Download test/util/test_http.py from MostafaRoohy/Project_CandleFetcher: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/datasets/MostafaRoohy/Project_CandleFetcher/resolve/main/test/util/test_http.py
- Command line
-
hf download hf://datasets/MostafaRoohy/Project_CandleFetcher/test/util/test_http.py
-
curl -L -o test_http.py https://huggingface.co/datasets/MostafaRoohy/Project_CandleFetcher/resolve/main/test/util/test_http.py
17.3 kB
| """ | |
| 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() | |
| # | |
| # | |
| # | |
| 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 | |
| # | |
| 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') | |
| # | |
| 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) | |
| # | |
| # | |
| 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) | |
| # | |
| 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) | |
| # | |
| 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 | |
| # | |
| # | |
| 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 | |
| # | |
| 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) | |
| # | |
| 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()) | |
| # | |
| 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()) | |
| # | |
| 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) | |
| # | |
| 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) | |
| # | |
| # | |
| ################################################################################################### | |
| ################################################################################################### | |
| ################################################################################################### | |
| # | |