Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
157 lines
5.1 KiB
Python
157 lines
5.1 KiB
Python
"""Shared helpers: drive the real HTTP handler without opening a socket."""
|
|
|
|
import io
|
|
import json
|
|
import os
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
if ROOT not in sys.path:
|
|
sys.path.insert(0, ROOT)
|
|
|
|
import server as server_module # noqa: E402
|
|
|
|
|
|
class FakeSocket:
|
|
"""Stands in for a connected socket: feeds bytes in, captures bytes out."""
|
|
|
|
def __init__(self, request):
|
|
self.incoming = io.BytesIO(request)
|
|
self.outgoing = io.BytesIO()
|
|
|
|
def makefile(self, mode, bufsize=-1, *args, **kwargs):
|
|
return self.incoming if "r" in mode else self.outgoing
|
|
|
|
def close(self):
|
|
pass
|
|
|
|
def shutdown(self, *args, **kwargs):
|
|
pass
|
|
|
|
def sendall(self, data):
|
|
self.outgoing.write(data)
|
|
|
|
def send(self, data):
|
|
self.outgoing.write(data)
|
|
return len(data)
|
|
|
|
|
|
class FakeServer:
|
|
def __init__(self, app):
|
|
self.app = app
|
|
self.server_address = ("127.0.0.1", 0)
|
|
|
|
def log_message(self, fmt, *args):
|
|
pass
|
|
|
|
def log_error(self, fmt, *args):
|
|
pass
|
|
|
|
def log_request(self, *args):
|
|
pass
|
|
|
|
|
|
def raw_request(app, method, path, body=None, extra_headers=None):
|
|
"""Run one HTTP request through CRMRequestHandler and return the response."""
|
|
headers = {"Host": "127.0.0.1", "Connection": "close"}
|
|
payload = b""
|
|
if body is not None:
|
|
if isinstance(body, bytes):
|
|
payload = body
|
|
elif isinstance(body, str):
|
|
payload = body.encode("utf-8")
|
|
else:
|
|
payload = json.dumps(body).encode("utf-8")
|
|
headers["Content-Length"] = str(len(payload))
|
|
if payload and "Content-Type" not in (extra_headers or {}):
|
|
headers["Content-Type"] = "application/json"
|
|
headers.update(extra_headers or {})
|
|
lines = ["%s %s HTTP/1.1" % (method, path)]
|
|
lines.extend("%s: %s" % (key, value) for key, value in headers.items())
|
|
request = ("\r\n".join(lines) + "\r\n\r\n").encode("ascii") + payload
|
|
|
|
sock = FakeSocket(request)
|
|
server_module.CRMRequestHandler(sock, ("127.0.0.1", 1234), FakeServer(app))
|
|
raw = sock.outgoing.getvalue()
|
|
|
|
head, _, rest = raw.partition(b"\r\n\r\n")
|
|
status_line = head.split(b"\r\n")[0].decode("latin-1")
|
|
parts = status_line.split(" ", 2)
|
|
status = int(parts[1])
|
|
response_headers = {}
|
|
for line in head.split(b"\r\n")[1:]:
|
|
name, _, value = line.decode("latin-1").partition(":")
|
|
response_headers[name.strip().lower()] = value.strip()
|
|
length = int(response_headers.get("content-length", "0") or 0)
|
|
body_bytes = rest[:length]
|
|
data = None
|
|
if body_bytes and "application/json" in response_headers.get("content-type", ""):
|
|
data = json.loads(body_bytes.decode("utf-8"))
|
|
return status, data, response_headers, body_bytes
|
|
|
|
|
|
class ApiTestCase(unittest.TestCase):
|
|
"""Base class with a throwaway database per test."""
|
|
|
|
def setUp(self):
|
|
self.tmpdir = tempfile.mkdtemp(prefix="crm-test-")
|
|
self.db_path = os.path.join(self.tmpdir, "crm.db")
|
|
self.store = server_module.Store(self.db_path)
|
|
self.app = server_module.CRMApp(self.store, static_dir=server_module.STATIC_DIR)
|
|
|
|
def tearDown(self):
|
|
self.store.close()
|
|
shutil.rmtree(self.tmpdir, ignore_errors=True)
|
|
|
|
def request_full(self, method, path, body=None, extra_headers=None):
|
|
"""Same as :meth:`request` but also returns the raw response bytes."""
|
|
return raw_request(self.app, method, path, body, extra_headers)
|
|
|
|
def request(self, method, path, body=None, extra_headers=None):
|
|
status, data, headers, _ = self.request_full(method, path, body, extra_headers)
|
|
return status, data, headers
|
|
|
|
def get(self, path):
|
|
status, data, headers, _ = self.request_full("GET", path)
|
|
return status, data, headers
|
|
|
|
def post(self, path, body=None, **kwargs):
|
|
status, data, _, _ = self.request_full("POST", path, body, **kwargs)
|
|
return status, data
|
|
|
|
def put(self, path, body=None):
|
|
status, data, _, _ = self.request_full("PUT", path, body)
|
|
return status, data
|
|
|
|
def delete(self, path):
|
|
status, data, _, _ = self.request_full("DELETE", path)
|
|
return status, data
|
|
|
|
def create(self, resource, payload):
|
|
status, data = self.post("/api/%s" % resource, payload)
|
|
self.assertEqual(status, 201, "could not create %s: %r" % (resource, data))
|
|
return data
|
|
|
|
def create_company(self, name="Acme", **extra):
|
|
payload = {"name": name}
|
|
payload.update(extra)
|
|
return self.create("companies", payload)
|
|
|
|
def create_contact(self, name="Ada", **extra):
|
|
payload = {"name": name}
|
|
payload.update(extra)
|
|
return self.create("contacts", payload)
|
|
|
|
def create_deal(self, title="Big deal", **extra):
|
|
payload = {"title": title}
|
|
payload.update(extra)
|
|
return self.create("deals", payload)
|
|
|
|
def assert_bad_request(self, status, data, path):
|
|
self.assertEqual(status, 400, "expected 400 from %s, got %s: %r" % (path, status, data))
|
|
self.assertIsInstance(data, dict)
|
|
self.assertTrue(data.get("error"))
|