sdtk-code-kit 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/assets/manifest/toolkit-bundle.manifest.json +82 -12
  4. package/assets/manifest/toolkit-bundle.sha256.txt +21 -7
  5. package/assets/toolkit/toolkit/AGENTS.md +1 -1
  6. package/assets/toolkit/toolkit/SDTKCODE_TOOLKIT.md +2 -2
  7. package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +4 -4
  8. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +4 -4
  9. package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +2 -2
  10. package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +2 -2
  11. package/assets/toolkit/toolkit/skills/code-discover/SKILL.md +3 -1
  12. package/assets/toolkit/toolkit/skills/code-ui-e2e/SKILL.md +97 -0
  13. package/assets/toolkit/toolkit/skills/code-ui-e2e/references/PROFILE_TEMPLATE.md +30 -0
  14. package/assets/toolkit/toolkit/skills/code-ui-e2e/references/SAFETY.md +17 -0
  15. package/assets/toolkit/toolkit/skills/code-ui-e2e/references/TEST_HOOKS.md +32 -0
  16. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/app_profile.py +118 -0
  17. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/build_test_app.py +140 -0
  18. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/cli.py +46 -0
  19. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/fault_proxy.py +381 -0
  20. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/run_smoke.py +242 -0
  21. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_app_profile.py +79 -0
  22. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_fault_proxy.py +327 -0
  23. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_run_smoke.py +79 -0
  24. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/uia_base.py +127 -0
  25. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/waits.py +40 -0
  26. package/package.json +1 -1
  27. package/src/lib/scope.js +1 -0
@@ -0,0 +1,242 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Runs a smoke suite (smoke/<suite>.py), whose cases carry the ids of the smoke-test markdown (ABC-FN-01 …).
3
+
4
+ python run_smoke.py smoke/abc.py
5
+ python run_smoke.py smoke/abc.py --only ABC-FN-01,ABC-ER-04
6
+ python run_smoke.py smoke/abc.py --list # every id of the markdown and how this suite covers it
7
+
8
+ A suite module declares:
9
+ SOURCE = r"...\\SMOKE_TEST_ABC_VI.md" # the markdown it implements (its ids are listed in the report)
10
+ CASES = {"ABC-FN-01": fn, ...} # fn(ctx); ctx.check / ctx.shot / ctx.visual / ctx.hold / ctx.note
11
+ MANUAL = {"ABC-ER-06": "network drive / USB"} # cases left to a tester, with the reason
12
+ make_driver(env) / make_api(env) # optional: the project's app driver and web API client
13
+ setup(ctx) / teardown(ctx) # optional, once per run
14
+
15
+ Result of a case: OK (every check passed), NG (a check failed or the case raised), 保留 (ctx.hold: cannot be judged now),
16
+ 要目視 (passed its checks but a screenshot must be looked at, ctx.visual). Ids of the markdown that the suite does not
17
+ implement are reported as 手動 (in MANUAL) or 未実装. Results: results/<timestamp>_<suite>/results.json + report.md, the
18
+ screenshots beside them as <id>[_<n>].png. Nothing is written into the markdown: a tester confirms the results first.
19
+ """
20
+ import argparse
21
+ import datetime
22
+ import importlib.util
23
+ import json
24
+ import os
25
+ import re
26
+ import sys
27
+ import time
28
+ import traceback
29
+
30
+ sys.stdout.reconfigure(encoding="utf-8")
31
+ HERE = os.path.dirname(os.path.abspath(__file__))
32
+ sys.path.insert(0, HERE)
33
+
34
+ # Same id pattern as sdtk-smoke-test-spec/scripts/validate_smoke_test.py (ID_RE): a suite code of one or more
35
+ # segments (HOME, G3-CSV), the group, the number. Keep the two in step.
36
+ CASE_ID = re.compile(r"^\|\s*\**([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*?-(?:UI|FN|ER|BV|RG)-\d+)\**\s*\|", re.M)
37
+
38
+
39
+ def markdown_ids(path) -> list[str]:
40
+ """The case ids of a smoke-test markdown, in order: rows starting with | **ID** | in section 4 (the case tables).
41
+ Other sections list ids too — the old suites' cases a phase 2 change replaces — and are not this suite's cases."""
42
+ with open(path, encoding="utf-8") as f:
43
+ text = f.read()
44
+ sections = re.split(r"^## ", text, flags=re.M)
45
+ text = next((s for s in sections if re.match(r"4[.\s]", s)), text)
46
+ seen, out = set(), []
47
+ for m in CASE_ID.finditer(text):
48
+ if m.group(1) not in seen:
49
+ seen.add(m.group(1))
50
+ out.append(m.group(1))
51
+ return out
52
+
53
+
54
+ class Hold(Exception):
55
+ """Raised by ctx.hold: the case cannot be judged now (a precondition is missing)."""
56
+
57
+
58
+ class Ctx:
59
+ """What a case function gets. The app driver and the web API are created on first use: a suite that only runs
60
+ command lines never starts the app."""
61
+
62
+ def __init__(self, env, out_dir, case_id=None):
63
+ self.env, self.out_dir, self.case_id = env, out_dir, case_id
64
+ self._driver = self._api = None
65
+ self.state = {} # shared by the cases of one run (setup puts things here)
66
+ self.reset()
67
+
68
+ def reset(self, case_id=None):
69
+ self.case_id = case_id
70
+ self.failures, self.passes, self.notes, self.visuals, self.shots = [], [], [], [], []
71
+
72
+ # The suite module provides make_driver(env) / make_api(env) (the project's app driver and web API client); the
73
+ # runner calls them on first use only.
74
+ make_driver = make_api = None
75
+
76
+ @property
77
+ def d(self):
78
+ if self._driver is None:
79
+ if self.make_driver is None:
80
+ raise RuntimeError("the suite defines no make_driver(env)")
81
+ self._driver = self.make_driver(self.env)
82
+ return self._driver
83
+
84
+ @property
85
+ def api(self):
86
+ if self._api is None:
87
+ if self.make_api is None:
88
+ raise RuntimeError("the suite defines no make_api(env)")
89
+ self._api = self.make_api(self.env)
90
+ return self._api
91
+
92
+ def check(self, ok, what):
93
+ (self.passes if ok else self.failures).append(what)
94
+ return bool(ok)
95
+
96
+ def note(self, text):
97
+ self.notes.append(text)
98
+
99
+ def visual(self, text):
100
+ self.visuals.append(text)
101
+
102
+ def hold(self, reason):
103
+ raise Hold(reason)
104
+
105
+ def shot(self, suffix=None, window=None):
106
+ """Screenshot of the 設定 window (or `window`, a pywinauto wrapper) as <id>[_<suffix>].png."""
107
+ name = self.case_id + (f"_{suffix}" if suffix else "") + ".png"
108
+ path = os.path.join(self.out_dir, name)
109
+ if window is None:
110
+ self.d.screenshot(path)
111
+ else:
112
+ from PIL import ImageGrab
113
+ r = window.rectangle()
114
+ ImageGrab.grab(bbox=(r.left, r.top, r.right, r.bottom), all_screens=True).save(path)
115
+ self.shots.append(name)
116
+
117
+
118
+ def load_suite(path):
119
+ spec = importlib.util.spec_from_file_location("smoke_suite_" + os.path.splitext(os.path.basename(path))[0], path)
120
+ module = importlib.util.module_from_spec(spec)
121
+ spec.loader.exec_module(module)
122
+ for attr in ("SOURCE", "CASES"):
123
+ if not hasattr(module, attr):
124
+ raise SystemExit(f"{path}: the suite declares no {attr}")
125
+ return module
126
+
127
+
128
+ def coverage(suite) -> dict:
129
+ """id -> 'auto' / '手動: <reason>' / '未実装', for every id of the markdown plus any the suite adds."""
130
+ ids = markdown_ids(suite.SOURCE)
131
+ manual = getattr(suite, "MANUAL", {})
132
+ unknown = [i for i in list(suite.CASES) + list(manual) if i not in ids]
133
+ if unknown:
134
+ raise SystemExit(f"ids not in {os.path.basename(suite.SOURCE)}: {unknown}")
135
+ return {i: "auto" if i in suite.CASES else f"手動: {manual[i]}" if i in manual else "未実装" for i in ids}
136
+
137
+
138
+ def run_case(ctx, case_id, fn) -> dict:
139
+ ctx.reset(case_id)
140
+ started = time.time()
141
+ status, error = None, ""
142
+ try:
143
+ fn(ctx)
144
+ except Hold as h:
145
+ status, error = "保留", str(h)
146
+ except Exception as e: # noqa: BLE001 - a case that raises is NG, the run goes on
147
+ status, error = "NG", f"{type(e).__name__}: {e}"
148
+ ctx.note(traceback.format_exc(limit=4))
149
+ if status is None:
150
+ status = "NG" if ctx.failures else "要目視" if ctx.visuals else "OK"
151
+ return {"id": case_id, "status": status, "error": error, "failed": ctx.failures, "passed": ctx.passes,
152
+ "visual": ctx.visuals, "notes": ctx.notes, "shots": ctx.shots, "seconds": round(time.time() - started, 1)}
153
+
154
+
155
+ def build_info(env) -> dict:
156
+ """build_info.json of build_test_app.py, found beside the exe's out folder; {} for an exe built otherwise."""
157
+ exe = env.get("APP_EXE", "")
158
+ path = os.path.join(os.path.dirname(os.path.dirname(exe)), "build_info.json") if exe else ""
159
+ return json.load(open(path, encoding="utf-8")) if path and os.path.exists(path) else {}
160
+
161
+
162
+ def write_report(out_dir, suite_name, source, results, cover, info):
163
+ by_id = {r["id"]: r for r in results}
164
+ counts = {}
165
+ rows = []
166
+ for case_id, how in cover.items():
167
+ r = by_id.get(case_id)
168
+ status = r["status"] if r else ("手動" if how.startswith("手動") else "未実装" if how == "未実装" else "未実行")
169
+ counts[status] = counts.get(status, 0) + 1
170
+ detail = ""
171
+ if r:
172
+ detail = "; ".join(filter(None, [r["error"], *("✗ " + f for f in r["failed"]), *("👁 " + v for v in r["visual"])]))
173
+ elif how.startswith("手動"):
174
+ detail = how[3:].strip()
175
+ rows.append(f"| {case_id} | {status} | {detail.replace('|', '/')} | {' '.join(r['shots']) if r else ''} |")
176
+ head = [f"# {suite_name}", "",
177
+ f"- Nguồn: `{source}`",
178
+ f"- Build: {info.get('ref', '?')} `{info.get('sha', '?')[:7]}`" + (" + UIA patch" if info.get("patch") else ""),
179
+ f"- Chạy lúc: {datetime.datetime.now():%Y-%m-%d %H:%M}",
180
+ "- Tổng: " + " · ".join(f"{k} {v}" for k, v in sorted(counts.items())), "",
181
+ "| ID | KQ | Chi tiết | Ảnh |", "|---|---|---|---|"]
182
+ open(os.path.join(out_dir, "report.md"), "w", encoding="utf-8").write("\n".join(head + rows) + "\n")
183
+ json.dump({"suite": suite_name, "source": source, "build": info, "results": results, "coverage": cover},
184
+ open(os.path.join(out_dir, "results.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
185
+ return counts
186
+
187
+
188
+ def load_env(path):
189
+ """KEY=VALUE lines of a .env file (missing file: {}); never committed — it holds accounts."""
190
+ env = {}
191
+ if os.path.exists(path):
192
+ with open(path, encoding="utf-8") as f:
193
+ for line in f:
194
+ key, sep, value = line.strip().partition("=")
195
+ if sep and not key.startswith("#"):
196
+ env[key.strip()] = value.strip()
197
+ return env
198
+
199
+
200
+ def run(suite_path, only=(), env=None, results_root=None):
201
+ env = env if env is not None else load_env(os.path.join(HERE, ".env"))
202
+ suite = load_suite(suite_path)
203
+ cover = coverage(suite)
204
+ name = os.path.splitext(os.path.basename(suite_path))[0]
205
+ out_dir = os.path.join(results_root or os.path.join(HERE, "results"), f"{datetime.datetime.now():%Y%m%d-%H%M%S}_{name}")
206
+ os.makedirs(out_dir, exist_ok=True)
207
+ ids = [i for i in suite.CASES if not only or i in only]
208
+ ctx = Ctx(env, out_dir)
209
+ ctx.make_driver = getattr(suite, "make_driver", None)
210
+ ctx.make_api = getattr(suite, "make_api", None)
211
+ results = []
212
+ try:
213
+ if hasattr(suite, "setup"):
214
+ suite.setup(ctx)
215
+ for case_id in ids:
216
+ print(f"--- {case_id}", flush=True)
217
+ r = run_case(ctx, case_id, suite.CASES[case_id])
218
+ print(f" {r['status']}" + (f" {r['error']}" if r["error"] else ""), flush=True)
219
+ results.append(r)
220
+ finally:
221
+ if hasattr(suite, "teardown"):
222
+ suite.teardown(ctx)
223
+ counts = write_report(out_dir, name, suite.SOURCE, results, cover, build_info(env))
224
+ print("report:", os.path.join(out_dir, "report.md"), counts)
225
+ return out_dir, results
226
+
227
+
228
+ def main():
229
+ a = argparse.ArgumentParser()
230
+ a.add_argument("suite")
231
+ a.add_argument("--only", default="")
232
+ a.add_argument("--list", action="store_true")
233
+ args = a.parse_args()
234
+ if args.list:
235
+ for case_id, how in coverage(load_suite(args.suite)).items():
236
+ print(f"{case_id:<14} {how}")
237
+ return
238
+ run(args.suite, set(filter(None, args.only.split(","))))
239
+
240
+
241
+ if __name__ == "__main__":
242
+ main()
@@ -0,0 +1,79 @@
1
+ # -*- coding: utf-8 -*-
2
+ """app_profile — python -m unittest test_app_profile (from this folder). Uses its own registry key
3
+ (HKCU\\Software\\sdtk-code-ui-e2e-unittest) and temp folders; the app's real key and data folder are never touched."""
4
+ import os
5
+ import subprocess
6
+ import tempfile
7
+ import sys
8
+ import unittest
9
+
10
+ if sys.platform != "win32":
11
+ raise unittest.SkipTest("app_profile parks the app's registry key and data folder: Windows only")
12
+
13
+ import winreg # noqa: E402
14
+
15
+ import app_profile # noqa: E402
16
+
17
+ KEY = r"Software\sdtk-code-ui-e2e-unittest"
18
+
19
+
20
+ def values():
21
+ out, i = {}, 0
22
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, KEY) as k:
23
+ while True:
24
+ try:
25
+ name, value, _ = winreg.EnumValue(k, i)
26
+ except OSError:
27
+ return out
28
+ out[name] = value
29
+ i += 1
30
+
31
+
32
+ class AppProfileTests(unittest.TestCase):
33
+ def setUp(self):
34
+ self.tmp = tempfile.TemporaryDirectory()
35
+ self.data = os.path.join(self.tmp.name, "data")
36
+ os.makedirs(self.data)
37
+ open(os.path.join(self.data, "app.db"), "w").write("owner")
38
+ self.cfg = {"generations": [{"exe_name": "Old.exe", "data_dir": "%TEMP%\\old", "registry_key": "Software\\Old"},
39
+ {"exe_name": "App.exe", "data_dir": self.data, "registry_key": KEY,
40
+ "data_files": ["app.db"]}],
41
+ "profile_values": {"BaseFolderPath": "{work}\\{label}"}, "clear_values": ["Session"]}
42
+ with winreg.CreateKey(winreg.HKEY_CURRENT_USER, KEY) as k:
43
+ winreg.SetValueEx(k, "Session", 0, winreg.REG_SZ, "owner session")
44
+ winreg.SetValueEx(k, "BaseFolderPath", 0, winreg.REG_SZ, "C:\\owner")
45
+ self.ident = app_profile.identity(self.cfg, r"C:\build\APP.EXE")
46
+ self.state = app_profile.OwnerState(self.ident, self.cfg, os.path.join(self.tmp.name, "state"),
47
+ os.path.join(self.tmp.name, "work"), running=lambda exe: False)
48
+
49
+ def tearDown(self):
50
+ subprocess.run(["reg", "delete", "HKCU\\" + KEY, "/f"], capture_output=True)
51
+ self.tmp.cleanup()
52
+
53
+ def test_identity_follows_the_exe(self):
54
+ self.assertEqual(self.ident.registry_key, KEY)
55
+ self.assertEqual(app_profile.identity(self.cfg, None).exe_name, "Old.exe")
56
+
57
+ def test_park_switch_restore_round_trip(self):
58
+ self.state.park()
59
+ self.assertFalse(os.path.exists(os.path.join(self.data, "app.db")))
60
+ self.state.switch_to("TK-1")
61
+ v = values()
62
+ self.assertEqual(v["BaseFolderPath"], os.path.join(self.tmp.name, "work", "TK-1"))
63
+ self.assertNotIn("Session", v)
64
+ open(os.path.join(self.data, "app.db"), "w").write("tk1")
65
+ self.state.restore()
66
+ self.assertEqual(open(os.path.join(self.data, "app.db")).read(), "owner")
67
+ self.assertEqual(values()["Session"], "owner session")
68
+ self.assertEqual(open(os.path.join(self.tmp.name, "state", "TK-1", "app.db")).read(), "tk1")
69
+
70
+ def test_refuses_while_the_app_runs(self):
71
+ state = app_profile.OwnerState(self.ident, self.cfg, os.path.join(self.tmp.name, "s2"), self.tmp.name,
72
+ running=lambda exe: True)
73
+ with self.assertRaisesRegex(RuntimeError, "is running"):
74
+ state.park()
75
+ self.assertTrue(os.path.exists(os.path.join(self.data, "app.db")))
76
+
77
+
78
+ if __name__ == "__main__":
79
+ unittest.main()
@@ -0,0 +1,327 @@
1
+ """Tests for fault_proxy.py - run with: python -m unittest test_fault_proxy (from this folder)
2
+
3
+ Stdlib only. A stand-in origin server is started, the proxy is put in front of it, and each mode is driven the way the
4
+ app (or a script) would drive it: through the proxy's own /__fault/mode path, then a request through the proxy.
5
+ """
6
+ import http.client
7
+ import http.server
8
+ import os
9
+ import socket
10
+ import subprocess
11
+ import sys
12
+ import threading
13
+ import time
14
+ import unittest
15
+
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ import fault_proxy as fp # noqa: E402
18
+
19
+
20
+ class Origin(http.server.BaseHTTPRequestHandler):
21
+ def do_GET(self):
22
+ body = b"origin-ok"
23
+ self.send_response(200)
24
+ self.send_header("Content-Length", str(len(body)))
25
+ self.end_headers()
26
+ self.wfile.write(body)
27
+
28
+ def do_POST(self):
29
+ data = self.rfile.read(int(self.headers.get("Content-Length", 0)))
30
+ self.send_response(200)
31
+ self.send_header("Content-Length", str(len(data)))
32
+ self.end_headers()
33
+ self.wfile.write(data)
34
+
35
+ def log_message(self, *args):
36
+ pass
37
+
38
+
39
+ _origin = None
40
+ _proxy_port = 0
41
+ _origin_port = 0
42
+
43
+
44
+ def setUpModule():
45
+ global _origin, _proxy_port, _origin_port
46
+ _origin = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Origin)
47
+ _origin_port = _origin.server_address[1]
48
+ threading.Thread(target=_origin.serve_forever, daemon=True).start()
49
+ server = fp.listen(0)
50
+ _proxy_port = server.getsockname()[1]
51
+ threading.Thread(target=fp.serve, args=(server,), daemon=True).start()
52
+
53
+
54
+ def tearDownModule():
55
+ _origin.shutdown()
56
+
57
+
58
+ def set_mode_by_request(key):
59
+ c = http.client.HTTPConnection("127.0.0.1", _proxy_port, timeout=3)
60
+ c.request("GET", f"/__fault/mode/{key}")
61
+ r = c.getresponse()
62
+ return r.status, r.read().decode()
63
+
64
+
65
+ def via_proxy(method="GET", body=None, timeout=3):
66
+ c = http.client.HTTPConnection("127.0.0.1", _proxy_port, timeout=timeout)
67
+ c.request(method, f"http://127.0.0.1:{_origin_port}/x?y=1", body=body)
68
+ r = c.getresponse()
69
+ return r, r.read()
70
+
71
+
72
+ class ControlPath(unittest.TestCase):
73
+ def test_setting_a_mode_answers_with_it_and_changes_it(self):
74
+ self.assertEqual((200, "mode=5"), set_mode_by_request("5"))
75
+ self.assertEqual("5", fp.MODE)
76
+
77
+ def test_asking_for_the_mode_reports_it_without_changing_it(self):
78
+ set_mode_by_request("7")
79
+ c = http.client.HTTPConnection("127.0.0.1", _proxy_port, timeout=3)
80
+ c.request("GET", "/__fault/mode")
81
+ r = c.getresponse()
82
+ self.assertEqual((200, "mode=7"), (r.status, r.read().decode()))
83
+ self.assertEqual("7", fp.MODE)
84
+
85
+ def test_an_unknown_mode_is_refused_and_changes_nothing(self):
86
+ set_mode_by_request("p")
87
+ status, _ = set_mode_by_request("z")
88
+ self.assertEqual(400, status)
89
+ self.assertEqual("p", fp.MODE)
90
+
91
+ def test_the_control_request_is_answered_not_forwarded(self):
92
+ set_mode_by_request("p")
93
+ c = http.client.HTTPConnection("127.0.0.1", _proxy_port, timeout=3)
94
+ c.request("GET", f"http://127.0.0.1:{_origin_port}/__fault/mode") # absolute form, as a proxy client sends
95
+ r = c.getresponse()
96
+ self.assertEqual("mode=p", r.read().decode()) # the origin would have said origin-ok
97
+
98
+ def test_it_still_works_while_the_proxy_is_hanging_or_dropping(self):
99
+ for stuck in ("h", "d"):
100
+ fp.set_mode(stuck)
101
+ self.assertEqual((200, "mode=p"), set_mode_by_request("p"))
102
+
103
+
104
+ class Modes(unittest.TestCase):
105
+ def setUp(self):
106
+ set_mode_by_request("p")
107
+
108
+ def test_pass_forwards_a_get(self):
109
+ r, body = via_proxy()
110
+ self.assertEqual((200, b"origin-ok"), (r.status, body))
111
+
112
+ def test_pass_forwards_a_post_body(self):
113
+ r, body = via_proxy("POST", body=b"hello-body")
114
+ self.assertEqual((200, b"hello-body"), (r.status, body))
115
+
116
+ def test_5_answers_503(self):
117
+ set_mode_by_request("5")
118
+ r, _ = via_proxy()
119
+ self.assertEqual(503, r.status)
120
+
121
+ def test_7_answers_407_with_a_challenge(self):
122
+ set_mode_by_request("7")
123
+ r, _ = via_proxy()
124
+ self.assertEqual(407, r.status)
125
+ self.assertTrue(r.getheader("Proxy-Authenticate"))
126
+
127
+ def test_r_answers_302_with_a_location(self):
128
+ set_mode_by_request("r")
129
+ r, _ = via_proxy()
130
+ self.assertEqual(302, r.status)
131
+ self.assertTrue(r.getheader("Location"))
132
+
133
+ def test_d_cuts_the_connection(self):
134
+ set_mode_by_request("d")
135
+ with self.assertRaises((ConnectionError, http.client.RemoteDisconnected, OSError)):
136
+ via_proxy()
137
+
138
+ def test_h_never_answers(self):
139
+ set_mode_by_request("h")
140
+ started = time.time()
141
+ with self.assertRaises((socket.timeout, TimeoutError)):
142
+ via_proxy(timeout=2)
143
+ self.assertGreaterEqual(time.time() - started, 1.5)
144
+
145
+
146
+ class Connect(unittest.TestCase):
147
+ def connect(self):
148
+ s = socket.create_connection(("127.0.0.1", _proxy_port), timeout=3)
149
+ s.sendall(f"CONNECT 127.0.0.1:{_origin_port} HTTP/1.1\r\nHost: 127.0.0.1:{_origin_port}\r\n\r\n".encode())
150
+ return s, s.recv(4096)
151
+
152
+ def test_pass_tunnels_to_the_origin(self):
153
+ set_mode_by_request("p")
154
+ s, established = self.connect()
155
+ self.assertTrue(established.startswith(b"HTTP/1.1 200"))
156
+ s.sendall(b"GET /t HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
157
+ time.sleep(0.3)
158
+ self.assertIn(b"origin-ok", s.recv(4096))
159
+ s.close()
160
+
161
+ def test_5_answers_503_on_the_connect_itself(self):
162
+ set_mode_by_request("5")
163
+ s, answer = self.connect()
164
+ self.assertTrue(answer.startswith(b"HTTP/1.1 503"))
165
+ s.close()
166
+
167
+
168
+ class StartupFlag(unittest.TestCase):
169
+ def test_mode_flag_starts_the_proxy_in_that_mode(self):
170
+ with socket.socket() as probe:
171
+ probe.bind(("127.0.0.1", 0))
172
+ port = probe.getsockname()[1]
173
+ proc = subprocess.Popen(
174
+ [sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), "fault_proxy.py"),
175
+ "--port", str(port), "--mode", "5"],
176
+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
177
+ try:
178
+ deadline = time.time() + 5
179
+ while True:
180
+ try:
181
+ c = http.client.HTTPConnection("127.0.0.1", port, timeout=2)
182
+ c.request("GET", f"http://127.0.0.1:{_origin_port}/x")
183
+ self.assertEqual(503, c.getresponse().status)
184
+ break
185
+ except ConnectionRefusedError:
186
+ if time.time() > deadline:
187
+ raise
188
+ time.sleep(0.1)
189
+ finally:
190
+ proc.kill()
191
+ proc.wait()
192
+ proc.stdin.close()
193
+
194
+
195
+ class VersionBodyTests(unittest.TestCase):
196
+ """The version check can be answered by the proxy itself (mode p only), set through /__fault/versionbody/<body>."""
197
+
198
+ def setUp(self):
199
+ fp.MODE = "p" # an earlier test may have left the proxy in another mode
200
+
201
+ def tearDown(self):
202
+ fp.VERSION_BODY = None
203
+
204
+ def _post(self, path="/api/user-manager/system-limit-version"):
205
+ conn = http.client.HTTPConnection("127.0.0.1", _proxy_port, timeout=5)
206
+ conn.request("POST", f"http://127.0.0.1:{_origin_port}{path}", body=b'{"data":{"key":"k"}}', headers={"Content-Type": "application/json"})
207
+ r = conn.getresponse()
208
+ return r.status, r.read()
209
+
210
+ def _control(self, tail):
211
+ conn = http.client.HTTPConnection("127.0.0.1", _proxy_port, timeout=5)
212
+ conn.request("GET", f"/__fault/versionbody/{tail}")
213
+ r = conn.getresponse()
214
+ return r.status, r.read()
215
+
216
+ def test_the_version_check_gets_the_body_that_was_set(self):
217
+ self.assertEqual(self._control('{"status":0,"data":{"limit_version":2000000}}')[0], 200)
218
+ status, body = self._post()
219
+ self.assertEqual((status, body), (200, b'{"status":0,"data":{"limit_version":2000000}}'))
220
+
221
+ def test_an_empty_body_can_be_set(self):
222
+ self._control("__empty__")
223
+ self.assertEqual(self._post(), (200, b""))
224
+
225
+ def test_other_requests_are_still_forwarded(self):
226
+ self._control('{"status":0}')
227
+ status, body = self._post("/api/other")
228
+ self.assertEqual(body, b'{"data":{"key":"k"}}')
229
+
230
+ def test_a_dash_puts_the_real_answer_back(self):
231
+ self._control("x")
232
+ self._control("-")
233
+ self.assertEqual(self._post()[1], b'{"data":{"key":"k"}}')
234
+
235
+
236
+ class InFlightTests(unittest.TestCase):
237
+ """Switching to a fault mode also cuts an exchange that is already being relayed (an upload under way)."""
238
+
239
+ def test_a_fault_mode_cuts_an_exchange_in_flight(self):
240
+ fp.MODE = "p"
241
+ a, b = socket.socketpair()
242
+ c, d = socket.socketpair()
243
+ t = threading.Thread(target=fp.relay, args=(a, c), daemon=True)
244
+ t.start()
245
+ time.sleep(0.3)
246
+ self.assertEqual(2, len(fp.ACTIVE))
247
+ fp.set_mode("d")
248
+ t.join(timeout=5)
249
+ self.assertFalse(t.is_alive())
250
+ self.assertEqual(0, len(fp.ACTIVE))
251
+ fp.set_mode("p")
252
+ for sk in (b, d):
253
+ sk.close()
254
+
255
+
256
+ class RuleTests(unittest.TestCase):
257
+ """An API request can be answered by the proxy with a chosen status (mode p), a limited number of times."""
258
+
259
+ def setUp(self):
260
+ fp.MODE = "p"
261
+ fp.RULES.clear()
262
+
263
+ def tearDown(self):
264
+ fp.RULES.clear()
265
+
266
+ def _rule(self, tail):
267
+ import urllib.parse
268
+ conn = http.client.HTTPConnection("127.0.0.1", _proxy_port, timeout=5)
269
+ conn.request("GET", "/__fault/rule/" + urllib.parse.quote(tail, safe=""))
270
+ r = conn.getresponse()
271
+ return r.status, r.read()
272
+
273
+ def _post(self, path):
274
+ conn = http.client.HTTPConnection("127.0.0.1", _proxy_port, timeout=5)
275
+ conn.request("POST", f"http://127.0.0.1:{_origin_port}{path}", body=b"{}")
276
+ r = conn.getresponse()
277
+ return r.status, r.read()
278
+
279
+ def test_a_rule_answers_with_its_status_and_body(self):
280
+ self._rule('{"match": "/items/search", "status": 409, "body": "{}"}')
281
+ self.assertEqual((409, b"{}"), self._post("/api/items/search/x"))
282
+
283
+ def test_other_paths_are_forwarded(self):
284
+ self._rule('{"match": "/items/search", "status": 409}')
285
+ self.assertEqual(200, self._post("/api/other")[0])
286
+
287
+ def test_times_limits_the_rule(self):
288
+ self._rule('{"match": "/api/", "status": 401, "times": 1}')
289
+ self.assertEqual(401, self._post("/api/a")[0])
290
+ self.assertEqual(200, self._post("/api/a")[0])
291
+
292
+ def test_not_match_excludes_a_path(self):
293
+ self._rule('{"match": "/api/", "not_match": "/user-manager/", "status": 401}')
294
+ self.assertEqual(200, self._post("/api/user-manager/login")[0])
295
+ self.assertEqual(401, self._post("/api/files")[0])
296
+
297
+ def test_a_dash_removes_the_rules(self):
298
+ self._rule('{"match": "/api/", "status": 401}')
299
+ self._rule("-")
300
+ self.assertEqual(200, self._post("/api/a")[0])
301
+
302
+
303
+ if __name__ == "__main__":
304
+ unittest.main()
305
+
306
+
307
+ class RuleMatching(unittest.TestCase):
308
+ """rule_matches: which requests a rule answers (path rules, WebSocket-only rules, CONNECT rules)."""
309
+
310
+ WS = ["GET http://h/ws/signal HTTP/1.1", "Host: h", "Upgrade: websocket", "Connection: Upgrade"]
311
+ API = ["GET http://h/api/x HTTP/1.1", "Host: h"]
312
+
313
+ def test_path_rule_matches_ordinary_requests_not_a_connect(self):
314
+ rule = {"match": "/api/", "status": 503}
315
+ self.assertTrue(fp.rule_matches(rule, "GET", "http://h/api/x", self.API))
316
+ self.assertFalse(fp.rule_matches(rule, "CONNECT", "h:443", ["CONNECT h:443 HTTP/1.1"]))
317
+
318
+ def test_websocket_rule_matches_only_the_handshake(self):
319
+ rule = {"match": "", "websocket": True, "status": 503}
320
+ self.assertTrue(fp.rule_matches(rule, "GET", "http://h/ws/signal", self.WS))
321
+ self.assertFalse(fp.rule_matches(rule, "GET", "http://h/api/x", self.API))
322
+
323
+ def test_connect_rule_matches_only_a_connect_to_that_host(self):
324
+ rule = {"connect": "realtime.example:443", "status": 503}
325
+ self.assertTrue(fp.rule_matches(rule, "CONNECT", "realtime.example:443", ["CONNECT x HTTP/1.1"]))
326
+ self.assertFalse(fp.rule_matches(rule, "CONNECT", "s3.example:443", ["CONNECT x HTTP/1.1"]))
327
+ self.assertFalse(fp.rule_matches(rule, "GET", "http://realtime.example:443/x", self.API))