states = {'J1': {'state': 'succeeded', 'output': output}, 'J2': {'state': 'timed_out', 'fixture': True}}
class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        self.rfile.read(int(self.headers.get('Content-Length', '0')))
        body = b'{"task_id":"J1","state":"queued"}'
        self.send_response(202)
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)
    def do_GET(self):
        body = json.dumps(states[self.path.rsplit('/', 1)[-1]], ensure_ascii=False).encode()
        self.send_response(200)
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)
    def log_message(self, *_):
        pass
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
    base = f'http://127.0.0.1:{server.server_port}'
    with urllib.request.urlopen(urllib.request.Request(base + '/jobs', b'{}'), timeout=5) as response:
        check('本地提交真实返回202及任务编号', response.status == 202 and json.loads(response.read())['task_id'] == 'J1')
    for key in ['J1', 'J2']:
        with urllib.request.urlopen(base + '/jobs/' + key, timeout=5) as response:
            got = json.loads(response.read())
        check('本地查询状态：' + key, got['state'] == states[key]['state'])
finally:
    server.shutdown()
    server.server_close()
    thread.join(timeout=5)
result = {'api_result': output, 'local_status_replay': states, 'boundary': 'Local HTTP replay uses the saved real API result; delayed timeout is a labelled fixture'}
