78 lines
2.7 KiB
Python
78 lines
2.7 KiB
Python
"""The public proxy forwards GET and POST (with body) to the engine and reports a missing engine."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sys
|
|
import threading
|
|
import unittest
|
|
import urllib.error
|
|
import urllib.request
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from unittest import mock
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
|
|
import web_proxy as wp # noqa: E402
|
|
|
|
|
|
class Echo(BaseHTTPRequestHandler):
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
def _reply(self, payload):
|
|
data = json.dumps(payload).encode("utf-8")
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def do_GET(self):
|
|
self._reply({"method": "GET", "path": self.path})
|
|
|
|
def do_POST(self):
|
|
body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
|
self._reply({"method": "POST", "path": self.path, "body": json.loads(body or b"{}")})
|
|
|
|
|
|
def serve(handler):
|
|
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
return server
|
|
|
|
|
|
class ProxyTests(unittest.TestCase):
|
|
def test_forwards_get_and_post(self):
|
|
engine = serve(Echo)
|
|
with mock.patch.object(wp, "ENGINE", f"http://127.0.0.1:{engine.server_address[1]}"):
|
|
proxy = serve(wp.Proxy)
|
|
base = f"http://127.0.0.1:{proxy.server_address[1]}"
|
|
try:
|
|
got = json.loads(urllib.request.urlopen(base + "/api/state?x=1").read())
|
|
self.assertEqual(got, {"method": "GET", "path": "/api/state?x=1"})
|
|
req = urllib.request.Request(base + "/api/coin/A/start", data=json.dumps({"a": 1}).encode(),
|
|
method="POST", headers={"Content-Type": "application/json"})
|
|
got = json.loads(urllib.request.urlopen(req).read())
|
|
self.assertEqual(got["body"], {"a": 1})
|
|
finally:
|
|
for s in (proxy, engine):
|
|
s.shutdown()
|
|
s.server_close()
|
|
|
|
def test_missing_engine_is_502(self):
|
|
with mock.patch.object(wp, "ENGINE", "http://127.0.0.1:9"):
|
|
proxy = serve(wp.Proxy)
|
|
try:
|
|
with self.assertRaises(urllib.error.HTTPError) as ctx:
|
|
urllib.request.urlopen(f"http://127.0.0.1:{proxy.server_address[1]}/")
|
|
self.assertEqual(ctx.exception.code, 502)
|
|
finally:
|
|
proxy.shutdown()
|
|
proxy.server_close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|