"""Run transport tests against an ephemeral loopback-only HTTP server.""" import http.server import pathlib import subprocess import sys import threading import time import urllib.parse PAYLOAD = bytes(range(256)) * 257 + b"TTDownloader-http" class Handler(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *args): pass def do_GET(self): path = urllib.parse.urlsplit(self.path).path if path == "/redirect": self.send_response(302) self.send_header("Location", "/plain") self.send_header("Content-Length", "0") self.end_headers() return if path == "/chunked": self.send_response(200) self.send_header("Transfer-Encoding", "chunked") self.end_headers() for offset in range(0, len(PAYLOAD), 1021): chunk = PAYLOAD[offset:offset+1021] self.wfile.write(("%x\r\n" % len(chunk)).encode("ascii") + chunk + b"\r\n") self.wfile.write(b"0\r\n\r\n") return if path in ("/large-length", "/overflow-length"): self.send_response(200) self.send_header("Content-Length", "5368709120" if path == "/large-length" else "9223372036854775808") self.send_header("Connection", "close") self.end_headers() self.close_connection = True return if path == "/slow": self.send_response(200) self.send_header("Content-Length", "1") self.end_headers() self.wfile.flush() # Leave enough margin for WinHTTP's coarse timeout polling. time.sleep(8) try: self.wfile.write(b"x") except (BrokenPipeError, ConnectionResetError): pass return body = PAYLOAD code = 200 content_range = None if path == "/context": if self.headers.get("Referer") != "https://example.test/source" or self.headers.get("User-Agent") != "TTDownloader Browser Bridge Test": code, body = 400, b"missing browser context" elif path == "/range": if self.headers.get("Range") != "bytes=123-": code, body = 400, b"wrong range" else: code, body = 206, PAYLOAD[123:] content_range = "bytes 123-%d/%d" % (len(PAYLOAD)-1, len(PAYLOAD)) elif path == "/unsatisfiable": code, body = 416, b"" content_range = "bytes */%d" % len(PAYLOAD) elif path not in ("/plain", "/ignore-range"): code, body = 404, b"missing" self.send_response(code) if content_range: self.send_header("Content-Range", content_range) self.send_header("Content-Length", str(len(body))) self.end_headers() try: self.wfile.write(body) except (BrokenPipeError, ConnectionResetError): pass class Server(http.server.ThreadingHTTPServer): daemon_threads = True def handle_error(self, request, address): # Closing an unread stream is part of the test, so connection resets are expected. pass if __name__ == "__main__": binary = pathlib.Path(sys.argv[1]).resolve() server = Server(("127.0.0.1", 0), Handler) worker = threading.Thread(target=server.serve_forever, daemon=True) worker.start() try: result = subprocess.run([str(binary), "http://127.0.0.1:%d" % server.server_port], timeout=40) code = result.returncode finally: server.shutdown() server.server_close() worker.join() sys.exit(code)