dsh-quiet-windows 0.0.0-stage → 0.2.2

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.
@@ -0,0 +1,83 @@
1
+ """浏览器回归测试:验证「独立 profile + 窗口进程归属」这条最容易出事的路径。
2
+
3
+ 默认不运行(会真的拉起浏览器)。手动跑:
4
+
5
+ python tests/regress_browser.py --run
6
+
7
+ 检查三件事:
8
+ 1. 窗口属于本次启动的进程(process_mismatch == False)—— 没有寄生到用户已开的浏览器;
9
+ 2. 窗口落在所有显示器之外,且从未上屏;
10
+ 3. 截图有内容,关掉之后进程不残留。
11
+ """
12
+ import json
13
+ import os
14
+ import subprocess
15
+ import sys
16
+
17
+ HERE = os.path.dirname(os.path.abspath(__file__))
18
+ HELPER = os.path.join(HERE, "..", "helper", "quietwin.py")
19
+
20
+ CANDIDATES = [
21
+ r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
22
+ r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
23
+ r"C:\Program Files\Google\Chrome\Application\chrome.exe",
24
+ ]
25
+
26
+
27
+ def run(*args):
28
+ proc = subprocess.run([sys.executable, "-X", "utf8", HELPER, *args, "--json"],
29
+ capture_output=True, text=True, encoding="utf-8")
30
+ try:
31
+ return json.loads(proc.stdout)
32
+ except json.JSONDecodeError:
33
+ raise SystemExit(f"helper 输出不是 JSON:{proc.stdout[:400]} {proc.stderr[:400]}")
34
+
35
+
36
+ def main() -> int:
37
+ if "--run" not in sys.argv:
38
+ print("默认跳过(会真的拉起浏览器)。要跑请加 --run")
39
+ return 0
40
+ exe = next((p for p in CANDIDATES if os.path.exists(p)), None)
41
+ if exe is None:
42
+ print("没找到 Edge/Chrome,跳过")
43
+ return 0
44
+
45
+ print("使用浏览器:", exe)
46
+ launched = run("launch", "--exe", exe, "--width", "1000", "--height", "720",
47
+ "--timeout", "120", "--argv-json", '["about:blank"]')
48
+ if launched.get("ok") is not True:
49
+ print("启动失败:", launched)
50
+ return 1
51
+
52
+ failures = []
53
+ if launched.get("process_mismatch") is not False:
54
+ failures.append("窗口不属于本次启动的进程(可能寄生到了已运行的浏览器)")
55
+ if launched.get("offscreen") is not True:
56
+ failures.append("窗口没有落在屏幕外")
57
+ if launched.get("flashed") is not False:
58
+ failures.append("窗口在创建过程中上过屏")
59
+ print("profile:", launched.get("isolated_profile"))
60
+ print("窗口 pid:", launched.get("pid"), "启动 pid:", launched.get("proc_pid"))
61
+
62
+ shot = run("shot", "--hwnd", str(launched["hwnd"]), "--out", os.path.join(HERE, "_regress.png"),
63
+ "--expect-pid", str(launched["pid"]))
64
+ if shot.get("ok") is not True:
65
+ failures.append("截图失败:" + str(shot.get("error")))
66
+ elif shot.get("looks_blank"):
67
+ failures.append("截图接近纯色(浏览器在屏幕外停止绘制)")
68
+
69
+ closed = run("close", "--hwnd", str(launched["hwnd"]), "--expect-pid", str(launched["pid"]))
70
+ if closed.get("closed") is not True:
71
+ failures.append("窗口没有关闭")
72
+
73
+ if failures:
74
+ print("失败:")
75
+ for item in failures:
76
+ print(" -", item)
77
+ return 1
78
+ print("通过:独立 profile、窗口归属正确、离屏、可截图、可关闭")
79
+ return 0
80
+
81
+
82
+ if __name__ == "__main__":
83
+ sys.exit(main())
@@ -0,0 +1,73 @@
1
+ """不开窗口的单元测试:只覆盖纯计算与句柄校验,跑起来不碰你的桌面。
2
+
3
+ python -m unittest discover -s tests -p "test_*.py"
4
+
5
+ 需要 GUI 的回归测试在同目录 regress_browser.py,默认不跑。
6
+ """
7
+ import os
8
+ import sys
9
+ import unittest
10
+
11
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "helper"))
12
+
13
+ import quietwin as q # noqa: E402
14
+
15
+
16
+ def overlaps(rect, monitor):
17
+ x1, y1, x2, y2 = rect
18
+ mx1, my1, mx2, my2 = monitor
19
+ return x2 > mx1 and x1 < mx2 and y2 > my1 and y1 < my2
20
+
21
+
22
+ class OffscreenOriginTest(unittest.TestCase):
23
+ """屏幕外原点必须对「任意」显示器布局都落在所有显示器之外。"""
24
+
25
+ LAYOUTS = [
26
+ [(0, 0, 2560, 1440)],
27
+ [(-1920, 0, 0, 1080), (0, 0, 2560, 1440)],
28
+ [(0, -900, 1920, 1080), (1920, 0, 3840, 1440)],
29
+ ]
30
+
31
+ def test_origin_never_touches_any_monitor(self):
32
+ original = q.monitors
33
+ try:
34
+ for layout in self.LAYOUTS:
35
+ q.monitors = lambda layout=layout: layout
36
+ for width, height in [(1, 1), (800, 600), (3840, 2160)]:
37
+ x, y = q.offscreen_origin(width, height)
38
+ rect = (x, y, x + width, y + height)
39
+ for monitor in layout:
40
+ self.assertFalse(
41
+ overlaps(rect, monitor),
42
+ f"{width}x{height} @ ({x},{y}) 与显示器 {monitor} 相交",
43
+ )
44
+ finally:
45
+ q.monitors = original
46
+
47
+ def test_real_layout_is_readable(self):
48
+ self.assertTrue(len(q.monitors()) >= 1)
49
+
50
+
51
+ class VerifyPidTest(unittest.TestCase):
52
+ """句柄复用防护:给了期望 pid 就必须校验,不给就放行。"""
53
+
54
+ def test_no_expectation_passes(self):
55
+ self.assertIsNone(q.verify_pid(0, None))
56
+
57
+ def test_wrong_process_is_rejected(self):
58
+ result = q.verify_pid(0, 999999)
59
+ self.assertIsNotNone(result)
60
+ self.assertFalse(result["ok"])
61
+ self.assertIn("复用", result["error"])
62
+
63
+
64
+ class DescribeTest(unittest.TestCase):
65
+ """describe() 对无效句柄要返回 error 而不是抛异常。"""
66
+
67
+ def test_invalid_handle_reports_error(self):
68
+ info = q.describe(0)
69
+ self.assertIn("error", info)
70
+
71
+
72
+ if __name__ == "__main__":
73
+ unittest.main()
@@ -0,0 +1,159 @@
1
+ /**
2
+ * 不开窗口的插件层测试。
3
+ *
4
+ * node --test tests/
5
+ *
6
+ * 覆盖:工具注册数量与取值、schema 完整性、render 对成功/失败结果的容错、
7
+ * 以及「找不到可用 Python」时是否给出能照做的错误。
8
+ */
9
+ import assert from 'node:assert/strict';
10
+ import { spawn } from 'node:child_process';
11
+ import test from 'node:test';
12
+
13
+ const MODULE = new URL('../index.js', import.meta.url).href;
14
+
15
+ function harness(spawnImpl) {
16
+ const tools = new Map();
17
+ const ctx = {
18
+ subprocess: { spawn: spawnImpl },
19
+ tools: {
20
+ register(def) {
21
+ tools.set(def.name, def);
22
+ return () => tools.delete(def.name);
23
+ },
24
+ },
25
+ effect() {},
26
+ };
27
+ return { tools, ctx };
28
+ }
29
+
30
+ /** 永远失败的 spawn:模拟「这台机器没有装好依赖的 Python」。 */
31
+ function failingSpawn() {
32
+ return () => ({
33
+ done: Promise.resolve({ exitCode: 1, signal: null }),
34
+ collected: {
35
+ stdout: { readFrom: () => ({ text: '', lossy: false, truncated: false }) },
36
+ stderr: {
37
+ readFrom: () => ({
38
+ text: 'ModuleNotFoundError: No module named win32gui',
39
+ lossy: false,
40
+ truncated: false,
41
+ }),
42
+ },
43
+ },
44
+ });
45
+ }
46
+
47
+ /** 真跑子进程的 spawn,用来验证成功路径。 */
48
+ function realSpawn(spec) {
49
+ const [cmd, ...args] = spec.argv;
50
+ const child = spawn(cmd, args, { cwd: spec.cwd, windowsHide: true });
51
+ let out = '';
52
+ let err = '';
53
+ child.stdout.on('data', (d) => { out += d; });
54
+ child.stderr.on('data', (d) => { err += d; });
55
+ const done = new Promise((resolve) => child.on('close', (code) => resolve({ exitCode: code, signal: null })));
56
+ return {
57
+ done,
58
+ collected: {
59
+ stdout: { readFrom: () => ({ text: out, lossy: false, truncated: false }) },
60
+ stderr: { readFrom: () => ({ text: err, lossy: false, truncated: false }) },
61
+ },
62
+ };
63
+ }
64
+
65
+ // 用一个中性的临时目录,别把作者机器上的路径写进公开仓库。
66
+ const EXEC = { agent: { session: { header: { cwd: process.cwd() } } } };
67
+ const EXPECTED = ['quiet_act', 'quiet_close', 'quiet_launch', 'quiet_shot', 'quiet_tree', 'quiet_windows'];
68
+
69
+ test('注册六个工具', async () => {
70
+ const { tools, ctx } = harness(failingSpawn());
71
+ const { apply } = await import(MODULE);
72
+ apply(ctx, {});
73
+ assert.deepEqual([...tools.keys()].sort(), EXPECTED);
74
+ });
75
+
76
+ test('每个工具的 schema 与 render 都完整', async () => {
77
+ const { tools, ctx } = harness(failingSpawn());
78
+ const { apply } = await import(MODULE);
79
+ apply(ctx, {});
80
+ for (const name of EXPECTED) {
81
+ const def = tools.get(name);
82
+ assert.equal(typeof def.description, 'string');
83
+ assert.ok(def.description.length > 10, name + ' 缺少描述');
84
+ assert.equal(def.parameters.type, 'object');
85
+ assert.equal(typeof def.output.render, 'function');
86
+ const blocks = def.output.render({}, { ok: false, error: '测试用错误' });
87
+ assert.ok(Array.isArray(blocks) && blocks.length > 0, name + ' render 没有返回内容');
88
+ assert.equal(blocks[0].type, 'text');
89
+ assert.match(blocks[0].text, /测试用错误/, name + ' 没有把错误带出来');
90
+ }
91
+ });
92
+
93
+ test('必需参数被写进 required', async () => {
94
+ const { tools, ctx } = harness(failingSpawn());
95
+ const { apply } = await import(MODULE);
96
+ apply(ctx, {});
97
+ assert.deepEqual(tools.get('quiet_launch').parameters.required, ['exe']);
98
+ assert.deepEqual(tools.get('quiet_act').parameters.required, ['hwnd', 'op']);
99
+ assert.deepEqual(tools.get('quiet_shot').parameters.required, ['hwnd']);
100
+ assert.equal(tools.get('quiet_windows').parameters.required, undefined);
101
+ });
102
+
103
+ test('Python 依赖缺失时给出可照做的错误', async () => {
104
+ const { tools, ctx } = harness(failingSpawn());
105
+ const { apply } = await import(MODULE);
106
+ apply(ctx, {});
107
+ const tool = tools.get('quiet_windows');
108
+ await assert.rejects(
109
+ () => tool.execute({}, EXEC),
110
+ (error) => {
111
+ assert.match(error.message, /pywin32/, '错误里要写明缺哪个依赖');
112
+ assert.match(error.message, /pythonPath/, '错误里要给出配置入口');
113
+ assert.match(error.message, /已尝试/, '错误里要列出试过哪些解释器');
114
+ return true;
115
+ },
116
+ );
117
+ });
118
+
119
+ /** 复刻宿主行为:cwd 不是字符串就在 spawn 内部抛错(0.2.0 的真实故障点)。 */
120
+ function strictSpawn(spec) {
121
+ if (typeof spec.cwd !== 'string' || spec.cwd === '') {
122
+ throw new TypeError("Cannot read properties of undefined (reading 'includes')");
123
+ }
124
+ return realSpawn(spec);
125
+ }
126
+
127
+ test('探测解释器时 cwd 必须是字符串(宿主契约)', async () => {
128
+ const { tools, ctx } = harness(strictSpawn);
129
+ const { apply } = await import(MODULE);
130
+ apply(ctx, {});
131
+ // 解析成功就说明探测调用带上了合法 cwd;否则 strictSpawn 会抛错并让工具失败。
132
+ const value = await tools.get('quiet_windows').execute({}, EXEC);
133
+ assert.equal(value.ok, true);
134
+ });
135
+
136
+ test('真实环境下能找到 Python 并列出屏幕外窗口', async () => {
137
+ const { tools, ctx } = harness(realSpawn);
138
+ const { apply } = await import(MODULE);
139
+ apply(ctx, {});
140
+ const value = await tools.get('quiet_windows').execute({}, EXEC);
141
+ assert.equal(value.ok, true);
142
+ assert.ok(Array.isArray(value.monitors) && value.monitors.length >= 1);
143
+ assert.ok(Array.isArray(value.offscreen));
144
+ });
145
+
146
+ test('launch → close 全链路可用(离屏,全程不碰桌面)', async () => {
147
+ const { tools, ctx } = harness(realSpawn);
148
+ const { apply } = await import(MODULE);
149
+ apply(ctx, { launchTimeoutMs: 60000 });
150
+ const tool = tools.get('quiet_launch');
151
+ assert.equal(tool.timeoutMs, 60000);
152
+ const value = await tool.execute({ exe: 'charmap.exe', width: 640, height: 560 }, EXEC);
153
+ assert.equal(value.ok, true);
154
+ assert.equal(value.offscreen, true);
155
+ assert.equal(value.process_mismatch, false, '窗口应属于本次启动的进程');
156
+ assert.ok(Number.isInteger(value.pid));
157
+ const closed = await tools.get('quiet_close').execute({ hwnd: value.hwnd }, EXEC);
158
+ assert.equal(closed.closed, true);
159
+ });