Spaces:
Running
Running
File size: 2,767 Bytes
8f3b9c2 | 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 | """Integration tests for core.http_utils JsonRequestHandler."""
from __future__ import annotations
import http.client
import json
import threading
from http.server import ThreadingHTTPServer
from pathlib import Path
from core.http_utils import BodyTooLargeError, JsonRequestHandler
WEB_DIR = Path(__file__).resolve().parents[1] / "web"
class _DemoHandler(JsonRequestHandler):
allow_cors = True
max_body_bytes = 32
def do_GET(self) -> None:
if self.path == "/api/ping":
self.send_json(200, {"ok": True})
return
self.serve_static_file(WEB_DIR)
def do_POST(self) -> None:
try:
body = self.read_json_body()
except BodyTooLargeError:
self.send_json(413, {"error": "too large"})
return
if body is None:
self.send_json(400, {"error": "invalid json"})
return
self.send_json(200, {"echo": body})
def test_http_utils_json_cors_limit_and_static_serving() -> None:
server = ThreadingHTTPServer(("127.0.0.1", 0), _DemoHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
conn.request("GET", "/api/ping")
resp = conn.getresponse()
body = json.loads(resp.read().decode("utf-8"))
assert resp.status == 200
assert resp.getheader("Content-Type", "").startswith("application/json")
assert resp.getheader("Access-Control-Allow-Origin") == "*"
assert body == {"ok": True}
conn.request("POST", "/api/echo", body="{bad json", headers={"Content-Length": "9"})
resp = conn.getresponse()
resp.read()
assert resp.status == 400
oversized = "x" * 64
conn.request(
"POST",
"/api/echo",
body=oversized,
headers={"Content-Length": str(len(oversized))},
)
resp = conn.getresponse()
resp.read()
assert resp.status == 413
conn.request("GET", "/assets/js/app.js")
resp = conn.getresponse()
resp.read()
assert resp.status == 200
assert resp.getheader("Content-Type", "").startswith("text/javascript")
conn.request("GET", "/assets/css/tailwind.css")
resp = conn.getresponse()
resp.read()
assert resp.status == 200
assert resp.getheader("Content-Type", "").startswith("text/css")
conn.request("GET", "/../pyproject.toml")
resp = conn.getresponse()
resp.read()
assert resp.status == 403
conn.close()
finally:
server.shutdown()
server.server_close()
|