sdtk-code-kit 0.4.4 → 0.6.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 (38) hide show
  1. package/README.md +1 -1
  2. package/assets/manifest/toolkit-bundle.manifest.json +139 -14
  3. package/assets/manifest/toolkit-bundle.sha256.txt +33 -8
  4. package/assets/toolkit/toolkit/AGENTS.md +2 -1
  5. package/assets/toolkit/toolkit/SDTKCODE_TOOLKIT.md +2 -2
  6. package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +4 -4
  7. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +4 -4
  8. package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +2 -2
  9. package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +2 -2
  10. package/assets/toolkit/toolkit/skills/code-discover/SKILL.md +7 -2
  11. package/assets/toolkit/toolkit/skills/code-issue/SKILL.md +75 -0
  12. package/assets/toolkit/toolkit/skills/code-issue/references/MODE_FIX.md +31 -0
  13. package/assets/toolkit/toolkit/skills/code-issue/references/MODE_PICK.md +19 -0
  14. package/assets/toolkit/toolkit/skills/code-issue/references/MODE_PLAN.md +23 -0
  15. package/assets/toolkit/toolkit/skills/code-issue/references/MODE_REVIEW.md +21 -0
  16. package/assets/toolkit/toolkit/skills/code-issue/references/PROFILE_TEMPLATE.md +53 -0
  17. package/assets/toolkit/toolkit/skills/code-issue/references/RECORDS.md +39 -0
  18. package/assets/toolkit/toolkit/skills/code-issue/scripts/test_tracker.py +283 -0
  19. package/assets/toolkit/toolkit/skills/code-issue/scripts/tracker.py +465 -0
  20. package/assets/toolkit/toolkit/skills/code-review/SKILL.md +2 -1
  21. package/assets/toolkit/toolkit/skills/code-review/references/lead-review-lessons.md +30 -0
  22. package/assets/toolkit/toolkit/skills/code-review/references/lead-review.md +120 -0
  23. package/assets/toolkit/toolkit/skills/code-ui-e2e/SKILL.md +97 -0
  24. package/assets/toolkit/toolkit/skills/code-ui-e2e/references/PROFILE_TEMPLATE.md +30 -0
  25. package/assets/toolkit/toolkit/skills/code-ui-e2e/references/SAFETY.md +17 -0
  26. package/assets/toolkit/toolkit/skills/code-ui-e2e/references/TEST_HOOKS.md +32 -0
  27. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/app_profile.py +118 -0
  28. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/build_test_app.py +140 -0
  29. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/cli.py +46 -0
  30. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/fault_proxy.py +381 -0
  31. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/run_smoke.py +242 -0
  32. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_app_profile.py +79 -0
  33. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_fault_proxy.py +327 -0
  34. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_run_smoke.py +79 -0
  35. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/uia_base.py +127 -0
  36. package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/waits.py +40 -0
  37. package/package.json +1 -1
  38. package/src/lib/scope.js +2 -0
@@ -0,0 +1,381 @@
1
+ #!/usr/bin/env python
2
+ """A proxy that can be told to misbehave, so connection-failure handling can be checked on the real app.
3
+
4
+ python fault_proxy.py # listens on 127.0.0.1:8899, mode p
5
+ python fault_proxy.py --port 9000 --mode 5
6
+
7
+ Point the app's proxy setting at 127.0.0.1:8899 (no user / password). The mode changes while it runs, either with one
8
+ key in the console (no Enter) or, for a script, with a request the proxy answers itself and never forwards (only from
9
+ 127.0.0.1):
10
+
11
+ curl http://127.0.0.1:8899/__fault/mode/5 # -> 200 mode=5
12
+ curl http://127.0.0.1:8899/__fault/mode # -> 200 mode=<current>
13
+ curl http://127.0.0.1:8899/__fault/rule/<url-encoded JSON rule> # see RULES below; /__fault/rule/- clears them
14
+
15
+ The keys:
16
+
17
+ p pass forward everything, as a healthy network would
18
+ 5 503 answer every plain-HTTP request with 503 (a server in maintenance)
19
+ h hang accept the connection and never answer (a server that is up but not responding)
20
+ d drop cut the connection at once (the network is gone / the server refuses)
21
+ 7 407 answer with "Proxy Authentication Required"
22
+ r 302 answer with a redirect, as a hotel Wi-Fi login page does
23
+ q quit
24
+
25
+ Write down, per mode, what the app must show (an error state, offline, retry) in the project's e2e profile: the proxy
26
+ only produces the fault, the test case states the expected reaction.
27
+
28
+ HTTPS goes through CONNECT (e.g. pre-signed storage URLs). The proxy cannot see inside a tunnel, so in modes 5/7/r a
29
+ CONNECT is answered with that status on the CONNECT itself - the client reports a failed connection. The API address
30
+ must be plain http for 5/7/r to be seen as HTTP answers.
31
+
32
+ If the API address is a loopback address, .NET may skip the proxy for it entirely and this window will show nothing.
33
+ Use the machine's LAN address in the app's settings for the check, and look for the request lines below.
34
+
35
+ Stdlib only - no install. Windows console (single-key input); elsewhere type the letter and press Enter.
36
+ Its own tests: python -m unittest test_fault_proxy (from this folder)
37
+ """
38
+ import argparse, json, socket, struct, sys, threading, time
39
+ from urllib.parse import unquote, urlsplit
40
+
41
+ LOCK = threading.Lock()
42
+ MODE = "p"
43
+ # What the app's version check (POST .../system-limit-version) is answered with while the mode is p; None = ask the real server.
44
+ VERSION_BODY = None
45
+ VERSION_PATH = "/system-limit-version"
46
+ # Answer rules for ordinary API requests while the mode is p: {"match": substring of the URL path, "not_match": substring it must NOT
47
+ # contain, "status": int, "body": str, "times": how many requests it answers (omitted = every one)}. First matching rule wins.
48
+ # "websocket": true limits a rule to WebSocket handshakes (Upgrade: websocket) - the app's realtime channel, plain ws:// through
49
+ # the proxy. {"connect": substring of host:port} makes a rule answer a CONNECT instead (a wss:// or https:// tunnel): the
50
+ # tunnel is refused with that status, ordinary requests are never matched by it.
51
+ RULES = []
52
+ MODES = {
53
+ "p": "pass",
54
+ "5": "503 Service Unavailable",
55
+ "h": "hang (no answer)",
56
+ "d": "drop (cut connection)",
57
+ "7": "407 Proxy Authentication Required",
58
+ "r": "302 redirect",
59
+ }
60
+ CANNED = {
61
+ "5": (503, "Service Unavailable", ""),
62
+ "7": (407, "Proxy Authentication Required", 'Proxy-Authenticate: Basic realm="fault_proxy"\r\n'),
63
+ "r": (302, "Found", "Location: http://captive.example.invalid/login\r\n"),
64
+ }
65
+ CONNECT_TIMEOUT = 10
66
+
67
+
68
+ def log(*a):
69
+ with LOCK:
70
+ print(time.strftime("%H:%M:%S"), *a, flush=True)
71
+
72
+
73
+ def read_head(sock):
74
+ """Reads up to the blank line. Returns (header lines, bytes already read past it), or (None, b"")."""
75
+ buf = b""
76
+ while b"\r\n\r\n" not in buf:
77
+ chunk = sock.recv(65536)
78
+ if not chunk:
79
+ return None, b""
80
+ buf += chunk
81
+ if len(buf) > 1 << 20:
82
+ return None, b""
83
+ head, _, rest = buf.partition(b"\r\n\r\n")
84
+ return head.decode("latin-1").split("\r\n"), rest
85
+
86
+
87
+ def answer(sock, code, reason, extra="", body=""):
88
+ data = body.encode("utf-8")
89
+ sock.sendall((f"HTTP/1.1 {code} {reason}\r\n{extra}Content-Length: {len(data)}\r\nConnection: close\r\n\r\n"
90
+ ).encode("latin-1") + data)
91
+
92
+
93
+ def reset(sock):
94
+ """Closes with RST rather than FIN, which is what a connection killed by the network looks like."""
95
+ try:
96
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
97
+ except OSError:
98
+ pass
99
+ try:
100
+ # Wakes a thread blocked in recv() on this socket (close() alone does not on Linux); sends nothing.
101
+ sock.shutdown(socket.SHUT_RD)
102
+ except OSError:
103
+ pass
104
+ sock.close()
105
+
106
+
107
+ def hang(sock):
108
+ """Holds the connection open, saying nothing, until the client gives up on its own."""
109
+ sock.settimeout(None)
110
+ try:
111
+ while sock.recv(4096):
112
+ pass
113
+ except OSError:
114
+ pass
115
+
116
+
117
+ def pipe(src, dst):
118
+ try:
119
+ while True:
120
+ data = src.recv(65536)
121
+ if not data:
122
+ break
123
+ dst.sendall(data)
124
+ except OSError:
125
+ pass
126
+ finally:
127
+ try:
128
+ dst.shutdown(socket.SHUT_WR)
129
+ except OSError:
130
+ pass
131
+
132
+
133
+ ACTIVE = set() # sockets of the exchanges being relayed right now: a fault mode cuts them too
134
+
135
+
136
+ def cut_active():
137
+ """Resets every exchange in flight (an upload already under way), as a dropped network would."""
138
+ with LOCK:
139
+ socks = list(ACTIVE)
140
+ ACTIVE.clear()
141
+ for sk in socks:
142
+ reset(sk)
143
+ if socks:
144
+ log(f"cut {len(socks)} exchange(s) in flight")
145
+
146
+
147
+ def relay(a, b):
148
+ with LOCK:
149
+ ACTIVE.update((a, b))
150
+ t = threading.Thread(target=pipe, args=(b, a), daemon=True)
151
+ t.start()
152
+ pipe(a, b)
153
+ t.join(timeout=5)
154
+ with LOCK:
155
+ ACTIVE.discard(a)
156
+ ACTIVE.discard(b)
157
+
158
+
159
+ CONTROL_PREFIX = "/__fault/mode"
160
+ VERSION_CONTROL = "/__fault/versionbody"
161
+ RULE_CONTROL = "/__fault/rule"
162
+
163
+
164
+ def control(client, addr, target):
165
+ """Answers a /__fault/mode request itself. True when the request was one (whatever the answer)."""
166
+ global VERSION_BODY
167
+ path = urlsplit(target).path
168
+ if path.startswith(RULE_CONTROL):
169
+ # GET /__fault/rule/<url-encoded JSON rule> adds a rule; /__fault/rule/- removes them all; no argument lists them.
170
+ if addr[0] != "127.0.0.1":
171
+ answer(client, 403, "Forbidden")
172
+ return True
173
+ wanted = unquote(path[len(RULE_CONTROL):].lstrip("/"))
174
+ with LOCK:
175
+ if wanted == "-":
176
+ RULES.clear()
177
+ elif wanted:
178
+ RULES.append(json.loads(wanted))
179
+ shown = json.dumps(RULES, ensure_ascii=False)
180
+ log(f"RULES -> {shown}")
181
+ answer(client, 200, "OK", "", shown)
182
+ return True
183
+ if path.startswith(VERSION_CONTROL):
184
+ # GET /__fault/versionbody/<body>: the version check is answered with that body (200, JSON) instead of the server's.
185
+ # "-" puts the real answer back, "__empty__" is an empty body, no argument reports what is set.
186
+ if addr[0] != "127.0.0.1":
187
+ answer(client, 403, "Forbidden")
188
+ return True
189
+ wanted = unquote(path[len(VERSION_CONTROL):].lstrip("/"))
190
+ if wanted == "-":
191
+ VERSION_BODY = None
192
+ elif wanted == "__empty__":
193
+ VERSION_BODY = ""
194
+ elif wanted:
195
+ VERSION_BODY = wanted
196
+ log(f"VERSION BODY -> {VERSION_BODY!r}")
197
+ answer(client, 200, "OK", "", f"versionbody={VERSION_BODY!r}")
198
+ return True
199
+ if not path.startswith(CONTROL_PREFIX):
200
+ return False
201
+ if addr[0] != "127.0.0.1":
202
+ answer(client, 403, "Forbidden")
203
+ return True
204
+ wanted = path[len(CONTROL_PREFIX):].strip("/")
205
+ if wanted and wanted not in MODES:
206
+ answer(client, 400, "Bad Request", "", f"unknown mode {wanted!r}; use one of {''.join(MODES)}")
207
+ return True
208
+ if wanted:
209
+ set_mode(wanted)
210
+ answer(client, 200, "OK", "", f"mode={MODE}")
211
+ return True
212
+
213
+
214
+ def rule_matches(rule, method, target, lines):
215
+ """Whether `rule` answers this request (see RULES)."""
216
+ if method.upper() == "CONNECT":
217
+ return "connect" in rule and rule["connect"] in target
218
+ if "connect" in rule:
219
+ return False
220
+ if rule.get("websocket") and not any(l.split(":", 1)[0].strip().lower() == "upgrade"
221
+ and l.split(":", 1)[1].strip().lower() == "websocket" for l in lines[1:] if ":" in l):
222
+ return False
223
+ path = urlsplit(target).path
224
+ return rule.get("match", "") in path and (not rule.get("not_match") or rule["not_match"] not in path)
225
+
226
+
227
+ def drain_body(client, lines, rest):
228
+ """Reads (and drops) the request body, so the answer is not sent into a half-read request."""
229
+ length = 0
230
+ for l in lines[1:]:
231
+ if l.lower().startswith("content-length:"):
232
+ length = int(l.split(":", 1)[1])
233
+ need = length - len(rest)
234
+ while need > 0:
235
+ chunk = client.recv(min(need, 4096))
236
+ if not chunk:
237
+ break
238
+ need -= len(chunk)
239
+
240
+
241
+ def handle(client, addr):
242
+ try:
243
+ client.settimeout(30)
244
+ lines, rest = read_head(client)
245
+ if not lines:
246
+ return
247
+ method, target, version = (lines[0].split(" ", 2) + ["", ""])[:3]
248
+ # Before the mode is looked at: the way out of `h` or `d` has to work while they are on.
249
+ if method.upper() == "GET" and control(client, addr, target):
250
+ return
251
+ mode = MODE
252
+ label = MODES[mode]
253
+
254
+ if mode == "p" and RULES:
255
+ hit = None
256
+ with LOCK:
257
+ for r in RULES:
258
+ if rule_matches(r, method, target, lines):
259
+ hit = r
260
+ if "times" in r:
261
+ r["times"] -= 1
262
+ if r["times"] <= 0:
263
+ RULES.remove(r)
264
+ break
265
+ if hit:
266
+ drain_body(client, lines, rest)
267
+ log(f"[rule] {method} {target} -> {hit['status']}")
268
+ answer(client, hit["status"], "Rule", "Content-Type: application/json" + chr(13) + chr(10), hit.get("body", ""))
269
+ return
270
+
271
+ if mode == "p" and VERSION_BODY is not None and method.upper() == "POST" and urlsplit(target).path.endswith(VERSION_PATH):
272
+ drain_body(client, lines, rest)
273
+ log(f"[version] {method} {target} -> 200 {VERSION_BODY!r}")
274
+ answer(client, 200, "OK", "Content-Type: application/json" + chr(13) + chr(10), VERSION_BODY)
275
+ return
276
+
277
+ if mode == "d":
278
+ log(f"[{label}] {method} {target}")
279
+ reset(client)
280
+ client = None
281
+ return
282
+ if mode == "h":
283
+ log(f"[{label}] {method} {target}")
284
+ hang(client)
285
+ return
286
+ if mode in CANNED:
287
+ code, reason, extra = CANNED[mode]
288
+ log(f"[{label}] {method} {target} -> {code}")
289
+ answer(client, code, reason, extra)
290
+ return
291
+
292
+ if method.upper() == "CONNECT":
293
+ host, _, port = target.rpartition(":")
294
+ upstream = socket.create_connection((host, int(port or 443)), timeout=CONNECT_TIMEOUT)
295
+ client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
296
+ log(f"[pass] CONNECT {target}")
297
+ upstream.settimeout(None)
298
+ client.settimeout(None)
299
+ relay(client, upstream)
300
+ upstream.close()
301
+ return
302
+
303
+ url = urlsplit(target)
304
+ host, port = url.hostname, url.port or 80
305
+ path = (url.path or "/") + (f"?{url.query}" if url.query else "")
306
+ upstream = socket.create_connection((host, port), timeout=CONNECT_TIMEOUT)
307
+ # Origin-form request, one exchange per connection: asking upstream to close lets the relay end on its own.
308
+ kept = [l for l in lines[1:] if l.split(":", 1)[0].lower() not in ("proxy-connection", "connection", "proxy-authorization")]
309
+ head = f"{method} {path} {version}\r\n" + "\r\n".join(kept) + "\r\nConnection: close\r\n\r\n"
310
+ upstream.sendall(head.encode("latin-1") + rest)
311
+ log(f"[pass] {method} {target}")
312
+ upstream.settimeout(None)
313
+ client.settimeout(None)
314
+ relay(client, upstream)
315
+ upstream.close()
316
+ except OSError as e:
317
+ log(f"[error] {addr}: {e}")
318
+ finally:
319
+ if client is not None:
320
+ try:
321
+ client.close()
322
+ except OSError:
323
+ pass
324
+
325
+
326
+ def listen(port):
327
+ """Binds 127.0.0.1:<port> (0 = any free port) and returns the listening socket."""
328
+ server = socket.socket()
329
+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
330
+ server.bind(("127.0.0.1", port))
331
+ server.listen(64)
332
+ return server
333
+
334
+
335
+ def serve(server):
336
+ while True:
337
+ client, addr = server.accept()
338
+ threading.Thread(target=handle, args=(client, addr), daemon=True).start()
339
+
340
+
341
+ def set_mode(key):
342
+ global MODE
343
+ if key == "q":
344
+ raise SystemExit(0)
345
+ if key in MODES:
346
+ MODE = key
347
+ log(f"MODE -> {key}: {MODES[key]}")
348
+ if key != "p":
349
+ cut_active()
350
+
351
+
352
+ def keys():
353
+ try:
354
+ import msvcrt
355
+ while True:
356
+ yield msvcrt.getwch()
357
+ except ImportError:
358
+ for line in sys.stdin:
359
+ if line.strip():
360
+ yield line.strip()[0]
361
+
362
+
363
+ def main():
364
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
365
+ ap.add_argument("--port", type=int, default=8899)
366
+ ap.add_argument("--mode", choices=list(MODES), default="p", help="the mode to start in (default p)")
367
+ args = ap.parse_args()
368
+ server = listen(args.port)
369
+ threading.Thread(target=serve, args=(server,), daemon=True).start()
370
+ log(f"fault_proxy on 127.0.0.1:{args.port} - keys: p pass, 5 503, h hang, d drop, 7 407, r 302, q quit; "
371
+ f"or GET /__fault/mode/<key>")
372
+ set_mode(args.mode)
373
+ try:
374
+ for key in keys():
375
+ set_mode(key)
376
+ except (KeyboardInterrupt, SystemExit):
377
+ pass
378
+
379
+
380
+ if __name__ == "__main__":
381
+ main()
@@ -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()