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.
- package/README.md +1 -1
- package/assets/manifest/toolkit-bundle.manifest.json +139 -14
- package/assets/manifest/toolkit-bundle.sha256.txt +33 -8
- package/assets/toolkit/toolkit/AGENTS.md +2 -1
- package/assets/toolkit/toolkit/SDTKCODE_TOOLKIT.md +2 -2
- package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +4 -4
- package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +4 -4
- package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +2 -2
- package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +2 -2
- package/assets/toolkit/toolkit/skills/code-discover/SKILL.md +7 -2
- package/assets/toolkit/toolkit/skills/code-issue/SKILL.md +75 -0
- package/assets/toolkit/toolkit/skills/code-issue/references/MODE_FIX.md +31 -0
- package/assets/toolkit/toolkit/skills/code-issue/references/MODE_PICK.md +19 -0
- package/assets/toolkit/toolkit/skills/code-issue/references/MODE_PLAN.md +23 -0
- package/assets/toolkit/toolkit/skills/code-issue/references/MODE_REVIEW.md +21 -0
- package/assets/toolkit/toolkit/skills/code-issue/references/PROFILE_TEMPLATE.md +53 -0
- package/assets/toolkit/toolkit/skills/code-issue/references/RECORDS.md +39 -0
- package/assets/toolkit/toolkit/skills/code-issue/scripts/test_tracker.py +283 -0
- package/assets/toolkit/toolkit/skills/code-issue/scripts/tracker.py +465 -0
- package/assets/toolkit/toolkit/skills/code-review/SKILL.md +2 -1
- package/assets/toolkit/toolkit/skills/code-review/references/lead-review-lessons.md +30 -0
- package/assets/toolkit/toolkit/skills/code-review/references/lead-review.md +120 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/SKILL.md +97 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/references/PROFILE_TEMPLATE.md +30 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/references/SAFETY.md +17 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/references/TEST_HOOKS.md +32 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/app_profile.py +118 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/build_test_app.py +140 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/cli.py +46 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/fault_proxy.py +381 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/run_smoke.py +242 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_app_profile.py +79 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_fault_proxy.py +327 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/test_run_smoke.py +79 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/uia_base.py +127 -0
- package/assets/toolkit/toolkit/skills/code-ui-e2e/scripts/waits.py +40 -0
- package/package.json +1 -1
- package/src/lib/scope.js +2 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: code-ui-e2e
|
|
3
|
+
description: Use when automating end-to-end or smoke tests of a Windows desktop application through its real UI (UI Automation / pywinauto); when asked to push, share or get CI to build a branch with test hooks (UI Automation names) in a product repository that belongs to a customer or another team; when tests run on a machine where the same app holds someone's real data; or when cleaning up test folders, network faults, command-line integrations or long background cycles are involved.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Desktop UI end-to-end tests
|
|
7
|
+
|
|
8
|
+
Drive the real app, read the screen as text through UI Automation, check what a tester would see, and never damage
|
|
9
|
+
the machine it runs on. The test cases come from a smoke-test markdown (`sdtk-smoke-test-spec`); the runner keys every
|
|
10
|
+
result by that file's case ids.
|
|
11
|
+
|
|
12
|
+
**REQUIRED BACKGROUND:** read `references/SAFETY.md` before the first run on any machine. Every rule there comes from
|
|
13
|
+
an incident (lost server data, a hidden user window, a password typed into a browser). Paths below (`scripts/`,
|
|
14
|
+
`references/`) are relative to this skill's folder.
|
|
15
|
+
|
|
16
|
+
## Critical Constraints
|
|
17
|
+
|
|
18
|
+
1. **Never start any build of the app on a machine where the owner's copy holds data** (saved session, database,
|
|
19
|
+
settings) before it is parked. Check first; if there is owner data, say what you found and **ask the owner before
|
|
20
|
+
parking**, then `app_profile.OwnerState.park()` before the first case and `restore()` after the last — also after a
|
|
21
|
+
crash. A test build with the same identity signs in with the owner's session and writes their database.
|
|
22
|
+
2. **Never kill the owner's app or close their windows.** If the app is running, stop and ask them to exit it. Never
|
|
23
|
+
attach to their Office / tools (`Dispatch`); private instances only (`DispatchEx`).
|
|
24
|
+
3. **Never delete a folder that is, or is under, a sync root / watched folder of the app** — not in cleanup, not
|
|
25
|
+
"just the test folder". Compare with the app's registered roots first; clean test data up through the server API.
|
|
26
|
+
If you cannot prove a folder is outside every root, leave it and report it.
|
|
27
|
+
4. **Test-only code never reaches a repository that is not the team's own — not even as a branch pushed "only to
|
|
28
|
+
build" or "only for CI".** Keep the hooks as a patch in the team's tool repository and build from `git archive`
|
|
29
|
+
with `scripts/build_test_app.py`. If CI must build it, it builds from the team's repository, not the product's.
|
|
30
|
+
5. **Cases are identified by the ids in section 4 of the smoke markdown**, never by position or by counting rows.
|
|
31
|
+
6. **Check the foreground window before every keystroke or coordinate click** (`uia_base.ensure_foreground`); match
|
|
32
|
+
controls by exact name, never by prefix or position alone.
|
|
33
|
+
7. **A script with side effects is never "tried" on the owner's machine**; run it on a copy or in a sandbox first.
|
|
34
|
+
|
|
35
|
+
## Process
|
|
36
|
+
|
|
37
|
+
1. **Read** `references/SAFETY.md` and the project profile (`docs/qa/e2e_profile.json` + `.md`). No profile → set
|
|
38
|
+
one up first (below).
|
|
39
|
+
2. **Check the machine** (read-only): is the app running, does the owner's copy hold data, which folders are sync
|
|
40
|
+
roots. Report what you found and ask before parking anything (constraint 1).
|
|
41
|
+
3. **Build** the test app from a ref with `scripts/build_test_app.py` (patch applied outside every repository).
|
|
42
|
+
4. **Run** the suite with `scripts/run_smoke.py` — owner state parked before, restored after.
|
|
43
|
+
5. **Clean up** through the server API only (constraint 3); restore the owner's state; confirm the app's data folder
|
|
44
|
+
and registry values are back.
|
|
45
|
+
6. **Report** `results/<time>_<suite>/report.md`. A tester confirms before anything is written back into the test
|
|
46
|
+
document.
|
|
47
|
+
|
|
48
|
+
## Set up (once per project)
|
|
49
|
+
|
|
50
|
+
1. **Profile** — `docs/qa/e2e_profile.json` + `.md` from `references/PROFILE_TEMPLATE.md`: app generations (exe, data
|
|
51
|
+
folder, registry key, data files), per-account values, the app's background cycle, smoke suites to automate.
|
|
52
|
+
2. **Test hooks** — owner-drawn controls need UI Automation names. When the product repository belongs to a customer
|
|
53
|
+
or another team, keep the hooks as a patch in the team's own tool repository (`references/TEST_HOOKS.md`).
|
|
54
|
+
3. **Build** — `scripts/build_test_app.py --repo … --project … --ref … --patch …` exports the ref with `git archive`,
|
|
55
|
+
applies the patch outside every repository and builds into `<out-root>/<ref>-<sha7>/out` with `build_info.json`.
|
|
56
|
+
A patch that no longer applies reports the files to refresh. Test on the latest commit of the target branch. The
|
|
57
|
+
build step is `dotnet build`; for another stack replace `build()` (one function).
|
|
58
|
+
|
|
59
|
+
## Write a suite
|
|
60
|
+
|
|
61
|
+
`smoke/<suite>.py`: `SOURCE` (the smoke markdown), `CASES = {"ABC-FN-01": fn}`, `MANUAL = {"ABC-ER-06": reason}`,
|
|
62
|
+
optional `setup` / `teardown` / `make_driver(env)` / `make_api(env)`. A case function gets `ctx`:
|
|
63
|
+
`ctx.check(ok, what)`, `ctx.shot()`, `ctx.visual(what to look at)`, `ctx.hold(reason)`, `ctx.note(text)`, `ctx.d`
|
|
64
|
+
(the project's driver), `ctx.api` (its web API client), `ctx.state` (shared by the run).
|
|
65
|
+
|
|
66
|
+
Build the project driver on `scripts/uia_base.py` (wait_until, exact-name find_control, invoke-then-click, foreground
|
|
67
|
+
check, folder dialog, screenshots). Prepare server data through the web API, not through the web UI. Other helpers:
|
|
68
|
+
`scripts/cli.py` (command-line entry points, exit codes), `scripts/waits.py` (cycles, files appearing),
|
|
69
|
+
`scripts/fault_proxy.py` (503 / hang / drop / 407 / redirect, per-path rules, WebSocket-only and CONNECT rules).
|
|
70
|
+
|
|
71
|
+
## Run
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
python scripts/run_smoke.py smoke/<suite>.py --list # coverage of the markdown: auto / 手動 / 未実装
|
|
75
|
+
python scripts/run_smoke.py smoke/<suite>.py [--only ABC-FN-01]
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Before the first case: owner's state parked (`app_profile.OwnerState.park`), app not running. After the last:
|
|
79
|
+
`restore()` — also after a crash (`--restore` in the project's wrapper). Results: `results/<time>_<suite>/report.md`,
|
|
80
|
+
`results.json`, `<id>.png`.
|
|
81
|
+
|
|
82
|
+
## Common mistakes
|
|
83
|
+
|
|
84
|
+
| Mistake | Effect | Instead |
|
|
85
|
+
|---|---|---|
|
|
86
|
+
| Starting the test build directly on a machine where the app is used | It signs in with the owner's session and runs on the owner's database | Check, ask, park / restore with `app_profile` |
|
|
87
|
+
| Deleting a test folder in cleanup | It had become a sync folder: the app deleted the items on the server | Never delete under a sync root; clean up through the API |
|
|
88
|
+
| Hard-coding the exe / data folder / registry key | Every test breaks at a product rename | Generations in the profile |
|
|
89
|
+
| Pushing the hook branch "only to build" | The customer sees test code in their repository | Patch in the team's repository, `git archive` build |
|
|
90
|
+
| Counting or matching cases by position | Renumbered documents pair the wrong cases | Case ids from section 4 of the markdown |
|
|
91
|
+
| Sleeping instead of waiting for a condition | Flaky or slow runs | `wait_until` / `waits.until` with a timeout |
|
|
92
|
+
| `fetch` / `push` / API calls that hang | Run stalls waiting for a credential prompt | `GIT_TERMINAL_PROMPT=0`, timeouts everywhere |
|
|
93
|
+
|
|
94
|
+
## Tests of the scripts
|
|
95
|
+
|
|
96
|
+
`python -m unittest discover -s scripts -p "test_*.py"` — uses temp folders and its own registry key only; the
|
|
97
|
+
registry tests skip outside Windows.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# E2E profile — <project>
|
|
2
|
+
|
|
3
|
+
Two files in the project repository (or in the team's tool repository when the product repository is a customer's):
|
|
4
|
+
`docs/qa/e2e_profile.json` (read by the scripts) and this markdown (read by people and agents).
|
|
5
|
+
|
|
6
|
+
## e2e_profile.json
|
|
7
|
+
|
|
8
|
+
```json
|
|
9
|
+
{
|
|
10
|
+
"generations": [
|
|
11
|
+
{"exe_name": "OldName.exe", "data_dir": "%LOCALAPPDATA%\\OldName", "registry_key": "Software\\OldName",
|
|
12
|
+
"data_files": ["app.db", "app.db-wal", "app.db-shm"]},
|
|
13
|
+
{"exe_name": "NewName.exe", "data_dir": "%LOCALAPPDATA%\\NewName", "registry_key": "Software\\NewName",
|
|
14
|
+
"data_files": ["app.db", "app.db-wal", "app.db-shm"]}
|
|
15
|
+
],
|
|
16
|
+
"profile_values": {"BaseFolderPath": "{work}\\{label}"},
|
|
17
|
+
"clear_values": ["Session"],
|
|
18
|
+
"cycle_seconds": 300
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Markdown part
|
|
23
|
+
|
|
24
|
+
- **Product repository / build:** repository, project file, branches under test, patch location.
|
|
25
|
+
- **Accounts:** labels (TK-1 …) → role; credentials only in `.env` (never committed).
|
|
26
|
+
- **Pages and controls:** navigation names, dialog titles, buttons per product version (old / new names).
|
|
27
|
+
- **Sync roots / watched folders:** where the app keeps them (registry values, database table) — the cleanup guard.
|
|
28
|
+
- **Shared files:** files the app shares with other programs (and who owns them).
|
|
29
|
+
- **Fault expectations:** per `fault_proxy` mode, what the app must show.
|
|
30
|
+
- **Suites:** smoke markdown → `smoke/<suite>.py`, cases left manual and why.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Safety rules for UI tests on a real machine
|
|
2
|
+
|
|
3
|
+
Each rule exists because breaking it caused damage once.
|
|
4
|
+
|
|
5
|
+
| Rule | Why |
|
|
6
|
+
|---|---|
|
|
7
|
+
| Before starting any build of the app, check whether the machine owner's copy has data (saved session, database). If so, park it (`app_profile.OwnerState`) and get the owner's agreement. | A test build with the same identity signs in with the owner's session and writes their database. |
|
|
8
|
+
| Never kill the owner's app or close their windows; refuse to start while it runs. | Their unsaved work and their uploads in progress. |
|
|
9
|
+
| Never delete a folder that is, or is under, a sync root / watched folder of the app — compare with the app's registered roots and settings first. Clean up test data through the server API. | A cleanup that removed a folder the app had adopted made the app delete the items on the server. |
|
|
10
|
+
| Files shared with another program (another app's database, a config both read): touch only your own rows / keys, snapshot them before, put them back after, keep a copy of the whole file, refuse while that program runs. | The file also holds the other program's queue and history. |
|
|
11
|
+
| Check the foreground window before every keystroke and coordinate click (`uia_base.ensure_foreground`). | Keys typed into a browser or editor that came to the front — a password included. |
|
|
12
|
+
| Match controls by exact name, never by prefix or position alone. | A prefix match ticked the wrong checkbox. |
|
|
13
|
+
| A script with side effects is never "tried" on the owner's machine; test it on a copy or in a sandbox first. | A cancel branch that did not work ran the real reset. |
|
|
14
|
+
| Never attach to the owner's running Office / tools (`Dispatch`); use private instances (`DispatchEx`). | Their window was hidden by the test. |
|
|
15
|
+
| Test-only code never reaches a repository that is not the team's own — not even as a pushed branch. | The repository owner sees every branch. |
|
|
16
|
+
| Commands given to a person: short, one per line, read-only parts run once before handing them over. | Long pasted lines wrapped and broke in the console. |
|
|
17
|
+
| Personal data in evidence screenshots (e-mail, tokens, user names) is pointed out before the evidence is shared. | Evidence travels to customers. |
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Test hooks kept out of the product repository
|
|
2
|
+
|
|
3
|
+
Owner-drawn controls (custom-painted lists, cards, chips, links) expose nothing to UI Automation unless the app gives
|
|
4
|
+
them a name. Adding those names is a small code change in the product — but when the product repository belongs to a
|
|
5
|
+
customer or another team, test-only code must not go there (every pushed branch is visible to its owner).
|
|
6
|
+
|
|
7
|
+
## Layout
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
<team tool repo>/
|
|
11
|
+
app_patch/uia-hooks.patch <- git format-patch of the hook commit, made on a local branch never pushed
|
|
12
|
+
.gitattributes <- "*.patch -text" (autocrlf would rewrite the patch and break it on another machine)
|
|
13
|
+
build_test_app.py <- or call the skill's scripts/build_test_app.py
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Making and refreshing the patch
|
|
17
|
+
|
|
18
|
+
1. In a local worktree of the product repository: branch from the target ref, add the names, commit, never push.
|
|
19
|
+
2. `git format-patch -1 <commit> --stdout > <tool repo>/app_patch/uia-hooks.patch`.
|
|
20
|
+
3. `build_test_app.py` reports "refresh it for: <files>" when a later ref changed those files: rebase the local hook
|
|
21
|
+
branch onto the new ref, resolve, export the patch again. A feature branch that redesigns a control needs new names
|
|
22
|
+
for its new controls — refresh the patch when that branch merges, not before.
|
|
23
|
+
|
|
24
|
+
## Naming convention for list rows (example)
|
|
25
|
+
|
|
26
|
+
One line per item: `title<TAB>subtitle<TAB>right text[<TAB>[x]|[ ]]` (the checkbox state when there is one). A
|
|
27
|
+
driver parses it into fields; keep the convention documented in the project profile.
|
|
28
|
+
|
|
29
|
+
## Moving the hooks into the product
|
|
30
|
+
|
|
31
|
+
If the repository owner agrees, accessibility names are a real feature (screen readers): then write them as readable
|
|
32
|
+
text ("title, subtitle") rather than a test format, and adapt the driver's parser.
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""What the app under test leaves on the machine, and keeping the machine owner's copy of it safe while tests run.
|
|
3
|
+
|
|
4
|
+
The project's e2e profile (`docs/qa/e2e_profile.json`, see references/PROFILE_TEMPLATE.md) declares one entry per
|
|
5
|
+
generation of the app (a product rename changes the exe, data folder and registry key):
|
|
6
|
+
|
|
7
|
+
{"generations": [{"exe_name": "App.exe", "data_dir": "%LOCALAPPDATA%\\\\App", "registry_key": "Software\\\\App",
|
|
8
|
+
"data_files": ["app.db", "app.db-wal", "app.db-shm"]}],
|
|
9
|
+
"profile_values": {"BaseFolderPath": "{work}\\\\{label}"}, # registry values set per test account
|
|
10
|
+
"clear_values": ["Session"]} # never resume another account's sign-in
|
|
11
|
+
|
|
12
|
+
A test build of the product usually has the SAME identity as the copy the machine owner uses every day: started as is,
|
|
13
|
+
it signs in with the owner's saved session and runs on the owner's database. OwnerState parks the owner's data files
|
|
14
|
+
and registry key before the run and puts them back after; it refuses while that exe is running, and keeps a copy of
|
|
15
|
+
the data files that nothing here ever deletes.
|
|
16
|
+
"""
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
import time
|
|
22
|
+
import winreg
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Identity:
|
|
28
|
+
exe_name: str
|
|
29
|
+
data_dir: str
|
|
30
|
+
registry_key: str
|
|
31
|
+
data_files: tuple = ()
|
|
32
|
+
extra: dict = field(default_factory=dict, hash=False, compare=False)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load(path) -> dict:
|
|
36
|
+
with open(path, encoding="utf-8") as f:
|
|
37
|
+
return json.load(f)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def identity(cfg: dict, exe_path: str | None = None) -> Identity:
|
|
41
|
+
"""The generation whose exe_name is the file name of `exe_path` (else the first one)."""
|
|
42
|
+
gens = cfg["generations"]
|
|
43
|
+
name = os.path.basename(exe_path or "").lower()
|
|
44
|
+
g = next((g for g in gens if g["exe_name"].lower() == name), gens[0])
|
|
45
|
+
return Identity(g["exe_name"], os.path.expandvars(g["data_dir"]), g["registry_key"], tuple(g.get("data_files", ())),
|
|
46
|
+
{k: v for k, v in g.items() if k not in ("exe_name", "data_dir", "registry_key", "data_files")})
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def process_running(exe_name: str) -> bool:
|
|
50
|
+
out = subprocess.run(["tasklist", "/FI", f"IMAGENAME eq {exe_name}", "/NH"], capture_output=True, text=True).stdout
|
|
51
|
+
return exe_name.lower() in out.lower()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class OwnerState:
|
|
55
|
+
def __init__(self, ident: Identity, cfg: dict, state_dir: str, work_root: str, running=process_running):
|
|
56
|
+
self.ident, self.cfg, self.state_dir, self.work_root, self.running = ident, cfg, state_dir, work_root, running
|
|
57
|
+
self.original_dir = os.path.join(state_dir, "_original")
|
|
58
|
+
self.backup_reg = os.path.join(state_dir, "_original.reg")
|
|
59
|
+
self.current = None
|
|
60
|
+
|
|
61
|
+
def _move(self, src_dir, dst_dir):
|
|
62
|
+
os.makedirs(dst_dir, exist_ok=True)
|
|
63
|
+
for name in self.ident.data_files:
|
|
64
|
+
src = os.path.join(src_dir, name)
|
|
65
|
+
if os.path.exists(src):
|
|
66
|
+
dst = os.path.join(dst_dir, name)
|
|
67
|
+
if os.path.exists(dst):
|
|
68
|
+
os.remove(dst)
|
|
69
|
+
shutil.move(src, dst)
|
|
70
|
+
|
|
71
|
+
def park(self):
|
|
72
|
+
"""Parks the owner's data files and exports their registry key. Call once, with the app stopped."""
|
|
73
|
+
if self.running(self.ident.exe_name):
|
|
74
|
+
raise RuntimeError(f"{self.ident.exe_name} is running (the owner's app?): close it first; nothing changed")
|
|
75
|
+
if os.path.exists(self.backup_reg):
|
|
76
|
+
raise RuntimeError(f"{self.backup_reg} exists: a previous run did not restore; restore first")
|
|
77
|
+
os.makedirs(self.state_dir, exist_ok=True)
|
|
78
|
+
subprocess.run(["reg", "export", "HKCU\\" + self.ident.registry_key, self.backup_reg, "/y"], capture_output=True)
|
|
79
|
+
if not os.path.exists(self.backup_reg):
|
|
80
|
+
open(self.backup_reg, "w").close() # no key yet: restoring means deleting it
|
|
81
|
+
keep = os.path.join(self.state_dir, "_owner_backup_" + time.strftime("%Y%m%d-%H%M%S"))
|
|
82
|
+
os.makedirs(keep, exist_ok=True)
|
|
83
|
+
for name in self.ident.data_files:
|
|
84
|
+
if os.path.exists(os.path.join(self.ident.data_dir, name)):
|
|
85
|
+
shutil.copy2(os.path.join(self.ident.data_dir, name), keep)
|
|
86
|
+
self._move(self.ident.data_dir, self.original_dir)
|
|
87
|
+
|
|
88
|
+
def switch_to(self, label: str):
|
|
89
|
+
"""Brings back `label`'s own data files (none on its first run) and sets its registry values. App stopped."""
|
|
90
|
+
if self.running(self.ident.exe_name):
|
|
91
|
+
raise RuntimeError(f"{self.ident.exe_name} is running: stop it before switching accounts")
|
|
92
|
+
if self.current:
|
|
93
|
+
self._move(self.ident.data_dir, os.path.join(self.state_dir, self.current))
|
|
94
|
+
self._move(os.path.join(self.state_dir, label), self.ident.data_dir)
|
|
95
|
+
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.ident.registry_key) as key:
|
|
96
|
+
for name, template in self.cfg.get("profile_values", {}).items():
|
|
97
|
+
value = template.format(work=self.work_root, label=label)
|
|
98
|
+
if name.lower().endswith(("path", "folder")):
|
|
99
|
+
os.makedirs(value, exist_ok=True) # the account's own folder, under the test work root
|
|
100
|
+
winreg.SetValueEx(key, name, 0, winreg.REG_SZ, value)
|
|
101
|
+
for name in self.cfg.get("clear_values", []):
|
|
102
|
+
try:
|
|
103
|
+
winreg.DeleteValue(key, name)
|
|
104
|
+
except FileNotFoundError:
|
|
105
|
+
pass
|
|
106
|
+
self.current = label
|
|
107
|
+
|
|
108
|
+
def restore(self):
|
|
109
|
+
"""Parks the last account's data files and puts the owner's data files and registry key back."""
|
|
110
|
+
if self.current:
|
|
111
|
+
self._move(self.ident.data_dir, os.path.join(self.state_dir, self.current))
|
|
112
|
+
self.current = None
|
|
113
|
+
self._move(self.original_dir, self.ident.data_dir)
|
|
114
|
+
if os.path.exists(self.backup_reg):
|
|
115
|
+
subprocess.run(["reg", "delete", "HKCU\\" + self.ident.registry_key, "/f"], capture_output=True)
|
|
116
|
+
if os.path.getsize(self.backup_reg) > 0:
|
|
117
|
+
subprocess.run(["reg", "import", self.backup_reg], check=True, capture_output=True)
|
|
118
|
+
os.remove(self.backup_reg)
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Builds the app under test from the product repository plus a private test patch (UI Automation names, test hooks).
|
|
3
|
+
|
|
4
|
+
python build_test_app.py --repo <product repo> --project src/App/App.csproj --ref origin/main --patch <tool repo>\\app_patch\\uia-hooks.patch
|
|
5
|
+
python build_test_app.py --repo <product repo> --project src/App/App.csproj --ref origin/feature/x --patch -
|
|
6
|
+
|
|
7
|
+
The product repository is only READ: `git archive` exports the ref into a new folder that is not a git repository,
|
|
8
|
+
the patch is applied there and the app is built into <out-root>\\<ref>-<sha7>\\out. Nothing is ever committed, branched
|
|
9
|
+
or pushed to the product repository: when that repository belongs to a customer, even a pushed branch is visible to
|
|
10
|
+
them, so test-only code stays a patch in the team's own tool repository.
|
|
11
|
+
A folder that already holds the same commit built with the same patch is reused unless --rebuild is given.
|
|
12
|
+
The build command is `dotnet build <project>`; for another stack, replace build() (one function).
|
|
13
|
+
"""
|
|
14
|
+
import argparse
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import tarfile
|
|
23
|
+
import time
|
|
24
|
+
|
|
25
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
26
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
27
|
+
# Outside every repository: `git apply` inside one resolves the patch paths from that repository's root.
|
|
28
|
+
DEFAULT_OUT_ROOT = os.environ.get("TEST_BUILD_ROOT") or os.path.join(os.path.expanduser("~"), "_testbuild")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class BuildError(RuntimeError):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def git(repo, *args, binary=False):
|
|
36
|
+
r = subprocess.run(["git", "-C", repo, *args], capture_output=True)
|
|
37
|
+
if r.returncode:
|
|
38
|
+
raise BuildError(f"git {' '.join(args)}: {r.stderr.decode('utf-8', 'replace').strip()}")
|
|
39
|
+
return r.stdout if binary else r.stdout.decode("utf-8").strip()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def inside_git_repo(path) -> bool:
|
|
43
|
+
"""`git apply` in a folder inside some repository resolves the patch's paths from that repository's root."""
|
|
44
|
+
probe = path
|
|
45
|
+
while not os.path.exists(probe):
|
|
46
|
+
probe = os.path.dirname(probe)
|
|
47
|
+
return subprocess.run(["git", "-C", probe, "rev-parse", "--show-toplevel"], capture_output=True).returncode == 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def sha256(path) -> str:
|
|
51
|
+
return hashlib.sha256(open(path, "rb").read()).hexdigest() if path else ""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def export(repo, sha, dest):
|
|
55
|
+
"""The commit's files, without a .git: nothing done here can reach the customer's repository."""
|
|
56
|
+
archive = git(repo, "archive", "--format=tar", sha, binary=True)
|
|
57
|
+
tar_path = dest + ".tar"
|
|
58
|
+
with open(tar_path, "wb") as f:
|
|
59
|
+
f.write(archive)
|
|
60
|
+
with tarfile.open(tar_path) as t:
|
|
61
|
+
t.extractall(dest, filter="data")
|
|
62
|
+
os.remove(tar_path)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def apply_patch(src, patch):
|
|
66
|
+
r = subprocess.run(["git", "apply", "--whitespace=nowarn", "-p1", patch], cwd=src, capture_output=True)
|
|
67
|
+
if r.returncode:
|
|
68
|
+
failed = sorted(set(re.findall(r"patch failed: ([^:]+):", r.stderr.decode("utf-8", "replace"))))
|
|
69
|
+
raise BuildError("the patch does not apply to this commit; refresh it for: " + (", ".join(failed) or
|
|
70
|
+
r.stderr.decode("utf-8", "replace").strip()))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def build(src, out, config, project):
|
|
74
|
+
r = subprocess.run(["dotnet", "build", os.path.join(src, project), "-c", config, "-o", out, "-nologo", "-v", "q"],
|
|
75
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace")
|
|
76
|
+
if r.returncode:
|
|
77
|
+
tail = "\n".join((r.stdout + r.stderr).strip().splitlines()[-15:])
|
|
78
|
+
raise BuildError("dotnet build failed:\n" + tail)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def find_exe(out):
|
|
82
|
+
exes = [f for f in os.listdir(out) if f.lower().endswith(".exe") and f.lower() not in ("createdump.exe",)]
|
|
83
|
+
if len(exes) != 1:
|
|
84
|
+
raise BuildError(f"expected one app exe in {out}, found {exes}")
|
|
85
|
+
return os.path.join(out, exes[0])
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def main(argv=None):
|
|
89
|
+
a = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
|
90
|
+
a.add_argument("--repo", required=True, help="the customer's repository (read only)")
|
|
91
|
+
a.add_argument("--ref", default="origin/main", help="commit, branch or tag to build")
|
|
92
|
+
a.add_argument("--project", required=True, help="project file to build, relative to the repository root")
|
|
93
|
+
a.add_argument("--patch", required=True, help="private test patch applied on top; '-' for none")
|
|
94
|
+
a.add_argument("--out-root", default=DEFAULT_OUT_ROOT)
|
|
95
|
+
a.add_argument("--config", default="Release")
|
|
96
|
+
a.add_argument("--rebuild", action="store_true")
|
|
97
|
+
args = a.parse_args(argv)
|
|
98
|
+
|
|
99
|
+
patch = None if args.patch == "-" else os.path.abspath(args.patch)
|
|
100
|
+
out_root = os.path.abspath(args.out_root)
|
|
101
|
+
if inside_git_repo(out_root):
|
|
102
|
+
raise BuildError(f"{out_root} is inside a git repository: choose --out-root outside any repository")
|
|
103
|
+
sha = git(args.repo, "rev-parse", "--verify", args.ref + "^{commit}")
|
|
104
|
+
name = re.sub(r"[^A-Za-z0-9._-]+", "-", args.ref.replace("origin/", "")).strip("-") + "-" + sha[:7]
|
|
105
|
+
dest = os.path.join(out_root, name)
|
|
106
|
+
info_path = os.path.join(dest, "build_info.json")
|
|
107
|
+
info = {"repo": os.path.abspath(args.repo), "project": args.project, "ref": args.ref, "sha": sha, "config": args.config,
|
|
108
|
+
"patch": patch, "patch_sha256": sha256(patch)}
|
|
109
|
+
|
|
110
|
+
if not args.rebuild and os.path.exists(info_path):
|
|
111
|
+
old = json.load(open(info_path, encoding="utf-8"))
|
|
112
|
+
if all(old.get(k) == v for k, v in info.items()) and os.path.exists(old.get("exe", "")):
|
|
113
|
+
print("up to date:", old["exe"])
|
|
114
|
+
return old["exe"]
|
|
115
|
+
if os.path.exists(dest):
|
|
116
|
+
# Only a folder this script made (build_info.json, or just src/out from a build that stopped half-way).
|
|
117
|
+
if not os.path.exists(info_path) and not set(os.listdir(dest)) <= {"src", "out", "src.tar"}:
|
|
118
|
+
raise BuildError(f"{dest} exists and was not made by this script: nothing deleted")
|
|
119
|
+
shutil.rmtree(dest)
|
|
120
|
+
src, out = os.path.join(dest, "src"), os.path.join(dest, "out")
|
|
121
|
+
os.makedirs(src)
|
|
122
|
+
print(f"export {args.ref} ({sha[:7]}) -> {src}")
|
|
123
|
+
export(args.repo, sha, src)
|
|
124
|
+
if patch:
|
|
125
|
+
print("apply", os.path.basename(patch))
|
|
126
|
+
apply_patch(src, patch)
|
|
127
|
+
print(f"dotnet build -c {args.config} -> {out}")
|
|
128
|
+
build(src, out, args.config, args.project)
|
|
129
|
+
info.update(exe=find_exe(out), built_at=time.strftime("%Y-%m-%d %H:%M:%S"))
|
|
130
|
+
json.dump(info, open(info_path, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
|
131
|
+
print("built:", info["exe"])
|
|
132
|
+
return info["exe"]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
if __name__ == "__main__":
|
|
136
|
+
try:
|
|
137
|
+
main()
|
|
138
|
+
except BuildError as e:
|
|
139
|
+
print("ERROR:", e)
|
|
140
|
+
sys.exit(1)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Runs the app's command-line entry points (a second process handing a request to the running app, a one-shot
|
|
3
|
+
mode, an integration called by another program) and reports exit code and timing.
|
|
4
|
+
|
|
5
|
+
r = cli.run(exe, ["--some-command=<id>", "--path=C:\\a b"])
|
|
6
|
+
ctx.check(r.accepted, f"accepted: {r}")
|
|
7
|
+
|
|
8
|
+
Each argument is one argv entry, so a path with spaces arrives whole. A process that has not exited at the timeout
|
|
9
|
+
is killed — it is the one this call started, never the running app (another pid). Most hand-over commands return as
|
|
10
|
+
soon as the request is accepted: check the effect separately (waits.py).
|
|
11
|
+
"""
|
|
12
|
+
import os
|
|
13
|
+
import subprocess
|
|
14
|
+
import time
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class CliResult:
|
|
20
|
+
args: list
|
|
21
|
+
code: int | None # None: still running at the timeout (then killed)
|
|
22
|
+
seconds: float
|
|
23
|
+
stdout: str
|
|
24
|
+
stderr: str
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def accepted(self) -> bool:
|
|
28
|
+
return self.code == 0
|
|
29
|
+
|
|
30
|
+
def __str__(self):
|
|
31
|
+
return f"exit {self.code} in {self.seconds:.1f}s: {' '.join(self.args[1:])}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run(exe: str, args: list[str], timeout: float = 60) -> CliResult:
|
|
35
|
+
cmd = [exe, *args]
|
|
36
|
+
started = time.time()
|
|
37
|
+
p = subprocess.Popen(cmd, cwd=os.path.dirname(exe) or None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
38
|
+
try:
|
|
39
|
+
out, err = p.communicate(timeout=timeout)
|
|
40
|
+
code = p.returncode
|
|
41
|
+
except subprocess.TimeoutExpired:
|
|
42
|
+
p.kill()
|
|
43
|
+
out, err = p.communicate()
|
|
44
|
+
code = None
|
|
45
|
+
return CliResult(cmd, code, time.time() - started,
|
|
46
|
+
out.decode("utf-8", "replace"), err.decode("utf-8", "replace"))
|