scorpiox-bot-plugin-github
←mockapi.pypython
280 lines · 10 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/mockapi.py - a loopback mock of the GitHub REST API.
3
4One process serves every endpoint plugin_github calls, so the plugin's real
5request builders are exercised end to end:
6
7 GET /user the credential's account
8 GET /repos/{owner}/{repo} repository record (404 for repo "nope")
9 GET /repos/{owner}/{repo}/issues?state= issues array (a PR entry is
10 embedded to prove the PR filter works)
11 POST /repos/{owner}/{repo}/issues creates issue #4221
12 GET /repos/{owner}/{repo}/pulls/{n} pull request record
13 GET /search/code?q=... code search shape
14 GET /flaky 503 + Retry-After once, then 200
15
16Every request is appended to `--log` as one JSON line *before* the reply is
17written, recording method, path, query, the Authorization header and the
18parsed body. The suite compares that record against what each tool's request
19should have been - a reply-only assertion cannot see a wrong path, a dropped
20query parameter or a missing credential.
21
22The mock also implements the failure paths GitHub has: an unknown repo is
23404 {"message":"Not Found"}, a wrong token is 401 with GitHub's own message
24("Bad credentials"), a POST without a title is 422 with the errors array, and
25`?fail=401|403|404|422` forces any endpoint's error shape.
26
27Usage: python3 tests/mockapi.py --port 0 --portfile /tmp/p --log /tmp/log.jsonl
28"""
29
30import argparse
31import json
32import threading
33from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
34from urllib.parse import urlparse, parse_qs
35
36LOCK = threading.Lock()
37STATE = {"flaky_hits": 0}
38
39# Deliberately not real-looking: a suite that uses plausible PAT text ends up
40# shipping it in a screenshot one day.
41GOOD_TOKEN = "GHPAT-MOCK-TOKEN-1"
42# a second accepted credential: the suite's config-resolution test needs a
43# stored token that is distinctive (so a leak check can grep for it) AND
44# valid on the mock
45STORED_TOKEN = "STORED-TOKEN-AAA"
46# the token tests/e2e.py types into the page: distinctive (the DOM-leak
47# assertion greps for it) and valid on the mock
48E2E_TOKEN = "GHPAT-E2E-SAVED-1"
49# saving a request whose FIRST answer is a 503 + Retry-After proves the
50# plugin's single honest retry: this token makes /user flaky exactly once.
51FLAKY_TOKEN = "GHPAT-MOCK-RETRY-1"
52VALID_TOKENS = {GOOD_TOKEN, FLAKY_TOKEN, STORED_TOKEN, E2E_TOKEN}
53
54
55def repo(owner, repo_name):
56 return {
57 "id": 123456,
58 "name": repo_name,
59 "full_name": "%s/%s" % (owner, repo_name),
60 "description": "A mocked repository, with \"quotes\" and\nnewlines",
61 "html_url": "https://github.test/%s/%s" % (owner, repo_name),
62 "default_branch": "main",
63 "language": "C",
64 "visibility": "public",
65 "archived": False,
66 "license": {"spdx_id": "MIT"},
67 "stargazers_count": 1234,
68 "forks_count": 77,
69 "open_issues_count": 9,
70 "pushed_at": "2026-11-01T00:00:00Z",
71 }
72
73
74def issues(owner, repo_name):
75 return [
76 {"number": 12, "title": "Buffer overflow in parser",
77 "state": "open",
78 "html_url": "https://github.test/%s/%s/issues/12" % (owner, repo_name)},
79 {"number": 11, "title": "Docs\tTAB and ctrl\x01chars",
80 "state": "open",
81 "html_url": "https://github.test/%s/%s/issues/11" % (owner, repo_name)},
82 # a pull request embedded in /issues exactly like the real API:
83 {"number": 10, "title": "MUST BE FILTERED (this is a PR)",
84 "state": "open",
85 "pull_request": {"url": "https://api.github.test/x"},
86 "html_url": "https://github.test/%s/%s/pull/10" % (owner, repo_name)},
87 ]
88
89
90def pull(owner, repo_name, n):
91 return {
92 "number": int(n),
93 "title": "Add the mocked thing",
94 "state": "open",
95 "html_url": "https://github.test/%s/%s/pull/%s" % (owner, repo_name, n),
96 "user": {"login": "mockuser", "type": "User"},
97 "head": {"label": "%s:feature" % owner, "ref": "feature"},
98 "base": {"label": "%s:main" % owner, "ref": "main"},
99 "draft": False,
100 "merged_at": None,
101 "commits": 3,
102 "comments": 2,
103 "additions": 120,
104 "deletions": 40,
105 "created_at": "2026-11-02T10:00:00Z",
106 }
107
108
109def search(query):
110 return {
111 "total_count": 137,
112 "incomplete_results": False,
113 "items": [
114 {"name": "thing.c",
115 "path": "src/thing.c",
116 "html_url": "https://github.test/acme/widgets/blob/main/src/thing.c",
117 "repository": {"full_name": "acme/widgets"}},
118 {"name": "thing.h",
119 "path": "include/thing.h",
120 "html_url": "https://github.test/other/thing/blob/main/include/thing.h",
121 "repository": {"full_name": "other/thing"}},
122 ],
123 }
124
125
126class Handler(BaseHTTPRequestHandler):
127 log_message = lambda *a: None # silence
128
129 def _reply(self, code, obj):
130 body = json.dumps(obj).encode()
131 self.send_response(code)
132 self.send_header("Content-Type", "application/json")
133 self.send_header("Content-Length", str(len(body)))
134 self.end_headers()
135 self.wfile.write(body)
136
137 def _record(self, body_obj):
138 u = urlparse(self.path)
139 rec = {
140 "method": self.command,
141 "path": u.path,
142 "query": {k: v[0] for k, v in parse_qs(u.query).items()},
143 "auth": self.headers.get("Authorization") or "",
144 "accept": self.headers.get("Accept") or "",
145 "api_version": self.headers.get("X-GitHub-Api-Version") or "",
146 "body": body_obj,
147 }
148 with LOCK:
149 with open(self.logpath, "a") as f:
150 f.write(json.dumps(rec) + "\n")
151
152 def _check_auth(self, need):
153 auth = self.headers.get("Authorization") or ""
154 if auth[len("Bearer "):] in VALID_TOKENS:
155 return True
156 if need:
157 self._reply(401, {"message": "Bad credentials",
158 "documentation_url": "https://docs.github.test/401"})
159 return False
160 return True # unauthenticated public reads work like GitHub's public GETs
161
162 def do_GET(self):
163 self._handle("GET")
164
165 def do_POST(self):
166 self._handle("POST")
167
168 def _handle(self, method):
169 u = urlparse(self.path)
170 q = {k: v[0] for k, v in parse_qs(u.query).items()}
171 length = int(self.headers.get("Content-Length") or 0)
172 raw = self.rfile.read(length) if length else b""
173 try:
174 body_obj = json.loads(raw.decode()) if raw else None
175 except Exception:
176 body_obj = {"__unparseable__": raw.decode(errors="replace")}
177 self._record(body_obj)
178
179 if q.get("fail"):
180 code = int(q["fail"])
181 msg = {401: "Bad credentials",
182 403: "Resource not accessible by integration",
183 404: "Not Found", 422: "Validation Failed"}.get(code, "Err")
184 self._reply(code, {"message": msg})
185 return
186
187 parts = [p for p in u.path.split("/") if p]
188
189 # The flaky credential 503s its FIRST request (any path) with
190 # Retry-After: 1, then answers normally: exactly the upstream
191 # secondary-rate-limit shape the plugin must survive once.
192 if (self.headers.get("Authorization") or "") == "Bearer " + FLAKY_TOKEN:
193 with LOCK:
194 STATE["flaky_hits"] += 1
195 hits = STATE["flaky_hits"]
196 if hits == 1:
197 self.send_response(503)
198 self.send_header("Retry-After", "1")
199 self.send_header("Content-Length", "0")
200 self.end_headers()
201 return
202 self._reply(200, {"login": "mockuser", "type": "User",
203 "retry_proved": True})
204 return
205
206 # The suite reuses one mock process for the native pass, the CGI
207 # pass and the ASan pass. The flaky counter is process state, so a
208 # reset endpoint is the only way each pass can honestly observe
209 # "the FIRST request 503s" instead of inheriting pass #1's history.
210 if u.path == "/__reset":
211 with LOCK:
212 STATE["flaky_hits"] = 0
213 self._reply(200, {"ok": True, "flaky_hits": 0})
214 return
215
216 if u.path == "/user":
217 if not self._check_auth(True):
218 return
219 self._reply(200, {"login": "mockuser", "type": "User"})
220 return
221
222 if len(parts) == 3 and parts[0] == "repos" and method == "GET":
223 if parts[2] == "nope":
224 self._reply(404, {"message": "Not Found"})
225 return
226 self._reply(200, repo(parts[1], parts[2]))
227 return
228
229 if len(parts) >= 4 and parts[0] == "repos":
230 owner, repo_name = parts[1], parts[2]
231 tail = parts[3]
232 if repo_name == "nope":
233 self._reply(404, {"message": "Not Found"})
234 return
235 if tail == "issues" and method == "GET" and len(parts) == 4:
236 self._reply(200, issues(owner, repo_name))
237 return
238 if tail == "issues" and method == "POST" and len(parts) == 4:
239 if not self._check_auth(True):
240 return
241 if not body_obj or not body_obj.get("title"):
242 self._reply(422, {"message": "Validation Failed",
243 "errors": [{"message": "title is missing"}]})
244 return
245 self._reply(201, {
246 "number": 4221,
247 "title": body_obj.get("title"),
248 "state": "open",
249 "html_url": "https://github.test/%s/%s/issues/4221" % (owner, repo_name),
250 })
251 return
252 if tail == "pulls" and len(parts) == 5 and method == "GET":
253 self._reply(200, pull(owner, repo_name, parts[4]))
254 return
255
256 if u.path == "/search/code" and method == "GET":
257 if not self._check_auth(True): # /search/code requires auth upstream
258 return
259 self._reply(200, search(q.get("q", "")))
260 return
261
262 self._reply(404, {"message": "Not Found"})
263
264
265def main():
266 ap = argparse.ArgumentParser()
267 ap.add_argument("--port", type=int, default=0)
268 ap.add_argument("--portfile", required=True)
269 ap.add_argument("--log", required=True)
270 args = ap.parse_args()
271
272 srv = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
273 Handler.logpath = args.log
274 with open(args.portfile, "w") as f:
275 f.write(str(srv.server_address[1]))
276 srv.serve_forever()
277
278
279if __name__ == "__main__":
280 main()