"""Exercises the unmodified server.py POST handler in-process (the sandbox blocks sockets), from a temporary copy, and checks the app.js price formula in Python. Standard library only.""" import io, json, os, shutil, sys, tempfile, filecmp, importlib.util from email.message import Message HERE = os.path.dirname(os.path.abspath(__file__)) SITE = os.path.join(HERE, '..', 'site') print('output/site/server.py identical to original site/server.py:', filecmp.cmp(os.path.join(SITE, 'server.py'), os.path.join(HERE, '..', '..', 'site', 'server.py'), shallow=False)) cwd = os.getcwd() tmp = tempfile.mkdtemp() shutil.copy(os.path.join(SITE, 'server.py'), tmp) spec = importlib.util.spec_from_file_location('srv', os.path.join(tmp, 'server.py')) srv = importlib.util.module_from_spec(spec); spec.loader.exec_module(srv) # chdirs into tmp def post(path, payload): body = json.dumps(payload).encode() h = srv.Handler.__new__(srv.Handler) h.rfile, h.wfile = io.BytesIO(body), io.BytesIO() h.path, h.command, h.request_version = path, 'POST', 'HTTP/1.1' h.requestline = f'POST {path} HTTP/1.1'; h.client_address = ('127.0.0.1', 0) h.close_connection = True; h.log_message = lambda *a: None m = Message(); m['Content-Length'] = str(len(body)); m['Content-Type'] = 'application/json'; h.headers = m h.do_POST() return h.wfile.getvalue().split(b'\r\n', 1)[0].decode() def lines(): return open('submissions.jsonl').read().splitlines() if os.path.exists('submissions.jsonl') else [] try: cases = [ ('/api/leads', {'name': 'Ada Tester', 'email': 'ada@example.test', 'seats': 3}), ('/api/lead', {'name': 'Old Path', 'email': 'old@example.test', 'seats': 1}), # URL used by original app.js ('/api/leads', {'name': ' ', 'email': 'x@example.test', 'seats': 1}), ('/api/leads', {'name': 'Bad Mail', 'email': 'not-an-email', 'seats': 1}), ('/api/leads', {'name': 'Zero', 'email': 'z@example.test', 'seats': 0}), ('/api/leads', {'name': 'Nine', 'email': 'n@example.test', 'seats': 9}), ('/api/leads', {'name': 'Frac', 'email': 'f@example.test', 'seats': 2.5}), ] for path, payload in cases: before = len(lines()); status = post(path, payload) print(f'POST {path} {payload} -> {status}; records added: {len(lines()) - before}') print('final temp submissions.jsonl:', lines()) finally: os.chdir(cwd); shutil.rmtree(tmp) def total(seats): # mirrors calculateTotal in output/site/app.js sub = seats * 240; d = 0.10 if seats >= 3 else 0 return round(sub * (1 - d) * 1.12 * 100) / 100 for s, exp in [(1, '268.80'), (2, '537.60'), (3, '725.76'), (8, '1935.36')]: print(f'{s} seat(s): {total(s):.2f} expected {exp}', 'OK' if f'{total(s):.2f}' == exp else 'FAIL')