dsh-native-uia 0.6.2 → 0.6.4

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.
@@ -1,1071 +1,1074 @@
1
- # scripts/regression-worker.ps1 -- 元素定位阶梯(match ladder)回归测试
2
- #
3
- # 跑法:
4
- # powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\regression-worker.ps1
5
- # 退出码:
6
- # 0 = 全部通过, 1 = 有断言失败, 2 = 环境/源码问题(worker 解析失败、文件缺失)
7
- #
8
- # 为什么不能 dot-source 整个 worker:
9
- # uia-worker.ps1 末尾是 [Console]::In.ReadLine() 常驻循环, dot-source 会直接把测试挂死。
10
- # 这里只用 Parser::ParseFile 做静态解析, 然后按函数名把「函数定义的源码文本」抽出来,
11
- # 在当前作用域里 Invoke-Expression 重新定义。参数表、注释、闭包都原样保留
12
- # (注意: FunctionDefinitionAst.Body.GetScriptBlock() 会丢掉 param 块, 不能用)。
13
- # 真正会碰桌面的那一层(窗口句柄 → AutomationElement)用同名 mock 顶替, 其余依赖函数
14
- # (Dict / ArgOf / Err / TruncStr / TickNow / Test-Deadline / RectOf / ControlTypeName)
15
- # 按真实源码加载, 所以测的是 worker 里的真实现。
16
- #
17
- # 无副作用: 不 SendInput、不点桌面、不写注册表、不启动常驻 worker、不读任何凭据。
18
- #
19
- # 编码须知: 本文件含中文测试数据, 必须保存为 UTF-8 **带 BOM**。
20
- # Windows PowerShell 5.1 对无 BOM 的 .ps1 按 ANSI 代码页解析, 中文会变乱码且测试会静默错位。
21
- # 下面的 Assert-SourceEncoding 会在启动时自检并明确报错。
22
-
23
- $ErrorActionPreference = 'Stop'
24
- Set-StrictMode -Off
25
-
26
- Add-Type -AssemblyName UIAutomationClient
27
- Add-Type -AssemblyName UIAutomationTypes
28
-
29
- $script:pass = 0
30
- $script:fail = 0
31
- $script:failures = New-Object System.Collections.Generic.List[string]
32
-
33
- function Write-Pass([string]$name) {
34
- $script:pass += 1
35
- Write-Host ('PASS ' + $name)
36
- }
37
- function Write-Fail([string]$name, [string]$why) {
38
- $script:fail += 1
39
- $script:failures.Add($name + ' :: ' + $why) | Out-Null
40
- Write-Host ('FAIL ' + $name + ' -- ' + $why)
41
- }
42
- function Assert-Equal([string]$name, $actual, $expected) {
43
- $a = [string]$actual
44
- $e = [string]$expected
45
- if ([string]::Equals($a, $e, [StringComparison]::Ordinal)) { Write-Pass $name }
46
- else { Write-Fail $name ('expected <' + $e + '> got <' + $a + '>') }
47
- }
48
- function Assert-Bool([string]$name, $actual, [bool]$expected) {
49
- if ([bool]$actual -eq $expected) { Write-Pass $name }
50
- else { Write-Fail $name ('expected ' + $expected + ' got ' + [string]([bool]$actual)) }
51
- }
52
- function Assert-Int([string]$name, $actual, [int]$expected) {
53
- if ([int]$actual -eq $expected) { Write-Pass $name }
54
- else { Write-Fail $name ('expected ' + $expected + ' got ' + [string]$actual) }
55
- }
56
- function Assert-Score([string]$name, $actual, [double]$expected) {
57
- $d = [Math]::Abs([double]$actual - $expected)
58
- if ($d -lt 0.0005) { Write-Pass $name }
59
- else { Write-Fail $name ('expected score ' + $expected + ' got ' + [string]$actual) }
60
- }
61
- function Assert-True([string]$name, [bool]$cond, [string]$detail) {
62
- if ($cond) { Write-Pass $name } else { Write-Fail $name $detail }
63
- }
64
- function Section([string]$title) {
65
- Write-Host ''
66
- Write-Host ('--- ' + $title + ' ---')
67
- }
68
-
69
- # ---------------------------------------------------------------- 源码自检
70
- function Assert-SourceEncoding {
71
- # 本文件若被存成 UTF-8 无 BOM,PS 5.1 会按 ANSI 解码,'会话' 就不再等于 U+4F1A U+9BDD。
72
- $want = -join @([char]0x4F1A, [char]0x8BDD)
73
- if (-not [string]::Equals($want, '会话', [StringComparison]::Ordinal)) {
74
- Write-Host 'FAIL 0.0 测试文件编码错误: 必须保存为 UTF-8 且带 BOM'
75
- Write-Host (' 解析出的 "会话" = ' + ([int][char]'会') + ',' + ([int][char]'话') + ' 期望 ' + [int][char]0x4F1A + ',' + [int][char]0x9BDD)
76
- exit 2
77
- }
78
- Write-Pass '0.0 测试文件按 UTF-8 正确解码'
79
- }
80
-
81
- # ---------------------------------------------------------------- worker 加载
82
- $script:workerPath = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\worker\uia-worker.ps1'))
83
- $script:workerAst = $null
84
- $script:fnAst = @{}
85
-
86
- function Initialize-WorkerSource {
87
- if (-not (Test-Path -LiteralPath $script:workerPath)) { throw ('找不到 worker: ' + $script:workerPath) }
88
- $tokens = $null
89
- $errors = $null
90
- $script:workerAst = [System.Management.Automation.Language.Parser]::ParseFile($script:workerPath, [ref]$tokens, [ref]$errors)
91
- if ($errors.Count -gt 0) {
92
- foreach ($e in $errors) { Write-Host ('PARSE L' + $e.Extent.StartLineNumber + ': ' + $e.Message) }
93
- throw ('worker 解析失败, ' + $errors.Count + ' 个语法错误')
94
- }
95
- $all = $script:workerAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)
96
- foreach ($f in $all) { if (-not $script:fnAst.ContainsKey($f.Name)) { $script:fnAst[$f.Name] = $f } }
97
- # The body was split into worker/lib (the entry dot-sources it in the order sources.mjs declares).
98
- # Parse every part so Get-WorkerFunctionSource still finds the real definition; a part with a
99
- # syntax error fails here instead of at the first live tool call.
100
- $libDir = Join-Path (Split-Path -Parent $script:workerPath) 'lib'
101
- $script:partAsts = New-Object System.Collections.Generic.List[object]
102
- if (Test-Path -LiteralPath $libDir) {
103
- foreach ($part in (Get-ChildItem -LiteralPath $libDir -Filter '*.ps1' | Sort-Object Name)) {
104
- $tp = $null
105
- $ep = $null
106
- $partAst = [System.Management.Automation.Language.Parser]::ParseFile($part.FullName, [ref]$tp, [ref]$ep)
107
- if ($ep.Count -gt 0) {
108
- foreach ($e in $ep) { Write-Host ('PARSE ' + $part.Name + ' L' + $e.Extent.StartLineNumber + ': ' + $e.Message) }
109
- throw ($part.Name + ' 解析失败, ' + $ep.Count + ' 个语法错误')
110
- }
111
- $script:partAsts.Add($partAst) | Out-Null
112
- $allPart = $partAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)
113
- foreach ($f in $allPart) { if (-not $script:fnAst.ContainsKey($f.Name)) { $script:fnAst[$f.Name] = $f } }
114
- }
115
- }
116
- # 共享 stdio 框架在 worker/ps-stdio.ps1(worker 在运行时 dot-source 它)。按函数名抽取
117
- # 也要把它的 FunctionDefinitionAst 并进来,否则 $workerDeps 里的 Dict/JsonOf/Split-Err/
118
- # Esc 等会在 Get-WorkerFunctionSource 报"worker 里没有函数 X"。
119
- $stdioPath = Join-Path (Split-Path -Parent $script:workerPath) 'ps-stdio.ps1'
120
- if (Test-Path -LiteralPath $stdioPath) {
121
- $t2 = $null
122
- $e2 = $null
123
- $stdioAst = [System.Management.Automation.Language.Parser]::ParseFile($stdioPath, [ref]$t2, [ref]$e2)
124
- if ($e2.Count -gt 0) {
125
- foreach ($e in $e2) { Write-Host ('PARSE ps-stdio L' + $e.Extent.StartLineNumber + ': ' + $e.Message) }
126
- throw ('ps-stdio.ps1 解析失败, ' + $e2.Count + ' 个语法错误')
127
- }
128
- $all2 = $stdioAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)
129
- foreach ($f in $all2) { if (-not $script:fnAst.ContainsKey($f.Name)) { $script:fnAst[$f.Name] = $f } }
130
- }
131
- }
132
-
133
- function Get-WorkerFunctionSource([string[]]$names) {
134
- # 只取 FunctionDefinition 的完整源码文本(含 param 块),不执行 worker 本身。
135
- $parts = New-Object System.Collections.Generic.List[string]
136
- foreach ($n in $names) {
137
- if (-not $script:fnAst.ContainsKey($n)) { throw ('worker 里没有函数 ' + $n) }
138
- $parts.Add($script:fnAst[$n].Extent.Text) | Out-Null
139
- }
140
- return ($parts -join "`r`n")
141
- }
142
-
143
- function Get-WorkerAssignmentValue([string]$leftText) {
144
- # $handlers / $defaultBudget moved into worker/lib/10-dispatch.ps1 with the split: search every
145
- # parsed part, not just the entry, or the dispatch tests read "no handler" and pass on nothing.
146
- if ($null -ne $script:partAsts) {
147
- foreach ($ast in $script:partAsts) {
148
- $hit = $ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and $n.Left.Extent.Text -eq $leftText }, $true) | Select-Object -First 1
149
- if ($null -ne $hit) { return (Invoke-Expression $hit.Right.Extent.Text) }
150
- }
151
- }
152
- $a = $script:workerAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and $n.Left.Extent.Text -eq $leftText }, $true) | Select-Object -First 1
153
- if ($null -eq $a) { return $null }
154
- return (Invoke-Expression $a.Right.Extent.Text)
155
- }
156
-
157
- # ---------------------------------------------------------------- mock 环境
158
- # 只顶替真正读桌面的 Window-Ae;元素/窗口对象按 UIA 客户端的可观察形状造。
159
- $script:W = @{ dl = [Int64]::MaxValue; lastMatch = $null }
160
- $script:ctCache = @{}
161
- $script:mockAe = $null
162
- function Window-Ae($entry) { return $script:mockAe }
163
-
164
- function Test-MockCondition($cp, $cond) {
165
- # 忠实复现 UIA 条件语义,否则测的就不是阶梯而是 mock 自己的宽严。
166
- if ($null -eq $cond) { return $true }
167
- if ([object]::ReferenceEquals($cond, [System.Windows.Automation.Condition]::TrueCondition)) { return $true }
168
- $tn = $cond.GetType().Name
169
- if ($tn -eq 'AndCondition') {
170
- foreach ($c in $cond.GetConditions()) { if (-not (Test-MockCondition $cp $c)) { return $false } }
171
- return $true
172
- }
173
- if ($tn -eq 'PropertyCondition') {
174
- $p = $cond.Property
175
- $v = $cond.Value
176
- if ([object]::ReferenceEquals($p, [System.Windows.Automation.AutomationElement]::NameProperty)) { return ([string]::Equals([string]$cp.Name, [string]$v, [StringComparison]::Ordinal)) }
177
- if ([object]::ReferenceEquals($p, [System.Windows.Automation.AutomationElement]::AutomationIdProperty)) { return ([string]::Equals([string]$cp.AutomationId, [string]$v, [StringComparison]::Ordinal)) }
178
- if ([object]::ReferenceEquals($p, [System.Windows.Automation.AutomationElement]::ClassNameProperty)) { return ([string]::Equals([string]$cp.ClassName, [string]$v, [StringComparison]::Ordinal)) }
179
- if ([object]::ReferenceEquals($p, [System.Windows.Automation.AutomationElement]::ControlTypeProperty)) {
180
- # PropertyCondition 会把 ControlType 归一化成它的 Id(int),而不是保留 ControlType 对象。
181
- # 两种形状都要认,否则 mock 永远匹配不上 Button 条件(本轮就是这样翻车的)。
182
- $a = -1
183
- try { $a = [int]$cp.ControlType.Id } catch { $a = -1 }
184
- $b = -2
185
- if ($v -is [int]) { $b = [int]$v }
186
- else { try { $b = [int]$v.Id } catch { $b = -2 } }
187
- return ($a -eq $b)
188
- }
189
- throw ('mock 不认识该属性: ' + $p.ProgrammaticName)
190
- }
191
- throw ('mock 不认识该条件类型: ' + $tn)
192
- }
193
-
194
- function New-MockElement([string]$name, [string]$controlType, [string]$className, [string]$automationId, [double]$x, [double]$y, [double]$w, [double]$h) {
195
- $ct = $null
196
- if ($controlType -ne '') {
197
- $field = [System.Windows.Automation.ControlType].GetField($controlType)
198
- if ($null -ne $field) { $ct = $field.GetValue($null) }
199
- }
200
- # RectOf 只读 X/Y/Width/Height,用同形状的普通对象即可(不引入 WindowsBase 依赖)。
201
- $rect = [pscustomobject]@{ X = $x; Y = $y; Width = $w; Height = $h }
202
- $cp = [pscustomobject]@{
203
- Name = $name
204
- ControlType = $ct
205
- ClassName = $className
206
- AutomationId = $automationId
207
- IsEnabled = $true
208
- IsOffscreen = $false
209
- BoundingRectangle = $rect
210
- ProcessId = 4242
211
- }
212
- $el = [pscustomobject]@{ Current = $cp }
213
- $el | Add-Member -MemberType ScriptMethod -Name GetRuntimeId -Value { return @(4242, 1) }
214
- return $el
215
- }
216
-
217
- function New-MockWindow($elements) {
218
- $ae = [pscustomobject]@{ Items = @($elements) }
219
- $ae | Add-Member -MemberType ScriptMethod -Name FindAll -Value {
220
- param($scope, $cond)
221
- $out = New-Object System.Collections.ArrayList
222
- foreach ($e in $this.Items) {
223
- if (Test-MockCondition $e.Current $cond) { [void]$out.Add($e) }
224
- }
225
- return $out.ToArray()
226
- }
227
- $ae | Add-Member -MemberType ScriptMethod -Name FindFirst -Value {
228
- param($scope, $cond)
229
- foreach ($e in $this.Items) {
230
- if (Test-MockCondition $e.Current $cond) { return $e }
231
- }
232
- return $null
233
- }
234
- return $ae
235
- }
236
-
237
- function Invoke-Match($elements, $by) {
238
- $script:mockAe = New-MockWindow $elements
239
- $entry = @{ id = 'w1'; hwnd = 4200; revision = 1 }
240
- return (Find-ByDescriptor $entry $by)
241
- }
242
- # prepare_batch / commit_batch 会碰到下面这几层;全部 mock 掉,动作一律不落到桌面。
243
- # (它们不在 $workerDeps 里,所以不会被真实源码覆盖。)
244
- function PatternsOf($el) { return @('Invoke') }
245
- function GetPattern($el, $name) { return $null }
246
- function Do-Action($re, $action, $value, $step) { return 'uia' }
247
- function Cursor-Pos { return @{ x = 100; y = 100 } }
248
- function Foreground-Hwnd { return [IntPtr]::Zero }
249
- function Test-Escape { return $false }
250
- function Get-MatchInfo { return $script:W.lastMatch }
251
- function Get-CandidateReason($cand) {
252
- if ($null -eq $cand) { return '' }
253
- return [string]$cand['reason']
254
- }
255
- function Get-ItemCount($v) {
256
- # 不能用 @($v):PS 5.1 对 New-Object 造出来的 List[object] 会抛 "Argument types do not match"。
257
- if ($null -eq $v) { return 0 }
258
- if ($v -is [string]) { return 1 }
259
- if ($v -is [System.Collections.ICollection]) { return [int]$v.Count }
260
- if ($v -is [System.Collections.IEnumerable]) {
261
- $n = 0
262
- foreach ($x in $v) { $n += 1 }
263
- return $n
264
- }
265
- return 1
266
- }
267
-
268
-
269
-
270
-
271
- # ---------------------------------------------------------------- 快照/扫描/窗口 mock(P-01/P-02/P-09)
272
- # 真正碰桌面的三处顶替(都不在 $workerDeps 里,所以不会被真实源码覆盖):
273
- # Get-SnapshotWalker 生产源码走 ControlViewWalker;这里给 mock walker,让 walker 回退
274
- # 路径也能在内存里走完整棵树(一次性路径失败时的那条分支)。
275
- # Window-ObservationHeader 位置元数据探测读真实前台/焦点(跨进程),不属于本文件的被测面。
276
- # RootWindows commit 窗口 diff 枚举桌面根窗口;由 $script:mockRootWindows 驱动两态。
277
- function Get-SnapshotWalker { return $script:mockWalker }
278
- function Window-ObservationHeader($entry) { return @{} }
279
- # RootWindows mock:commit_batch 在 phase 2 前后各枚举一次(每次调用一对),用奇偶切换返回
280
- # before/after 两个集合,让同一次 commit 内的 diff 可以构造出「新窗口」。
281
- $script:mockRootCalls = 0
282
- $script:mockRootBefore = @()
283
- $script:mockRootAfter = @()
284
- function RootWindows {
285
- $script:mockRootCalls += 1
286
- if (($script:mockRootCalls % 2) -eq 1) { return $script:mockRootBefore }
287
- return $script:mockRootAfter
288
- }
289
-
290
- $script:mockWalker = [pscustomobject]@{}
291
- $script:mockWalker | Add-Member -MemberType ScriptMethod -Name GetFirstChild -Value {
292
- param($el, $req)
293
- if ($null -eq $el.Children -or $el.Children.Count -eq 0) { return $null }
294
- $c = $el.Children[0]
295
- $c.Parent = $el
296
- return $c
297
- }
298
- $script:mockWalker | Add-Member -MemberType ScriptMethod -Name GetNextSibling -Value {
299
- param($el, $req)
300
- $p = $el.Parent
301
- if ($null -eq $p) { return $null }
302
- $idx = -1
303
- for ($i = 0; $i -lt $p.Children.Count; $i++) { if ([object]::ReferenceEquals($p.Children[$i], $el)) { $idx = $i; break } }
304
- if ($idx -lt 0 -or ($idx + 1) -ge $p.Children.Count) { return $null }
305
- $n = $p.Children[$idx + 1]
306
- $n.Parent = $p
307
- return $n
308
- }
309
-
310
- # AutomationElementCollection 的最小替身:.Count + int 索引器 + GetEnumerator,让 worker 的
311
- # CachedChildren 消费代码(Count、[i]、for 反向 push)和 mock walker 的 Children 遍历都按真实
312
- # 形状工作。
313
- if (-not ('MockElementCollection' -as [type])) {
314
- Add-Type -TypeDefinition 'public class MockElementCollection { private System.Collections.Generic.List<object> items = new System.Collections.Generic.List<object>(); public MockElementCollection(object[] src) { if (src != null) { foreach (object i in src) { items.Add(i); } } } public int Count { get { return items.Count; } } public object this[int i] { get { return items[i]; } } public System.Collections.IEnumerator GetEnumerator() { return items.GetEnumerator(); } }'
315
- }
316
- function New-MockElementCollection([object[]]$items = @()) {
317
- return (New-Object MockElementCollection (,$items))
318
- }
319
-
320
- # 带缓存形状的 mock 元素:Current/Cached 同构、CachedChildren 导航、GetCachedPropertyValue 供
321
- # RuntimeIdKey 的缓存读(其余可用性一律 $false,避免牵动 Cached-PatternsOf 的列表内容)。
322
- $script:snapRid = 100
323
- function New-MockSnapElement([string]$name, [string]$ct, [object[]]$children = @()) {
324
- $script:snapRid += 1
325
- $ctObj = $null
326
- $field = [System.Windows.Automation.ControlType].GetField($ct)
327
- if ($null -ne $field) { $ctObj = $field.GetValue($null) }
328
- $rect = [pscustomobject]@{ X = 5.0; Y = 5.0; Width = 100.0; Height = 20.0 }
329
- $cp = [pscustomobject]@{ Name = $name; ControlType = $ctObj; ClassName = 'Mock'; AutomationId = ('aid-' + $script:snapRid); IsEnabled = $true; IsOffscreen = $false; BoundingRectangle = $rect }
330
- $kidsCol = New-MockElementCollection $children
331
- $el = [pscustomobject]@{ Current = $cp; Cached = $cp; Children = $kidsCol; Rid = $script:snapRid; Parent = $null }
332
- $el | Add-Member -MemberType ScriptMethod -Name GetRuntimeId -Value { return @(77, $this.Rid) }
333
- $el | Add-Member -MemberType ScriptMethod -Name GetCachedPropertyValue -Value {
334
- param($prop)
335
- if ([object]::ReferenceEquals($prop, [System.Windows.Automation.AutomationElement]::RuntimeIdProperty)) { return @(77, $this.Rid) }
336
- return $false
337
- }
338
- # CachedChildren 必须是「属性访问」形状(真实 AutomationElement.CachedChildren 是 .NET 属性,
339
- # worker 用无括号访问),不能用 ScriptMethod:PS 5.1 对 ScriptMethod 的无括号访问返回方法
340
- # 对象本身而不调用它(实测),那会让一次性路径把方法对象当子元素推进队列。集合对象自带
341
- # .Count 与索引器,与 AutomationElementCollection 的用法一致。
342
- $el | Add-Member -MemberType NoteProperty -Name CachedChildren -Value (New-MockElementCollection $children)
343
- return $el
344
- }
345
-
346
- # 快照/扫描 mock 窗口:GetUpdatedCache 返回整树缓存根(一次性路径,带调用计数);FindAll 返回
347
- # 全部元素(find_text 扫描)。没有 GetUpdatedCache 的窗口对象(New-MockWindow)走 walker 回退。
348
- function New-MockSnapshotWindow($rootEl, [object[]]$findElements = @()) {
349
- $ae = [pscustomobject]@{ CachedRoot = $rootEl; AllElements = @($findElements); GetUpdatedCalls = 0 }
350
- $ae | Add-Member -MemberType ScriptMethod -Name GetUpdatedCache -Value {
351
- param($req)
352
- $this.GetUpdatedCalls = $this.GetUpdatedCalls + 1
353
- return $this.CachedRoot
354
- }
355
- $ae | Add-Member -MemberType ScriptMethod -Name FindAll -Value { param($scope, $cond) return $this.AllElements }
356
- return $ae
357
- }
358
-
359
- function New-MockRootWindow($hwnd, $procId, $title) {
360
- $cp = [pscustomobject]@{ NativeWindowHandle = $hwnd; ProcessId = $procId; Name = $title; ClassName = 'MockRoot' }
361
- return [pscustomobject]@{ Current = $cp }
362
- }
363
-
364
- function Reset-WorkerState {
365
- # 每个 P-01/P-02/P-09 用例节的公共底座:worker 真实的 $script:W 形状 + 空表 + 无 deadline。
366
- $script:W = Get-WorkerAssignmentValue '$script:W'
367
- $script:W.dl = [Int64]::MaxValue
368
- $script:W.lastMatch = $null
369
- $script:W.windows = @{}
370
- $script:W.winByHwnd = @{}
371
- $script:W.refs = @{}
372
- $script:W.refOrder = New-Object System.Collections.Generic.List[string]
373
- $script:W.refSeq = 0
374
- $script:W.totalRefs = 0
375
- $script:nativeLoaded = $true
376
- $script:escCache = @{}
377
- $script:snapProps = Get-WorkerAssignmentValue '$script:snapProps'
378
- $script:snapPatterns = Get-WorkerAssignmentValue '$script:snapPatterns'
379
- $script:cachedPatProps = Get-WorkerAssignmentValue '$script:cachedPatProps'
380
- $script:snapReq = $null
381
- $script:subTreeReq = $null
382
- $script:findReq = $null
383
- $script:mockRootCalls = 0
384
- $script:mockRootBefore = @()
385
- $script:mockRootAfter = @()
386
- }
387
-
388
- # type_text 用例的 [Native] 桩:worker 源码按类名引用 [Native],测试环境不编译原生助手,给一个
389
- # 纯内存实现(键盘路径返回固定计数),这样 via 缺省=keyboard 的正测也不会真发 SendInput。
390
- if (-not ('Native' -as [type])) {
391
- Add-Type -TypeDefinition 'public static class Native { public static int SendUnicode(string s) { return s.Length * 2; } public static uint KeyDownVk(int vk) { return 1u; } public static uint KeyUpVk(int vk) { return 1u; } public static System.IntPtr GetForegroundWindow() { return System.IntPtr.Zero; } public static bool IsWindowVisible(System.IntPtr h) { return true; } }'
392
- }
393
-
394
- # 真实 worker 函数(不含任何桌面调用)
395
- Assert-SourceEncoding
396
- try {
397
- Initialize-WorkerSource
398
- } catch {
399
- Write-Host ('FAIL 0.1 ' + $_.Exception.Message)
400
- exit 2
401
- }
402
- Write-Pass ('0.1 worker 静态解析通过 (' + $script:fnAst.Count + ' 个函数)')
403
-
404
- $workerDeps = @(
405
- 'Normalize-NameText', 'Get-NameSimilarity', 'Test-ExplicitFalse', 'Join-UiaCondition', 'Get-MatchScore',
406
- 'Get-LocatorFields', 'New-MatchCandidate', 'New-MatchCandidateList', 'Select-DescriptorHit', 'Find-ByDescriptor',
407
- 'Dict', 'ArgOf', 'Err', 'TruncStr', 'TickNow', 'Test-Deadline', 'RectOf', 'ControlTypeName',
408
- 'Cmd-DescriptorMatch', 'Window-Entry', 'StrArg', 'JsonOf', 'Esc', 'OneLine',
409
- 'Cmd-PrepareBatch', 'Cmd-CommitBatch', 'ListOf', 'IntArg', 'BoolArg', 'Split-Err', 'MsFrom',
410
- 'DescriptorOf', 'Read-Value', 'SupportedActionOf', 'Resolve-Ref', 'New-Ref', 'RuntimeIdKey', 'Apply-ModeArg',
411
- # GetPattern 缓存层:Read-Value 第三参路由到这里,不加载就会在 commit 用例里 CommandNotFound。
412
- 'Get-RefPattern',
413
- # 屏外元素先滚动到可见:Cmd-CommitBatch 每步动作前都会调用它,缺了就在 15.x 里整批失败。
414
- 'Ensure-InView',
415
- # verify 求值管道:Eval-Once(scroll_percent_changed 用例)/ Target-Element(其目标解析)/
416
- # Read-ScrollPercent(滚动百分比动作前读数)。
417
- 'Eval-Once', 'Target-Element', 'Read-ScrollPercent',
418
- # 快照/扫描/输入通道(P-01/P-02/P-05):一次性子树路径 + walker 回退、缓存可用性、find_text
419
- # 缓存扫描、type_text via 分支,全部走真实源码(walker/前台/根窗口由下面 mock 区顶替)。
420
- 'Build-Snapshot', 'Build-SnapshotNode', 'Snapshot-CacheRequest', 'Subtree-CacheRequest',
421
- 'New-SnapshotCacheRequest', 'Find-CacheRequest', 'Cached-PatternsOf', 'Cached-ValueOf',
422
- 'Cmd-FindText', 'Cmd-TypeText', 'Ensure-Pointer', 'Log', 'Evict-ForReservation'
423
- )
424
- try {
425
- Invoke-Expression (Get-WorkerFunctionSource $workerDeps)
426
- } catch {
427
- Write-Host ('FAIL 0.2 抽取 worker 函数失败: ' + $_.Exception.Message)
428
- exit 2
429
- }
430
- Write-Pass ('0.2 从 AST 抽取并加载 ' + $workerDeps.Count + ' 个真实函数(未执行 worker)')
431
-
432
- # ================================================================ 用例
433
- Section '1. strict 精确匹配(向后兼容基线)'
434
- $e1 = New-MockElement '会话 A 刚刚' 'Button' 'ChatRow' 'row-1' 10 10 200 24
435
- $by1 = @{ name = '会话 A 刚刚'; controlType = 'Button'; automationId = 'row-1' }
436
- $el = Invoke-Match @($e1) $by1
437
- $lm = Get-MatchInfo
438
- Assert-True '1.1 命中元素(返回元素对象,不是包装体)' ($null -ne $el) 'expected an AutomationElement'
439
- $gotName = ''
440
- if ($null -ne $el) { $gotName = [string]$el.Current.Name }
441
- Assert-Equal '1.2 返回的就是该元素本身(.Current.Name 可读)' $gotName '会话 A 刚刚'
442
- Assert-Equal '1.3 matchedBy=strict' $lm.matchedBy 'strict'
443
- Assert-Equal '1.4 ladder=strict' $lm.ladder 'strict'
444
- Assert-Bool '1.5 degraded=false(未降级)' $lm.degraded $false
445
- Assert-Score '1.6 score=1.0' $lm.score 1.0
446
- Assert-Equal '1.7 scanned=first(strict 无消歧时走 FindFirst 快路径)' $lm.scanned 'first'
447
- # F: 快路径诚实化——FindFirst 只见第一个命中,真实命中数未知。旧行为伪造 candidateCount=1,
448
- # descriptor_match 读到的就是谎言。现在钉住:count 留 0(表示"未知")且 candidateCountKnown=false,
449
- # 由只读诊断 descriptor_match 用同条件全量枚举补上真实数(见 1.10x 用例)。
450
- Assert-Int '1.8 快路径不伪造 candidateCount(未知=0)' $lm.candidateCount 0
451
- Assert-Bool '1.9 nameExact 记录为 true' $lm.nameExact $true
452
- Assert-Bool '1.10 candidateCountKnown=false(FindFirst 无法知道总数)' $lm.candidateCountKnown $false
453
- Assert-True '1.11 fastCond 保留(供 descriptor_match 重枚举)' ($null -ne $lm.fastCond) 'fastCond is null'
454
-
455
- Section '2. 动态时间戳:strict 失败 → normalizedName 命中并报告降级'
456
- $e2 = New-MockElement '会话 A 3分钟' 'Button' 'ChatRow' '' 10 10 200 24
457
- $by2 = @{ name = '会话 A 刚刚'; controlType = 'Button' }
458
- $el = Invoke-Match @($e2) $by2
459
- $lm = Get-MatchInfo
460
- Assert-True '2.1 归一化后命中' ($null -ne $el) 'expected the row whose name churned'
461
- Assert-Equal '2.2 matchedBy=normalizedName' $lm.matchedBy 'normalizedName'
462
- Assert-Equal '2.3 ladder=normalizedName' $lm.ladder 'normalizedName'
463
- Assert-Bool '2.4 degraded=true(必须报告降级)' $lm.degraded $true
464
- Assert-Score '2.5 score=0.7' $lm.score 0.7
465
- $tried = ($lm.tried -join ',')
466
- Assert-Equal '2.6 先 strict 再 normalizedName' $tried 'strict,normalizedName'
467
- Assert-Int '2.7 candidateCount=1' $lm.candidateCount 1
468
-
469
- Section '3. id-anchored:automationId 在、名称已变,仍命中'
470
- $e3 = New-MockElement '会话 B 5分钟' 'Button' 'ChatRow' 'row-42' 10 40 200 24
471
- $by3 = @{ name = '会话 B 刚刚'; controlType = 'Button'; automationId = 'row-42' }
472
- $el = Invoke-Match @($e3) $by3
473
- $lm = Get-MatchInfo
474
- Assert-True '3.1 命中' ($null -ne $el) 'expected the id-anchored row'
475
- Assert-Equal '3.2 matchedBy=id(名称不参与)' $lm.matchedBy 'id'
476
- Assert-Equal '3.3 ladder=id' $lm.ladder 'id'
477
- Assert-Bool '3.4 degraded=true' $lm.degraded $true
478
- Assert-Score '3.5 score=0.8' $lm.score 0.8
479
- $tried = ($lm.tried -join ',')
480
- Assert-Equal '3.6 tried=strict,id(在 id 级停下)' $tried 'strict,id'
481
- Assert-Int '3.7 candidateCount=1' $lm.candidateCount 1
482
-
483
- Section '4. nameExact:false → prefix 字面包含;* ? [ ] 不得当通配符'
484
- $e4 = New-MockElement '导出 [CSV] 报告' 'Button' 'Toolbar' 'btn-export' 10 70 120 24
485
- $by4 = @{ name = '[CSV]'; nameExact = $false; controlType = 'Button' }
486
- $el = Invoke-Match @($e4) $by4
487
- $lm = Get-MatchInfo
488
- Assert-True '4.1 方括号名称按字面命中' ($null -ne $el) 'expected literal substring match'
489
- Assert-Equal '4.2 matchedBy=prefix' $lm.matchedBy 'prefix'
490
- Assert-Equal '4.3 ladder=prefix' $lm.ladder 'prefix'
491
- Assert-Bool '4.4 degraded=true' $lm.degraded $true
492
- Assert-Score '4.5 score=0.55' $lm.score 0.55
493
- Assert-Bool '4.6 nameExact 记录为 false' $lm.nameExact $false
494
- $e4b = New-MockElement 'axb' 'Button' 'Toolbar' '' 10 100 120 24
495
- $by4b = @{ name = 'a*b'; nameExact = $false; controlType = 'Button' }
496
- $el = Invoke-Match @($e4b) $by4b
497
- $lm = Get-MatchInfo
498
- Assert-True '4.7 * 不是通配符(a*b 不匹配 axb)' ($null -eq $el) 'matched something, substring must be literal'
499
- Assert-Equal '4.8 未命中原因=no_match' $lm.reason 'no_match'
500
- Assert-True '4.9 仍给出最接近的候选' ($lm.candidates.Count -ge 1) ('candidates=' + $lm.candidates.Count)
501
- $cand0 = $lm.candidates[0]
502
- $candReason = Get-CandidateReason $cand0
503
- Assert-True '4.10 候选标注 name-differs' ($candReason.IndexOf('name-differs') -ge 0) ('reason=' + $candReason)
504
- $e4c = New-MockElement 'C' 'Button' 'Toolbar' '' 10 120 40 24
505
- $by4c = @{ name = '[CSV]'; nameExact = $false; controlType = 'Button' }
506
- $el = Invoke-Match @($e4c) $by4c
507
- Assert-True '4.11 方括号不是字符集([CSV] 不匹配 C)' ($null -eq $el) 'brackets were treated as a character class'
508
- $e4d = New-MockElement '导出 [CSV] 报告' 'Button' 'Toolbar' 'btn-export' 10 70 120 24
509
- $by4d = @{ name = '[CSV]'; nameExact = 'false'; controlType = 'Button' }
510
- $el = Invoke-Match @($e4d) $by4d
511
- $lm = Get-MatchInfo
512
- Assert-Equal '4.12 字符串 "false" 同样表示显式不精确' $lm.matchedBy 'prefix'
513
-
514
- Section '5. 歧义:同 id 同类型、无 nth/nearPoint → 失败并带候选'
515
- $e5a = New-MockElement '行 甲' 'Button' 'Row' 'row-x' 10 10 100 20
516
- $e5b = New-MockElement '行 乙' 'Button' 'Row' 'row-x' 10 40 100 20
517
- $by5 = @{ name = '行 丙'; controlType = 'Button'; automationId = 'row-x' }
518
- $el = Invoke-Match @($e5a, $e5b) $by5
519
- $lm = Get-MatchInfo
520
- Assert-True '5.1 未命中(不静默取第一个)' ($null -eq $el) 'ambiguous descriptor resolved to an element'
521
- Assert-Equal '5.2 reason=ambiguous' $lm.reason 'ambiguous'
522
- Assert-Equal '5.3 ambiguityAt=id' $lm.ambiguityAt 'id'
523
- Assert-True '5.4 candidates >= 2' ($lm.candidates.Count -ge 2) ('candidates=' + $lm.candidates.Count)
524
- $c0 = $lm.candidates[0]
525
- $c1 = $lm.candidates[1]
526
- Assert-Equal '5.5 候选1 name' ([string]($c0['name'])) '行 甲'
527
- Assert-Equal '5.6 候选1 automationId' ([string]($c0['automationId'])) 'row-x'
528
- Assert-Equal '5.7 候选1 controlType' ([string]($c0['controlType'])) 'Button'
529
- Assert-Int '5.8 候选1 可用 nth=1 复现' ([int]($c0['nth'])) 1
530
- Assert-Int '5.9 候选2 可用 nth=2 复现' ([int]($c1['nth'])) 2
531
- $r0 = Get-CandidateReason $c0
532
- Assert-True '5.10 候选标注 ambiguous' ($r0.IndexOf('ambiguous') -ge 0) ('reason=' + $r0)
533
- Assert-Int '5.11 candidateCount=2' $lm.candidateCount 2
534
-
535
- Section '6. nth / nearPoint 在 id 分支下仍然生效(防退化)'
536
- $by6a = @{ name = '行 丙'; controlType = 'Button'; automationId = 'row-x'; nth = 2 }
537
- $el = Invoke-Match @($e5a, $e5b) $by6a
538
- $lm = Get-MatchInfo
539
- $n6 = ''
540
- if ($null -ne $el) { $n6 = [string]$el.Current.Name }
541
- Assert-Equal '6.1 nth=2 取到第二个' $n6 '行 乙'
542
- Assert-Equal '6.2 matchedBy=nth' $lm.matchedBy 'nth'
543
- Assert-Equal '6.3 ladder=id(仍由 id 级定集)' $lm.ladder 'id'
544
- Assert-Score '6.4 score=0.75(0.8-0.05)' $lm.score 0.75
545
- $by6b = @{ name = '行 丙'; controlType = 'Button'; automationId = 'row-x'; nearPoint = @{ x = 60; y = 20 } }
546
- $el = Invoke-Match @($e5a, $e5b) $by6b
547
- $lm = Get-MatchInfo
548
- $n6b = ''
549
- if ($null -ne $el) { $n6b = [string]$el.Current.Name }
550
- Assert-Equal '6.5 nearPoint 取到最近的' $n6b '行 甲'
551
- Assert-Equal '6.6 matchedBy=nearPoint' $lm.matchedBy 'nearPoint'
552
- Assert-Equal '6.7 ladder=id' $lm.ladder 'id'
553
- Assert-Score '6.8 score=0.77(0.8-0.03)' $lm.score 0.77
554
-
555
- Section '7. 归一化函数自身的边界(逐条规则)'
556
- $just = -join @([char]0x521A, [char]0x521A)
557
- $min2 = -join @([char]0x5206, [char]0x949F)
558
- $hour = -join @([char]0x5C0F, [char]0x65F6)
559
- $dayw = -join @([char]0x5929)
560
- $lp = [char]0xFF08
561
- $rp = [char]0xFF09
562
- $itemw = -join @([char]0x9879)
563
-
564
- $s = ' 会话 A ' + $just + ' '
565
- Assert-Equal ('7.1 空白折叠+去首尾: ' + $s) (Normalize-NameText $s) '会话 A'
566
- $s = '会话 A ' + $just
567
- Assert-Equal '7.2 去尾随相对时间(刚刚)' (Normalize-NameText $s) '会话 A'
568
- $s = '会话 A 3' + $min2
569
- Assert-Equal '7.3 去尾随 N分钟' (Normalize-NameText $s) '会话 A'
570
- $s = '会话 A 2' + $hour
571
- Assert-Equal '7.4 去尾随 N小时' (Normalize-NameText $s) '会话 A'
572
- $s = '会话 A 1' + $dayw
573
- Assert-Equal '7.5 去尾随 N天' (Normalize-NameText $s) '会话 A'
574
- $s = '会话 A 14:03'
575
- Assert-Equal '7.6 去尾随时间戳 H:MM' (Normalize-NameText $s) '会话 A'
576
- $s = '会话 A 14:03:59'
577
- Assert-Equal '7.7 去尾随时间戳 H:MM:SS' (Normalize-NameText $s) '会话 A'
578
- $s = '收件箱 (3)'
579
- Assert-Equal '7.8 去尾随纯计数括号 (3)' (Normalize-NameText $s) '收件箱'
580
- $s = '收件箱 ' + $lp + '12' + $rp
581
- Assert-Equal '7.9 去尾随纯计数括号(全角)' (Normalize-NameText $s) '收件箱'
582
- $s = '设置 (2 ' + $itemw + ')'
583
- Assert-Equal '7.10 非纯计数括号不动:设置 (2 项)' (Normalize-NameText $s) $s
584
- $s = '普通标题'
585
- Assert-Equal '7.11 普通标题不动' (Normalize-NameText $s) $s
586
- $s = '设置'
587
- Assert-Equal '7.12 短标题不动' (Normalize-NameText $s) $s
588
- $s = '倒计时3' + $min2
589
- Assert-Equal '7.13 粘连的时间尾段不猜(无分隔符)' (Normalize-NameText $s) $s
590
- $s = $just + ' 会话 A'
591
- Assert-Equal '7.14 只处理尾段,头部不动' (Normalize-NameText $s) $s
592
- $s = '会话 A ' + $just + ' (2)'
593
- Assert-Equal '7.15 时间+计数组合一次归一' (Normalize-NameText $s) '会话 A'
594
- $s = $null
595
- Assert-Equal '7.16 null 归一为空串' (Normalize-NameText $s) ''
596
- $s = ''
597
- Assert-Equal '7.17 空串保持空串' (Normalize-NameText $s) ''
598
-
599
- $idem = @(
600
- ('会话 A ' + $just), ('会话 A 3' + $min2), ('收件箱 (3)'), ('设置 (2 ' + $itemw + ')'),
601
- ('倒计时3' + $min2), ('普通标题'), (' A B '), ('会话 A ' + $just + ' (2)')
602
- )
603
- $idemOk = $true
604
- $idemBad = ''
605
- foreach ($v in $idem) {
606
- $once = Normalize-NameText $v
607
- $twice = Normalize-NameText $once
608
- if (-not [string]::Equals($once, $twice, [StringComparison]::Ordinal)) { $idemOk = $false; $idemBad = $v }
609
- }
610
- Assert-True '7.18 幂等性:归一化两次等于一次' $idemOk ('not idempotent for: ' + $idemBad)
611
-
612
- Section '8. id 级歧义被更精确的 normalizedName 级化解(并如实报告)'
613
- $e8a = New-MockElement ('群聊 3' + $min2) 'Button' 'Row' 'row-z' 10 10 100 20
614
- $e8b = New-MockElement ('私聊 5' + $min2) 'Button' 'Row' 'row-z' 10 40 100 20
615
- $by8 = @{ name = ('群聊 ' + $just); controlType = 'Button'; automationId = 'row-z' }
616
- $el = Invoke-Match @($e8a, $e8b) $by8
617
- $lm = Get-MatchInfo
618
- $n8 = ''
619
- if ($null -ne $el) { $n8 = [string]$el.Current.Name }
620
- Assert-Equal ('8.1 归一化名称唯一定位到 群聊 3' + $min2) $n8 ('群聊 3' + $min2)
621
- Assert-Equal '8.2 matchedBy=normalizedName' $lm.matchedBy 'normalizedName'
622
- Assert-Equal '8.3 ambiguityAt=id(id 级歧义被记录,未静默吞掉)' $lm.ambiguityAt 'id'
623
- Assert-Bool '8.4 degraded=true' $lm.degraded $true
624
-
625
- Section '9. 老配方基线:同名多命中、无消歧 → 仍取树序第一个'
626
- $e9a = New-MockElement '复制' 'Button' 'Toolbar' 'btn-copy' 10 10 60 20
627
- $e9b = New-MockElement '复制' 'Button' 'Menu' 'btn-copy2' 10 40 60 20
628
- $by9 = @{ name = '复制'; controlType = 'Button' }
629
- $el = Invoke-Match @($e9a, $e9b) $by9
630
- $lm = Get-MatchInfo
631
- $n9 = ''
632
- $y9 = -1.0
633
- if ($null -ne $el) { $n9 = [string]$el.Current.Name; $y9 = [double]$el.Current.BoundingRectangle.Y }
634
- Assert-Equal '9.1 取到同名元素' $n9 '复制'
635
- Assert-Score '9.2 首元素 Y=10(树序第一个)' $y9 10
636
- Assert-Equal '9.3 matchedBy=strict' $lm.matchedBy 'strict'
637
- Assert-Score '9.4 score=1.0(历史配方仍是最强匹配)' $lm.score 1.0
638
- Assert-Equal '9.5 scanned=first(未枚举,与旧 FindFirst 一致)' $lm.scanned 'first'
639
-
640
- Section '10. nth 越界 = 终止失败,不静默降级到别的元素'
641
- $e10 = New-MockElement ('上行 3' + $min2) 'Button' 'Row' 'row-x' 10 10 100 20
642
- $by10 = @{ name = ('上行 ' + $just); controlType = 'Button'; automationId = 'row-x'; nth = 3 }
643
- $el = Invoke-Match @($e10) $by10
644
- $lm = Get-MatchInfo
645
- Assert-True '10.1 未命中(不拿第一个顶替)' ($null -eq $el) 'nth out of range silently resolved'
646
- Assert-Equal '10.2 reason=nth_out_of_range' $lm.reason 'nth_out_of_range'
647
- Assert-True '10.3 仍给出候选' ($lm.candidates.Count -ge 1) ('candidates=' + $lm.candidates.Count)
648
- $c10 = $lm.candidates[0]
649
- Assert-Int '10.4 候选标出 nth=1' ([int]($c10['nth'])) 1
650
- $r10 = Get-CandidateReason $c10
651
- Assert-True '10.5 候选原因含 nth_out_of_range' ($r10.IndexOf('nth_out_of_range') -ge 0) ('reason=' + $r10)
652
-
653
- Section '11. 命令注册与状态槽(静态契约,不执行 worker)'
654
- $handlers = Get-WorkerAssignmentValue '$handlers'
655
- $budgets = Get-WorkerAssignmentValue '$defaultBudget'
656
- $wInit = Get-WorkerAssignmentValue '$script:W'
657
- $hasHandler = ($null -ne $handlers -and $handlers.ContainsKey('descriptor_match'))
658
- Assert-True '11.1 $handlers 注册了 descriptor_match' $hasHandler 'no descriptor_match handler'
659
- $hval = ''
660
- if ($hasHandler) { $hval = [string]$handlers['descriptor_match'] }
661
- Assert-Equal '11.2 descriptor_match → Cmd-DescriptorMatch' $hval 'Cmd-DescriptorMatch'
662
- Assert-True '11.3 Cmd-DescriptorMatch 函数存在' ($script:fnAst.ContainsKey('Cmd-DescriptorMatch')) 'function missing'
663
- $hasBudget = ($null -ne $budgets -and $budgets.ContainsKey('descriptor_match'))
664
- Assert-True '11.4 $defaultBudget 配了 descriptor_match' $hasBudget 'no budget'
665
- $bval = -1
666
- if ($hasBudget) { $bval = [int]$budgets['descriptor_match'] }
667
- Assert-True '11.5 budget 在 (0,12000] 区间' ($bval -gt 0 -and $bval -le 12000) ('budget=' + $bval)
668
- Assert-True '11.6 $script:W 有 lastMatch 槽' ($null -ne $wInit -and $wInit.ContainsKey('lastMatch')) 'lastMatch missing'
669
- $missing = New-Object System.Collections.Generic.List[string]
670
- foreach ($k in @($handlers.Keys)) {
671
- $fn = [string]$handlers[$k]
672
- if (-not $script:fnAst.ContainsKey($fn)) { $missing.Add($k + '->' + $fn) | Out-Null }
673
- }
674
- Assert-True '11.7 所有 handler 都指向真实存在的函数' ($missing.Count -eq 0) ('broken: ' + ($missing -join ', '))
675
- $missingTier = New-Object System.Collections.Generic.List[string]
676
- foreach ($f in $workerDeps) { if (-not $script:fnAst.ContainsKey($f)) { $missingTier.Add($f) | Out-Null } }
677
- Assert-True '11.8 阶梯相关函数齐全' ($missingTier.Count -eq 0) ('missing: ' + ($missingTier -join ', '))
678
-
679
- Section '12. 只给结构条件的描述符(无 name)保持旧行为'
680
- $e12 = New-MockElement '会话 C 刚刚' 'Button' 'ChatRow' 'row-77' 10 10 200 24
681
- $by12 = @{ controlType = 'Button'; automationId = 'row-77' }
682
- $el = Invoke-Match @($e12) $by12
683
- $lm = Get-MatchInfo
684
- $n12 = ''
685
- if ($null -ne $el) { $n12 = [string]$el.Current.Name }
686
- Assert-Equal '12.1 结构条件命中' $n12 '会话 C 刚刚'
687
- Assert-Equal '12.2 matchedBy=strict' $lm.matchedBy 'strict'
688
- Assert-Bool '12.3 degraded=false' $lm.degraded $false
689
- Assert-Score '12.4 score=1.0' $lm.score 1.0
690
- $tried = ($lm.tried -join ',')
691
- Assert-Equal '12.5 无 name 时不跑多余层级' $tried 'strict'
692
-
693
- Section '13. descriptor_match:旁路信息透出 + JSON 契约 + 只读'
694
- $script:escCache = @{}
695
- $script:W.refs = @{}
696
- $script:W.windows = @{}
697
- $entry13 = @{ id = 'w1'; hwnd = 4200; revision = 1; class = 'ChatWnd'; pid = 4242; snapshots = @() }
698
- $script:W.windows['w1'] = $entry13
699
- $e13 = New-MockElement '会话 D 刚刚' 'Button' 'ChatRow' 'row-9' 10 10 200 24
700
- $script:mockAe = New-MockWindow @($e13)
701
- $args13 = @{ windowId = 'w1'; by = @{ name = '会话 D 刚刚'; controlType = 'Button' } }
702
- $res13 = Cmd-DescriptorMatch $args13
703
- Assert-Bool '13.1 found=true' $res13['found'] $true
704
- Assert-Equal '13.2 matchedBy=strict' ([string]($res13['matchedBy'])) 'strict'
705
- Assert-Score '13.3 score=1.0' ([double]($res13['score'])) 1.0
706
- Assert-Bool '13.4 degraded=false' $res13['degraded'] $false
707
- $elem13 = $res13['element']
708
- Assert-Equal '13.5 element.name' ([string]($elem13['name'])) '会话 D 刚刚'
709
- Assert-Equal '13.6 element.controlType' ([string]($elem13['controlType'])) 'Button'
710
- Assert-Equal '13.7 element.automationId' ([string]($elem13['automationId'])) 'row-9'
711
- Assert-True '13.8 成功时 candidates 为空' ((Get-ItemCount $res13['candidates']) -eq 0) 'candidates not empty'
712
- $json13 = JsonOf $res13
713
- Write-Host (' JSON: ' + $json13)
714
- $okJson13 = $true
715
- $obj13 = $null
716
- try { $obj13 = ConvertFrom-Json $json13 } catch { $okJson13 = $false }
717
- Assert-True '13.9 JsonOf 产出可解析 JSON' $okJson13 $json13
718
- if ($okJson13) {
719
- Assert-Bool '13.10 JSON found=true' $obj13.found $true
720
- Assert-Equal '13.11 JSON matchedBy' ([string]$obj13.matchedBy) 'strict'
721
- Assert-Equal '13.12 JSON element.name' ([string]$obj13.element.name) '会话 D 刚刚'
722
- }
723
- Assert-Int '13.13 只读:未铸造 ref' ($script:W.refs.Count) 0
724
- Assert-Int '13.14 只读:未改窗口 revision' ([int]$entry13.revision) 1
725
- $e13b = New-MockElement '行 甲' 'Button' 'Row' 'row-x' 10 10 100 20
726
- $e13c = New-MockElement '行 乙' 'Button' 'Row' 'row-x' 10 40 100 20
727
- $script:mockAe = New-MockWindow @($e13b, $e13c)
728
- $args13b = @{ windowId = 'w1'; by = @{ name = '行 丙'; controlType = 'Button'; automationId = 'row-x' } }
729
- $res13b = Cmd-DescriptorMatch $args13b
730
- Assert-Bool '13.15 失败时 found=false' $res13b['found'] $false
731
- Assert-Equal '13.16 失败原因=ambiguous' ([string]($res13b['reason'])) 'ambiguous'
732
- Assert-True '13.17 失败仍带候选' ((Get-ItemCount $res13b['candidates']) -ge 2) ('candidates=' + (Get-ItemCount $res13b['candidates']))
733
- $json13b = JsonOf $res13b
734
- $obj13b = ConvertFrom-Json $json13b
735
- Assert-True '13.18 失败 JSON 省略 matchedBy/ladder' ($null -eq $obj13b.matchedBy -and $null -eq $obj13b.ladder) $json13b
736
-
737
- Section '14. strict 级的老消歧(nth/nearPoint)重构后仍按原语义工作'
738
- $e14a = New-MockElement '复制' 'Button' 'Toolbar' 'btn-copy' 10 10 60 20
739
- $e14b = New-MockElement '复制' 'Button' 'Toolbar' 'btn-copy2' 10 40 60 20
740
- $by14a = @{ name = '复制'; controlType = 'Button'; nth = 2 }
741
- $el = Invoke-Match @($e14a, $e14b) $by14a
742
- $lm = Get-MatchInfo
743
- $y14 = -1.0
744
- if ($null -ne $el) { $y14 = [double]$el.Current.BoundingRectangle.Y }
745
- Assert-Score '14.1 strict+nth=2 取第二个(Y=40)' $y14 40
746
- Assert-Equal '14.2 matchedBy=nth' $lm.matchedBy 'nth'
747
- Assert-Equal '14.3 ladder=strict(集合仍由精确条件定)' $lm.ladder 'strict'
748
- Assert-Score '14.4 score=0.95(1.0-0.05)' $lm.score 0.95
749
- Assert-Int '14.5 candidateCount=2' $lm.candidateCount 2
750
- $by14b = @{ name = '复制'; controlType = 'Button'; nearPoint = @{ x = 40; y = 15 } }
751
- $el = Invoke-Match @($e14a, $e14b) $by14b
752
- $lm = Get-MatchInfo
753
- $y14b = -1.0
754
- if ($null -ne $el) { $y14b = [double]$el.Current.BoundingRectangle.Y }
755
- Assert-Score '14.6 strict+nearPoint 取最近的(Y=10)' $y14b 10
756
- Assert-Equal '14.7 matchedBy=nearPoint' $lm.matchedBy 'nearPoint'
757
- Assert-Equal '14.8 ladder=strict' $lm.ladder 'strict'
758
- Assert-Score '14.9 score=0.97(1.0-0.03)' $lm.score 0.97
759
-
760
- Section '15. prepare/commit 逐步结果携带定位置信度(ref 分支不带)'
761
- # 以 worker 真实的 $script:W 初始化做底(actionNames/stats/refs 形状都对),再补窗口与引用表。
762
- $script:W = Get-WorkerAssignmentValue '$script:W'
763
- $script:W.dl = [Int64]::MaxValue
764
- $script:W.lastMatch = $null
765
- $script:W.windows = @{}
766
- $script:W.winByHwnd = @{}
767
- $script:W.refs = @{}
768
- $script:W.refOrder = New-Object System.Collections.Generic.List[string]
769
- $script:W.refSeq = 0
770
- $script:W.totalRefs = 0
771
- $script:escCache = @{}
772
- $entry15 = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 3; snapshots = (New-Object System.Collections.Generic.List[object]) }
773
- $script:W.windows['w1'] = $entry15
774
- $e15ok = New-MockElement '确定' 'Button' 'Dialog' 'btn-ok' 10 10 60 20
775
- $e15row = New-MockElement '会话 E 3分钟' 'Button' 'ChatRow' '' 10 40 200 24
776
- $script:mockAe = New-MockWindow @($e15ok, $e15row)
777
- $script:W.refs['e9'] = @{
778
- ref = 'e9'
779
- windowId = 'w1'
780
- revision = 3
781
- ae = $e15ok
782
- runtimeId = '4242,1'
783
- controlType = 'Button'
784
- name = '确定'
785
- className = 'Dialog'
786
- automationId = 'btn-ok'
787
- patterns = @('Invoke')
788
- enabled = $true
789
- isOffscreen = $false
790
- rect = @{ x = 10; y = 10; w = 60; h = 20 }
791
- depth = 2
792
- rebound = $false
793
- }
794
- $script:W.refOrder.Add('e9') | Out-Null
795
- $step15a = @{ by = @{ name = '确定'; controlType = 'Button'; automationId = 'btn-ok' }; action = 'invoke' }
796
- $step15b = @{ by = @{ name = '会话 E 刚刚'; controlType = 'Button' }; action = 'invoke' }
797
- $step15c = @{ ref = 'e9'; action = 'invoke' }
798
- $prep15 = Cmd-PrepareBatch @{ windowId = 'w1'; steps = @($step15a, $step15b, $step15c) }
799
- Assert-Bool '15.1 prepare 全部解析成功' $prep15['allResolved'] $true
800
- $d15 = $prep15['descriptors']
801
- Assert-Int '15.2 prepare 返回 3 条描述符' (Get-ItemCount $d15) 3
802
- $d0 = $d15[0]
803
- $d1 = $d15[1]
804
- $d2 = $d15[2]
805
- Assert-Equal '15.3 strict 步 matchedBy=strict' ([string]($d0['matchedBy'])) 'strict'
806
- Assert-Equal '15.4 strict 步 ladder=strict' ([string]($d0['ladder'])) 'strict'
807
- Assert-Score '15.5 strict 步 score=1.0' ([double]($d0['score'])) 1.0
808
- Assert-Bool '15.6 strict 步 degraded=false' $d0['degraded'] $false
809
- Assert-Equal '15.7 归一化步 matchedBy=normalizedName' ([string]($d1['matchedBy'])) 'normalizedName'
810
- Assert-Equal '15.8 归一化步 ladder=normalizedName' ([string]($d1['ladder'])) 'normalizedName'
811
- Assert-Score '15.9 归一化步 score=0.7' ([double]($d1['score'])) 0.7
812
- Assert-Bool '15.10 归一化步 degraded=true' $d1['degraded'] $true
813
- Assert-True '15.11 ref 步没有 matchedBy 字段' (-not $d2.Contains('matchedBy')) 'ref step carries matchedBy'
814
- Assert-True '15.12 ref 步没有 ladder/score/degraded 字段' (-not ($d2.Contains('ladder') -or $d2.Contains('score') -or $d2.Contains('degraded'))) 'ref step carries locator fields'
815
- $o15 = ConvertFrom-Json (JsonOf $prep15)
816
- $j0 = $o15.descriptors[0]
817
- $j1 = $o15.descriptors[1]
818
- $j2 = $o15.descriptors[2]
819
- Assert-Bool '15.13 JSON strict 步 degraded=false' $j0.degraded $false
820
- Assert-Equal '15.14 JSON 归一化步 matchedBy' ([string]$j1.matchedBy) 'normalizedName'
821
- Assert-True '15.15 JSON ref 步无 matchedBy' ($null -eq $j2.matchedBy) 'ref step has matchedBy in JSON'
822
- Write-Host (' prepare[1] normalizedName: ' + (JsonOf $d1))
823
- Write-Host (' prepare[2] ref (无置信度): ' + (JsonOf $d2))
824
- $comm15 = Cmd-CommitBatch @{ windowId = 'w1'; revision = 3; steps = @($step15a, $step15b, $step15c) }
825
- $r15 = $comm15['results']
826
- Assert-Int '15.16 commit 执行了 3 步' ([int]$comm15['performedCount']) 3
827
- Assert-Bool '15.17 commit batchOk=true' $comm15['batchOk'] $true
828
- $r0 = $r15[0]
829
- $r1 = $r15[1]
830
- $r2 = $r15[2]
831
- Assert-Equal '15.18 commit strict 步 matchedBy=strict' ([string]($r0['matchedBy'])) 'strict'
832
- Assert-Bool '15.19 commit strict 步 degraded=false' $r0['degraded'] $false
833
- Assert-Equal '15.20 commit 归一化步 matchedBy=normalizedName' ([string]($r1['matchedBy'])) 'normalizedName'
834
- Assert-Bool '15.21 commit 归一化步 degraded=true' $r1['degraded'] $true
835
- Assert-Score '15.22 commit 归一化步 score=0.7' ([double]($r1['score'])) 0.7
836
- Assert-True '15.23 commit ref 步没有 matchedBy 字段' (-not $r2.Contains('matchedBy')) 'ref step carries matchedBy'
837
- $st15 = (@($r15 | ForEach-Object { [string]$_['status'] }) -join ',')
838
- Assert-Equal '15.24 commit 三步都 passed' $st15 'passed,passed,passed'
839
- $o15c = ConvertFrom-Json (JsonOf $comm15)
840
- $jc2 = $o15c.results[2]
841
- Assert-True '15.25 JSON commit ref 步无 matchedBy' ($null -eq $jc2.matchedBy) 'ref step has matchedBy in commit JSON'
842
- Write-Host (' commit[1] normalizedName : ' + (JsonOf $r1))
843
- Write-Host (' commit[2] ref (无置信度) : ' + (JsonOf $r2))
844
-
845
- Section '16. Eval-Once scroll_percent_changed:滚动百分比的确定性判据(命中/未命中两例)'
846
- # mock 元素带 ScrollPattern,Current.VerticalScrollPercent 走 ScriptProperty 读
847
- # $script:mockScrollPct——同一个"元素"在动作前后能给出不同读数,才能测"滚了但列表没动"。
848
- # GetPattern mock 只认带 ScrollPattern 属性的元素,其余保持返回 $null(不影响已跑完的用例)。
849
- $script:mockScrollPct = 20.0
850
- $scrollCur16 = New-Object PSObject
851
- $scrollCur16 | Add-Member -MemberType ScriptProperty -Name VerticalScrollPercent -Value { return [double]$script:mockScrollPct }
852
- $scrollPat16 = New-Object PSObject
853
- $scrollPat16 | Add-Member -MemberType NoteProperty -Name Current -Value $scrollCur16
854
- function GetPattern($el, $name) {
855
- if ($name -eq 'Scroll' -and $null -ne $el.PSObject.Properties['ScrollPattern']) { return $el.ScrollPattern }
856
- return $null
857
- }
858
- $el16 = New-MockElement '列表' 'List' 'ListBox' 'list-1' 10 10 300 400
859
- $el16 | Add-Member -MemberType NoteProperty -Name ScrollPattern -Value $scrollPat16
860
- # 复用第 15 节搭好的 $script:W(窗口 w1 revision=3):Resolve-Ref 要求 ref.revision 与窗口一致。
861
- $script:W.refs['s1'] = @{
862
- ref = 's1'
863
- windowId = 'w1'
864
- revision = 3
865
- ae = $el16
866
- runtimeId = '4242,16'
867
- controlType = 'List'
868
- name = '列表'
869
- className = 'ListBox'
870
- automationId = 'list-1'
871
- patterns = @('Scroll')
872
- enabled = $true
873
- isOffscreen = $false
874
- rect = @{ x = 10; y = 10; w = 300; h = 400 }
875
- depth = 1
876
- rebound = $false
877
- patCache = @{}
878
- }
879
- $entry16 = $script:W.windows['w1']
880
- $cond16 = @{ type = 'scroll_percent_changed'; ref = 's1'; expect = 5 }
881
- # 命中:动作前 20%,动作后 40%——差值 20 ≥ expect 5。
882
- $before16 = Read-ScrollPercent $script:W.refs['s1']
883
- Assert-Equal '16.1 动作前滚动百分比读数=20' $before16 20
884
- $script:mockScrollPct = 40.0
885
- $r16a = Eval-Once 'scroll_percent_changed' $entry16 $cond16 $null $null $before16
886
- Assert-Bool '16.2 命中(差值 20 ≥ expect 5)' ([bool]$r16a['matched']) $true
887
- Assert-Equal '16.3 observed=percent=40' ([string]$r16a['observed']) 'percent=40'
888
- Assert-Equal '16.4 before=percent=20' ([string]$r16a['before']) 'percent=20'
889
- # 未命中:动作前 40%,"滚了"但读数没动——差值 0 < expect 5,这就是要拦的无效滚动。
890
- $script:mockScrollPct = 40.0
891
- $before16b = Read-ScrollPercent $script:W.refs['s1']
892
- Assert-Equal '16.5 动作前滚动百分比读数=40' $before16b 40
893
- $r16b = Eval-Once 'scroll_percent_changed' $entry16 $cond16 $null $null $before16b
894
- Assert-Bool '16.6 未命中(差值 0 < expect 5)' ([bool]$r16b['matched']) $false
895
- Assert-Equal '16.7 observed=percent=40' ([string]$r16b['observed']) 'percent=40'
896
-
897
-
898
-
899
-
900
- Section '17. snapshot 快照:一次性子树(GetUpdatedCache)与 walker 回退,契约不变(P-01)'
901
- Reset-WorkerState
902
- $g17 = New-MockSnapElement '孙' 'Button' @()
903
- $c17a = New-MockSnapElement '子甲' 'Button' @($g17)
904
- $c17b = New-MockSnapElement '子乙' 'Edit' @()
905
- $root17 = New-MockSnapElement '根窗' 'Window' @($c17a, $c17b)
906
- $entry17 = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
907
- $script:W.windows['w1'] = $entry17
908
- $script:mockAe = New-MockSnapshotWindow $root17
909
- $snap17 = Build-Snapshot $entry17 @{ windowId = 'w1' }
910
- Assert-Int '17.1 一次性路径节点数=整树 4 节点' ([int]$snap17['nodeCount']) 4
911
- Assert-Int '17.2 visited=4' ([int]$snap17['visited']) 4
912
- Assert-Bool '17.3 truncated=false' ([bool]$snap17['truncated']) $false
913
- Assert-Int '17.4 revision 已 bump' ([int]$snap17['revision']) 2
914
- Assert-True '17.5 无 partialReason' (-not $snap17.Contains('partialReason')) ('partialReason=' + [string]$snap17['partialReason'])
915
- Assert-Int '17.6 ref 登记数=节点数' ([int]$script:W.refs.Count) 4
916
- Assert-Int '17.7 refOrder 登记数=节点数' ([int]$script:W.refOrder.Count) 4
917
- Assert-True '17.8 GetUpdatedCache 恰好调用一次(一次性路径生效)' ([int]$script:mockAe.GetUpdatedCalls -eq 1) ('calls=' + $script:mockAe.GetUpdatedCalls)
918
- $n17 = $snap17['nodes']
919
- Assert-Equal '17.9 树序首节点=根' ([string]$n17[0]['name']) '根窗'
920
- Assert-Equal '17.10 首节点 ref=e1' ([string]$n17[0]['ref']) 'e1'
921
- Assert-Equal '17.11 第二节点=子甲' ([string]$n17[1]['name']) '子甲'
922
- Assert-Int '17.12 子甲 depth=1' ([int]$n17[1]['depth']) 1
923
- Assert-Equal '17.13 第三节点=孙' ([string]$n17[2]['name']) '孙'
924
- Assert-Int '17.14 孙 depth=2' ([int]$n17[2]['depth']) 2
925
- Assert-Equal '17.15 第四节点=子乙' ([string]$n17[3]['name']) '子乙'
926
- Assert-Equal '17.16 节点 patterns 来自 mock' ((@($n17[0]['patterns']) -join ',')) 'Invoke'
927
- Assert-Equal '17.17 ref 的 runtimeId 来自缓存' ([string]$script:W.refs['e2']['runtimeId']) '77,102'
928
- Assert-True '17.18 节点字段齐全' (($n17[1].Contains('controlType') -and $n17[1].Contains('automationId') -and $n17[1].Contains('enabled') -and $n17[1].Contains('isOffscreen') -and $n17[1].Contains('rect'))) 'missing node fields'
929
-
930
- # maxNodes 截断:emit 层契约不变(truncated + partialReason['maxNodes'],ref 只铸已产出节点)。
931
- Reset-WorkerState
932
- $entry17b = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
933
- $script:W.windows['w1'] = $entry17b
934
- $script:mockAe = New-MockSnapshotWindow $root17
935
- $snap17b = Build-Snapshot $entry17b @{ windowId = 'w1'; maxNodes = 2 }
936
- Assert-Int '17.19 maxNodes=2 截断到 2 节点' ([int]$snap17b['nodeCount']) 2
937
- Assert-Bool '17.20 truncated=true' ([bool]$snap17b['truncated']) $true
938
- Assert-True '17.21 partialReason 含 maxNodes' (([string]$snap17b['partialReason']).IndexOf('maxNodes') -ge 0) ('partialReason=' + [string]$snap17b['partialReason'])
939
- Assert-Int '17.22 ref 只铸已产出节点' ([int]$script:W.refs.Count) 2
940
-
941
- # maxDepth 截断:一次性路径在导航计数阶段剪枝,标记同 walker。
942
- Reset-WorkerState
943
- $entry17c = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
944
- $script:W.windows['w1'] = $entry17c
945
- $script:mockAe = New-MockSnapshotWindow $root17
946
- $snap17c = Build-Snapshot $entry17c @{ windowId = 'w1'; maxDepth = 1 }
947
- Assert-Int '17.23 maxDepth=1 收 3 节点(depth 0..1,孙不入树)' ([int]$snap17c['nodeCount']) 3
948
- Assert-Bool '17.24 truncated=true' ([bool]$snap17c['truncated']) $true
949
- Assert-True '17.25 partialReason 含 maxDepth' (([string]$snap17c['partialReason']).IndexOf('maxDepth') -ge 0) ('partialReason=' + [string]$snap17c['partialReason'])
950
- $n17c = $snap17c['nodes']
951
- Assert-True '17.23b 孙(depth=2)未入树' (($n17c | Where-Object { [string]$_['name'] -eq '孙' } | Measure-Object).Count -eq 0) 'grandchild emitted'
952
-
953
- # emit 过滤在内存层照旧(filter 只减 emit,不减 visited)。
954
- Reset-WorkerState
955
- $entry17d = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
956
- $script:W.windows['w1'] = $entry17d
957
- $script:mockAe = New-MockSnapshotWindow $root17
958
- $snap17d = Build-Snapshot $entry17d @{ windowId = 'w1'; filter = @{ controlType = 'Button' } }
959
- Assert-Int '17.26 filter=Button 只 emit 两个 Button' ([int]$snap17d['nodeCount']) 2
960
- Assert-Int '17.27 visited 不受 filter 影响' ([int]$snap17d['visited']) 4
961
-
962
- # walker 回退路径:窗口对象没有 GetUpdatedCache(mock 元素调用抛错)→ 沿用 per-child walker,
963
- # 契约一致。root17 本身就是快照 mock 元素形状(Current/Cached/Children 齐全,无 GetUpdatedCache)。
964
- Reset-WorkerState
965
- $entry17e = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
966
- $script:W.windows['w1'] = $entry17e
967
- $script:mockAe = $root17
968
- $snap17e = Build-Snapshot $entry17e @{ windowId = 'w1' }
969
- Assert-Int '17.28 回退路径节点数=4' ([int]$snap17e['nodeCount']) 4
970
- Assert-Bool '17.29 回退路径 truncated=false' ([bool]$snap17e['truncated']) $false
971
- Assert-Int '17.30 回退路径 ref 登记数=4' ([int]$script:W.refs.Count) 4
972
- Assert-True '17.31 回退路径无 childProviderError' (([string]$snap17e['partialReason']).IndexOf('childProviderError') -lt 0) ('partialReason=' + [string]$snap17e['partialReason'])
973
-
974
- Section '18. find_text:缓存扫描契约(命中/ref/nth/by/matchedTotal/truncated)(P-02)'
975
- Reset-WorkerState
976
- $ft1 = New-MockSnapElement '保存' 'Button' @()
977
- $ft2 = New-MockSnapElement '保存' 'Button' @()
978
- $ft3 = New-MockSnapElement '保存的草稿' 'Text' @()
979
- $root18 = New-MockSnapElement '' 'Window' @($ft1, $ft2, $ft3)
980
- $entry18 = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 5; snapshots = (New-Object System.Collections.Generic.List[object]) }
981
- $script:W.windows['w1'] = $entry18
982
- $script:mockAe = New-MockSnapshotWindow $root18 @($root18, $ft1, $ft2, $ft3)
983
- $ft = Cmd-FindText @{ windowId = 'w1'; text = '保存' }
984
- $ftMatches = $ft['matches']
985
- Assert-Int '18.1 count=3' ([int]$ft['count']) 3
986
- Assert-Int '18.2 matchedTotal=3(诚实总数)' ([int]$ft['matchedTotal']) 3
987
- Assert-Int '18.3 scanned=4(含根)' ([int]$ft['scanned']) 4
988
- Assert-Bool '18.4 truncated=false' ([bool]$ft['truncated']) $false
989
- Assert-True '18.5 首项带 ref' ($null -ne $ftMatches[0]['ref']) 'first match has no ref'
990
- Assert-Equal '18.6 首项 by.controlType=Button' ([string]$ftMatches[0]['by']['controlType']) 'Button'
991
- Assert-Int '18.7 次同名项 nth=2' ([int]$ftMatches[1]['nth']) 2
992
- Assert-True '18.8 by 携带 nth=2(回放可寻址)' ([int]$ftMatches[1]['by']['nth'] -eq 2) 'by.nth missing'
993
- Assert-Int '18.9 首项 center.x=55(rect 中心)' ([int]$ftMatches[0]['center']['x']) 55
994
- Assert-True '18.10 结果带 ms(采集耗时)' ([int]$ft['ms'] -ge 0) ('ms=' + [string]$ft['ms'])
995
- $ft1b = Cmd-FindText @{ windowId = 'w1'; text = '保存'; max = 1 }
996
- Assert-Int '18.11 max=1 只返回 1 个' ([int]$ft1b['count']) 1
997
- Assert-Bool '18.12 truncated=true' ([bool]$ft1b['truncated']) $true
998
- Assert-Int '18.13 matchedTotal 仍=3' ([int]$ft1b['matchedTotal']) 3
999
- $ft0 = Cmd-FindText @{ windowId = 'w1'; text = '不存在的词' }
1000
- Assert-Int '18.14 无命中 count=0' ([int]$ft0['count']) 0
1001
- Assert-Int '18.15 无命中 matchedTotal=0' ([int]$ft0['matchedTotal']) 0
1002
- Assert-Int '18.16 ref 表登记=3+1(max 截断的不铸)' ([int]$script:W.refs.Count) 4
1003
-
1004
- Section '19. commit_batch:批次前后顶层窗口 diff(newWindows 两态 + 指示层 pid 排除)(P-09)'
1005
- Reset-WorkerState
1006
- $entry19 = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 3; snapshots = (New-Object System.Collections.Generic.List[object]) }
1007
- $script:W.windows['w1'] = $entry19
1008
- $el19 = New-MockElement '确定' 'Button' 'Dialog' 'btn-ok' 10 10 60 20
1009
- $script:W.refs['e9'] = @{
1010
- ref = 'e9'
1011
- windowId = 'w1'
1012
- revision = 3
1013
- ae = $el19
1014
- runtimeId = '4242,1'
1015
- controlType = 'Button'
1016
- name = '确定'
1017
- className = 'Dialog'
1018
- automationId = 'btn-ok'
1019
- patterns = @('Invoke')
1020
- enabled = $true
1021
- isOffscreen = $false
1022
- rect = @{ x = 10; y = 10; w = 60; h = 20 }
1023
- depth = 2
1024
- rebound = $false
1025
- patCache = @{}
1026
- }
1027
- $script:W.refOrder.Add('e9') | Out-Null
1028
- $step19 = @{ ref = 'e9'; action = 'invoke' }
1029
- $m19a = New-MockRootWindow 4200 4242 '目标窗'
1030
- $m19b = New-MockRootWindow 9999 4243 '弹出对话框'
1031
- # RootWindows mock 按调用奇偶切 before/after:commit A 前后同集(无新窗口);commit B 的 after
1032
- # 多出 9999(构造「新窗口」)。
1033
- $script:mockRootBefore = @($m19a)
1034
- $script:mockRootAfter = @($m19a)
1035
- $comm19a = Cmd-CommitBatch @{ windowId = 'w1'; revision = 3; steps = @($step19) }
1036
- Assert-Bool '19.1 无新窗口时结果无 newWindows 键' (-not $comm19a.Contains('newWindows')) $true
1037
- $script:mockRootAfter = @($m19a, $m19b)
1038
- $comm19b = Cmd-CommitBatch @{ windowId = 'w1'; revision = 3; steps = @($step19) }
1039
- Assert-Bool '19.2 有新窗口时带 newWindows 键' $comm19b.Contains('newWindows') $true
1040
- $nw19 = $comm19b['newWindows']
1041
- Assert-Int '19.3 newWindows 一条' ([int]$nw19.Count) 1
1042
- Assert-Equal '19.4 新窗口标题' ([string]$nw19[0]['title']) '弹出对话框'
1043
- Assert-Int '19.5 新窗口 pid' ([int]$nw19[0]['pid']) 4243
1044
- Assert-Int '19.6 新窗口 hwnd' ([int]$nw19[0]['hwnd']) 9999
1045
- $script:mockRootAfter = @($m19a, $m19b)
1046
- $comm19c = Cmd-CommitBatch @{ windowId = 'w1'; revision = 3; steps = @($step19); indicatorPid = 4243 }
1047
- Assert-Bool '19.7 指示层 pid 被排除(无 newWindows 键)' (-not $comm19c.Contains('newWindows')) $true
1048
- $json19 = JsonOf $comm19b
1049
- $obj19 = ConvertFrom-Json $json19
1050
- Assert-Equal '19.8 JSON newWindows[0].title' ([string]$obj19.newWindows[0].title) '弹出对话框'
1051
-
1052
- Section '20. type_text:via 非法值负测(不触桌面)(P-05)'
1053
- Reset-WorkerState
1054
- $code20 = ''
1055
- try { Cmd-TypeText @{ text = 'hi'; via = 'mouse' } } catch { $c20, $m20 = Split-Err $_; $code20 = $c20 }
1056
- Assert-Equal '20.1 via=mouse 报 bad_arg' $code20 'bad_arg'
1057
- $code20 = ''
1058
- try { $r20 = Cmd-TypeText @{ text = 'hi' } } catch { $code20 = 'threw' }
1059
- Assert-Equal '20.2 缺省 via=keyboard 正常([Native] 桩,不真发输入)' $code20 ''
1060
- Assert-Int '20.3 键盘路径 chars=2' ([int]$r20['chars']) 2
1061
-
1062
- # ================================================================ 汇总
1063
- $total = $script:pass + $script:fail
1064
- Write-Host ''
1065
- Write-Host ('==== ' + $script:pass + '/' + $total + ' passed, ' + $script:fail + ' failed ====')
1066
- if ($script:fail -gt 0) {
1067
- Write-Host '失败明细:'
1068
- foreach ($f in $script:failures) { Write-Host (' - ' + $f) }
1069
- exit 1
1070
- }
1071
- exit 0
1
+ # scripts/regression-worker.ps1 -- 元素定位阶梯(match ladder)回归测试
2
+ #
3
+ # 跑法:
4
+ # powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\regression-worker.ps1
5
+ # 退出码:
6
+ # 0 = 全部通过, 1 = 有断言失败, 2 = 环境/源码问题(worker 解析失败、文件缺失)
7
+ #
8
+ # 为什么不能 dot-source 整个 worker:
9
+ # uia-worker.ps1 末尾是 [Console]::In.ReadLine() 常驻循环, dot-source 会直接把测试挂死。
10
+ # 这里只用 Parser::ParseFile 做静态解析, 然后按函数名把「函数定义的源码文本」抽出来,
11
+ # 在当前作用域里 Invoke-Expression 重新定义。参数表、注释、闭包都原样保留
12
+ # (注意: FunctionDefinitionAst.Body.GetScriptBlock() 会丢掉 param 块, 不能用)。
13
+ # 真正会碰桌面的那一层(窗口句柄 → AutomationElement)用同名 mock 顶替, 其余依赖函数
14
+ # (Dict / ArgOf / Err / TruncStr / TickNow / Test-Deadline / RectOf / ControlTypeName)
15
+ # 按真实源码加载, 所以测的是 worker 里的真实现。
16
+ #
17
+ # 无副作用: 不 SendInput、不点桌面、不写注册表、不启动常驻 worker、不读任何凭据。
18
+ #
19
+ # 编码须知: 本文件含中文测试数据, 必须保存为 UTF-8 **带 BOM**。
20
+ # Windows PowerShell 5.1 对无 BOM 的 .ps1 按 ANSI 代码页解析, 中文会变乱码且测试会静默错位。
21
+ # 下面的 Assert-SourceEncoding 会在启动时自检并明确报错。
22
+
23
+ $ErrorActionPreference = 'Stop'
24
+ Set-StrictMode -Off
25
+
26
+ Add-Type -AssemblyName UIAutomationClient
27
+ Add-Type -AssemblyName UIAutomationTypes
28
+
29
+ $script:pass = 0
30
+ $script:fail = 0
31
+ $script:failures = New-Object System.Collections.Generic.List[string]
32
+
33
+ function Write-Pass([string]$name) {
34
+ $script:pass += 1
35
+ Write-Host ('PASS ' + $name)
36
+ }
37
+ function Write-Fail([string]$name, [string]$why) {
38
+ $script:fail += 1
39
+ $script:failures.Add($name + ' :: ' + $why) | Out-Null
40
+ Write-Host ('FAIL ' + $name + ' -- ' + $why)
41
+ }
42
+ function Assert-Equal([string]$name, $actual, $expected) {
43
+ $a = [string]$actual
44
+ $e = [string]$expected
45
+ if ([string]::Equals($a, $e, [StringComparison]::Ordinal)) { Write-Pass $name }
46
+ else { Write-Fail $name ('expected <' + $e + '> got <' + $a + '>') }
47
+ }
48
+ function Assert-Bool([string]$name, $actual, [bool]$expected) {
49
+ if ([bool]$actual -eq $expected) { Write-Pass $name }
50
+ else { Write-Fail $name ('expected ' + $expected + ' got ' + [string]([bool]$actual)) }
51
+ }
52
+ function Assert-Int([string]$name, $actual, [int]$expected) {
53
+ if ([int]$actual -eq $expected) { Write-Pass $name }
54
+ else { Write-Fail $name ('expected ' + $expected + ' got ' + [string]$actual) }
55
+ }
56
+ function Assert-Score([string]$name, $actual, [double]$expected) {
57
+ $d = [Math]::Abs([double]$actual - $expected)
58
+ if ($d -lt 0.0005) { Write-Pass $name }
59
+ else { Write-Fail $name ('expected score ' + $expected + ' got ' + [string]$actual) }
60
+ }
61
+ function Assert-True([string]$name, [bool]$cond, [string]$detail) {
62
+ if ($cond) { Write-Pass $name } else { Write-Fail $name $detail }
63
+ }
64
+ function Section([string]$title) {
65
+ Write-Host ''
66
+ Write-Host ('--- ' + $title + ' ---')
67
+ }
68
+
69
+ # ---------------------------------------------------------------- 源码自检
70
+ function Assert-SourceEncoding {
71
+ # 本文件若被存成 UTF-8 无 BOM,PS 5.1 会按 ANSI 解码,'会话' 就不再等于 U+4F1A U+9BDD。
72
+ $want = -join @([char]0x4F1A, [char]0x8BDD)
73
+ if (-not [string]::Equals($want, '会话', [StringComparison]::Ordinal)) {
74
+ Write-Host 'FAIL 0.0 测试文件编码错误: 必须保存为 UTF-8 且带 BOM'
75
+ Write-Host (' 解析出的 "会话" = ' + ([int][char]'会') + ',' + ([int][char]'话') + ' 期望 ' + [int][char]0x4F1A + ',' + [int][char]0x9BDD)
76
+ exit 2
77
+ }
78
+ Write-Pass '0.0 测试文件按 UTF-8 正确解码'
79
+ }
80
+
81
+ # ---------------------------------------------------------------- worker 加载
82
+ $script:workerPath = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\worker\uia-worker.ps1'))
83
+ $script:workerAst = $null
84
+ $script:fnAst = @{}
85
+
86
+ function Initialize-WorkerSource {
87
+ if (-not (Test-Path -LiteralPath $script:workerPath)) { throw ('找不到 worker: ' + $script:workerPath) }
88
+ $tokens = $null
89
+ $errors = $null
90
+ $script:workerAst = [System.Management.Automation.Language.Parser]::ParseFile($script:workerPath, [ref]$tokens, [ref]$errors)
91
+ if ($errors.Count -gt 0) {
92
+ foreach ($e in $errors) { Write-Host ('PARSE L' + $e.Extent.StartLineNumber + ': ' + $e.Message) }
93
+ throw ('worker 解析失败, ' + $errors.Count + ' 个语法错误')
94
+ }
95
+ $all = $script:workerAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)
96
+ foreach ($f in $all) { if (-not $script:fnAst.ContainsKey($f.Name)) { $script:fnAst[$f.Name] = $f } }
97
+ # The body was split into worker/lib (the entry dot-sources it in the order sources.mjs declares).
98
+ # Parse every part so Get-WorkerFunctionSource still finds the real definition; a part with a
99
+ # syntax error fails here instead of at the first live tool call.
100
+ $libDir = Join-Path (Split-Path -Parent $script:workerPath) 'lib'
101
+ $script:partAsts = New-Object System.Collections.Generic.List[object]
102
+ if (Test-Path -LiteralPath $libDir) {
103
+ foreach ($part in (Get-ChildItem -LiteralPath $libDir -Filter '*.ps1' | Sort-Object Name)) {
104
+ $tp = $null
105
+ $ep = $null
106
+ $partAst = [System.Management.Automation.Language.Parser]::ParseFile($part.FullName, [ref]$tp, [ref]$ep)
107
+ if ($ep.Count -gt 0) {
108
+ foreach ($e in $ep) { Write-Host ('PARSE ' + $part.Name + ' L' + $e.Extent.StartLineNumber + ': ' + $e.Message) }
109
+ throw ($part.Name + ' 解析失败, ' + $ep.Count + ' 个语法错误')
110
+ }
111
+ $script:partAsts.Add($partAst) | Out-Null
112
+ $allPart = $partAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)
113
+ foreach ($f in $allPart) { if (-not $script:fnAst.ContainsKey($f.Name)) { $script:fnAst[$f.Name] = $f } }
114
+ }
115
+ }
116
+ # 共享 stdio 框架在 worker/ps-stdio.ps1(worker 在运行时 dot-source 它)。按函数名抽取
117
+ # 也要把它的 FunctionDefinitionAst 并进来,否则 $workerDeps 里的 Dict/JsonOf/Split-Err/
118
+ # Esc 等会在 Get-WorkerFunctionSource 报"worker 里没有函数 X"。
119
+ $stdioPath = Join-Path (Split-Path -Parent $script:workerPath) 'ps-stdio.ps1'
120
+ if (Test-Path -LiteralPath $stdioPath) {
121
+ $t2 = $null
122
+ $e2 = $null
123
+ $stdioAst = [System.Management.Automation.Language.Parser]::ParseFile($stdioPath, [ref]$t2, [ref]$e2)
124
+ if ($e2.Count -gt 0) {
125
+ foreach ($e in $e2) { Write-Host ('PARSE ps-stdio L' + $e.Extent.StartLineNumber + ': ' + $e.Message) }
126
+ throw ('ps-stdio.ps1 解析失败, ' + $e2.Count + ' 个语法错误')
127
+ }
128
+ $all2 = $stdioAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)
129
+ foreach ($f in $all2) { if (-not $script:fnAst.ContainsKey($f.Name)) { $script:fnAst[$f.Name] = $f } }
130
+ }
131
+ }
132
+
133
+ function Get-WorkerFunctionSource([string[]]$names) {
134
+ # 只取 FunctionDefinition 的完整源码文本(含 param 块),不执行 worker 本身。
135
+ $parts = New-Object System.Collections.Generic.List[string]
136
+ foreach ($n in $names) {
137
+ if (-not $script:fnAst.ContainsKey($n)) { throw ('worker 里没有函数 ' + $n) }
138
+ $parts.Add($script:fnAst[$n].Extent.Text) | Out-Null
139
+ }
140
+ return ($parts -join "`r`n")
141
+ }
142
+
143
+ function Get-WorkerAssignmentValue([string]$leftText) {
144
+ # $handlers / $defaultBudget moved into worker/lib/10-dispatch.ps1 with the split: search every
145
+ # parsed part, not just the entry, or the dispatch tests read "no handler" and pass on nothing.
146
+ if ($null -ne $script:partAsts) {
147
+ foreach ($ast in $script:partAsts) {
148
+ $hit = $ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and $n.Left.Extent.Text -eq $leftText }, $true) | Select-Object -First 1
149
+ if ($null -ne $hit) { return (Invoke-Expression $hit.Right.Extent.Text) }
150
+ }
151
+ }
152
+ $a = $script:workerAst.FindAll({ param($n) $n -is [System.Management.Automation.Language.AssignmentStatementAst] -and $n.Left.Extent.Text -eq $leftText }, $true) | Select-Object -First 1
153
+ if ($null -eq $a) { return $null }
154
+ return (Invoke-Expression $a.Right.Extent.Text)
155
+ }
156
+
157
+ # ---------------------------------------------------------------- mock 环境
158
+ # 只顶替真正读桌面的 Window-Ae;元素/窗口对象按 UIA 客户端的可观察形状造。
159
+ $script:W = @{ dl = [Int64]::MaxValue; lastMatch = $null }
160
+ $script:ctCache = @{}
161
+ $script:mockAe = $null
162
+ function Window-Ae($entry) { return $script:mockAe }
163
+
164
+ function Test-MockCondition($cp, $cond) {
165
+ # 忠实复现 UIA 条件语义,否则测的就不是阶梯而是 mock 自己的宽严。
166
+ if ($null -eq $cond) { return $true }
167
+ if ([object]::ReferenceEquals($cond, [System.Windows.Automation.Condition]::TrueCondition)) { return $true }
168
+ $tn = $cond.GetType().Name
169
+ if ($tn -eq 'AndCondition') {
170
+ foreach ($c in $cond.GetConditions()) { if (-not (Test-MockCondition $cp $c)) { return $false } }
171
+ return $true
172
+ }
173
+ if ($tn -eq 'PropertyCondition') {
174
+ $p = $cond.Property
175
+ $v = $cond.Value
176
+ if ([object]::ReferenceEquals($p, [System.Windows.Automation.AutomationElement]::NameProperty)) { return ([string]::Equals([string]$cp.Name, [string]$v, [StringComparison]::Ordinal)) }
177
+ if ([object]::ReferenceEquals($p, [System.Windows.Automation.AutomationElement]::AutomationIdProperty)) { return ([string]::Equals([string]$cp.AutomationId, [string]$v, [StringComparison]::Ordinal)) }
178
+ if ([object]::ReferenceEquals($p, [System.Windows.Automation.AutomationElement]::ClassNameProperty)) { return ([string]::Equals([string]$cp.ClassName, [string]$v, [StringComparison]::Ordinal)) }
179
+ if ([object]::ReferenceEquals($p, [System.Windows.Automation.AutomationElement]::ControlTypeProperty)) {
180
+ # PropertyCondition 会把 ControlType 归一化成它的 Id(int),而不是保留 ControlType 对象。
181
+ # 两种形状都要认,否则 mock 永远匹配不上 Button 条件(本轮就是这样翻车的)。
182
+ $a = -1
183
+ try { $a = [int]$cp.ControlType.Id } catch { $a = -1 }
184
+ $b = -2
185
+ if ($v -is [int]) { $b = [int]$v }
186
+ else { try { $b = [int]$v.Id } catch { $b = -2 } }
187
+ return ($a -eq $b)
188
+ }
189
+ throw ('mock 不认识该属性: ' + $p.ProgrammaticName)
190
+ }
191
+ throw ('mock 不认识该条件类型: ' + $tn)
192
+ }
193
+
194
+ function New-MockElement([string]$name, [string]$controlType, [string]$className, [string]$automationId, [double]$x, [double]$y, [double]$w, [double]$h) {
195
+ $ct = $null
196
+ if ($controlType -ne '') {
197
+ $field = [System.Windows.Automation.ControlType].GetField($controlType)
198
+ if ($null -ne $field) { $ct = $field.GetValue($null) }
199
+ }
200
+ # RectOf 只读 X/Y/Width/Height,用同形状的普通对象即可(不引入 WindowsBase 依赖)。
201
+ $rect = [pscustomobject]@{ X = $x; Y = $y; Width = $w; Height = $h }
202
+ $cp = [pscustomobject]@{
203
+ Name = $name
204
+ ControlType = $ct
205
+ ClassName = $className
206
+ AutomationId = $automationId
207
+ IsEnabled = $true
208
+ IsOffscreen = $false
209
+ BoundingRectangle = $rect
210
+ ProcessId = 4242
211
+ }
212
+ $el = [pscustomobject]@{ Current = $cp }
213
+ $el | Add-Member -MemberType ScriptMethod -Name GetRuntimeId -Value { return @(4242, 1) }
214
+ return $el
215
+ }
216
+
217
+ function New-MockWindow($elements) {
218
+ $ae = [pscustomobject]@{ Items = @($elements) }
219
+ $ae | Add-Member -MemberType ScriptMethod -Name FindAll -Value {
220
+ param($scope, $cond)
221
+ $out = New-Object System.Collections.ArrayList
222
+ foreach ($e in $this.Items) {
223
+ if (Test-MockCondition $e.Current $cond) { [void]$out.Add($e) }
224
+ }
225
+ return $out.ToArray()
226
+ }
227
+ $ae | Add-Member -MemberType ScriptMethod -Name FindFirst -Value {
228
+ param($scope, $cond)
229
+ foreach ($e in $this.Items) {
230
+ if (Test-MockCondition $e.Current $cond) { return $e }
231
+ }
232
+ return $null
233
+ }
234
+ return $ae
235
+ }
236
+
237
+ function Invoke-Match($elements, $by) {
238
+ $script:mockAe = New-MockWindow $elements
239
+ $entry = @{ id = 'w1'; hwnd = 4200; revision = 1 }
240
+ return (Find-ByDescriptor $entry $by)
241
+ }
242
+ # prepare_batch / commit_batch 会碰到下面这几层;全部 mock 掉,动作一律不落到桌面。
243
+ # (它们不在 $workerDeps 里,所以不会被真实源码覆盖。)
244
+ function PatternsOf($el) { return @('Invoke') }
245
+ function GetPattern($el, $name) { return $null }
246
+ function Do-Action($re, $action, $value, $step) { return 'uia' }
247
+ function Cursor-Pos { return @{ x = 100; y = 100 } }
248
+ function Foreground-Hwnd { return [IntPtr]::Zero }
249
+ function Test-Escape { return $false }
250
+ function Get-MatchInfo { return $script:W.lastMatch }
251
+ function Get-CandidateReason($cand) {
252
+ if ($null -eq $cand) { return '' }
253
+ return [string]$cand['reason']
254
+ }
255
+ function Get-ItemCount($v) {
256
+ # 不能用 @($v):PS 5.1 对 New-Object 造出来的 List[object] 会抛 "Argument types do not match"。
257
+ if ($null -eq $v) { return 0 }
258
+ if ($v -is [string]) { return 1 }
259
+ if ($v -is [System.Collections.ICollection]) { return [int]$v.Count }
260
+ if ($v -is [System.Collections.IEnumerable]) {
261
+ $n = 0
262
+ foreach ($x in $v) { $n += 1 }
263
+ return $n
264
+ }
265
+ return 1
266
+ }
267
+
268
+
269
+
270
+
271
+ # ---------------------------------------------------------------- 快照/扫描/窗口 mock(P-01/P-02/P-09)
272
+ # 真正碰桌面的三处顶替(都不在 $workerDeps 里,所以不会被真实源码覆盖):
273
+ # Get-SnapshotWalker 生产源码走 ControlViewWalker;这里给 mock walker,让 walker 回退
274
+ # 路径也能在内存里走完整棵树(一次性路径失败时的那条分支)。
275
+ # Window-ObservationHeader 位置元数据探测读真实前台/焦点(跨进程),不属于本文件的被测面。
276
+ # RootWindows commit 窗口 diff 枚举桌面根窗口;由 $script:mockRootWindows 驱动两态。
277
+ function Get-SnapshotWalker { return $script:mockWalker }
278
+ function Window-ObservationHeader($entry) { return @{} }
279
+ # RootWindows mock:commit_batch 在 phase 2 前后各枚举一次(每次调用一对),用奇偶切换返回
280
+ # before/after 两个集合,让同一次 commit 内的 diff 可以构造出「新窗口」。
281
+ $script:mockRootCalls = 0
282
+ $script:mockRootBefore = @()
283
+ $script:mockRootAfter = @()
284
+ function RootWindows {
285
+ $script:mockRootCalls += 1
286
+ if (($script:mockRootCalls % 2) -eq 1) { return $script:mockRootBefore }
287
+ return $script:mockRootAfter
288
+ }
289
+
290
+ $script:mockWalker = [pscustomobject]@{}
291
+ $script:mockWalker | Add-Member -MemberType ScriptMethod -Name GetFirstChild -Value {
292
+ param($el, $req)
293
+ if ($null -eq $el.Children -or $el.Children.Count -eq 0) { return $null }
294
+ $c = $el.Children[0]
295
+ $c.Parent = $el
296
+ return $c
297
+ }
298
+ $script:mockWalker | Add-Member -MemberType ScriptMethod -Name GetNextSibling -Value {
299
+ param($el, $req)
300
+ $p = $el.Parent
301
+ if ($null -eq $p) { return $null }
302
+ $idx = -1
303
+ for ($i = 0; $i -lt $p.Children.Count; $i++) { if ([object]::ReferenceEquals($p.Children[$i], $el)) { $idx = $i; break } }
304
+ if ($idx -lt 0 -or ($idx + 1) -ge $p.Children.Count) { return $null }
305
+ $n = $p.Children[$idx + 1]
306
+ $n.Parent = $p
307
+ return $n
308
+ }
309
+
310
+ # AutomationElementCollection 的最小替身:.Count + int 索引器 + GetEnumerator,让 worker 的
311
+ # CachedChildren 消费代码(Count、[i]、for 反向 push)和 mock walker 的 Children 遍历都按真实
312
+ # 形状工作。
313
+ if (-not ('MockElementCollection' -as [type])) {
314
+ Add-Type -TypeDefinition 'public class MockElementCollection { private System.Collections.Generic.List<object> items = new System.Collections.Generic.List<object>(); public MockElementCollection(object[] src) { if (src != null) { foreach (object i in src) { items.Add(i); } } } public int Count { get { return items.Count; } } public object this[int i] { get { return items[i]; } } public System.Collections.IEnumerator GetEnumerator() { return items.GetEnumerator(); } }'
315
+ }
316
+ function New-MockElementCollection([object[]]$items = @()) {
317
+ return (New-Object MockElementCollection (,$items))
318
+ }
319
+
320
+ # 带缓存形状的 mock 元素:Current/Cached 同构、CachedChildren 导航、GetCachedPropertyValue 供
321
+ # RuntimeIdKey 的缓存读(其余可用性一律 $false,避免牵动 Cached-PatternsOf 的列表内容)。
322
+ $script:snapRid = 100
323
+ function New-MockSnapElement([string]$name, [string]$ct, [object[]]$children = @()) {
324
+ $script:snapRid += 1
325
+ $ctObj = $null
326
+ $field = [System.Windows.Automation.ControlType].GetField($ct)
327
+ if ($null -ne $field) { $ctObj = $field.GetValue($null) }
328
+ $rect = [pscustomobject]@{ X = 5.0; Y = 5.0; Width = 100.0; Height = 20.0 }
329
+ $cp = [pscustomobject]@{ Name = $name; ControlType = $ctObj; ClassName = 'Mock'; AutomationId = ('aid-' + $script:snapRid); IsEnabled = $true; IsOffscreen = $false; BoundingRectangle = $rect }
330
+ $kidsCol = New-MockElementCollection $children
331
+ $el = [pscustomobject]@{ Current = $cp; Cached = $cp; Children = $kidsCol; Rid = $script:snapRid; Parent = $null }
332
+ $el | Add-Member -MemberType ScriptMethod -Name GetRuntimeId -Value { return @(77, $this.Rid) }
333
+ $el | Add-Member -MemberType ScriptMethod -Name GetCachedPropertyValue -Value {
334
+ param($prop)
335
+ if ([object]::ReferenceEquals($prop, [System.Windows.Automation.AutomationElement]::RuntimeIdProperty)) { return @(77, $this.Rid) }
336
+ return $false
337
+ }
338
+ # CachedChildren 必须是「属性访问」形状(真实 AutomationElement.CachedChildren 是 .NET 属性,
339
+ # worker 用无括号访问),不能用 ScriptMethod:PS 5.1 对 ScriptMethod 的无括号访问返回方法
340
+ # 对象本身而不调用它(实测),那会让一次性路径把方法对象当子元素推进队列。集合对象自带
341
+ # .Count 与索引器,与 AutomationElementCollection 的用法一致。
342
+ $el | Add-Member -MemberType NoteProperty -Name CachedChildren -Value (New-MockElementCollection $children)
343
+ return $el
344
+ }
345
+
346
+ # 快照/扫描 mock 窗口:GetUpdatedCache 返回整树缓存根(一次性路径,带调用计数);FindAll 返回
347
+ # 全部元素(find_text 扫描)。没有 GetUpdatedCache 的窗口对象(New-MockWindow)走 walker 回退。
348
+ function New-MockSnapshotWindow($rootEl, [object[]]$findElements = @()) {
349
+ $ae = [pscustomobject]@{ CachedRoot = $rootEl; AllElements = @($findElements); GetUpdatedCalls = 0 }
350
+ $ae | Add-Member -MemberType ScriptMethod -Name GetUpdatedCache -Value {
351
+ param($req)
352
+ $this.GetUpdatedCalls = $this.GetUpdatedCalls + 1
353
+ return $this.CachedRoot
354
+ }
355
+ $ae | Add-Member -MemberType ScriptMethod -Name FindAll -Value { param($scope, $cond) return $this.AllElements }
356
+ return $ae
357
+ }
358
+
359
+ function New-MockRootWindow($hwnd, $procId, $title) {
360
+ $cp = [pscustomobject]@{ NativeWindowHandle = $hwnd; ProcessId = $procId; Name = $title; ClassName = 'MockRoot' }
361
+ return [pscustomobject]@{ Current = $cp }
362
+ }
363
+
364
+ function Reset-WorkerState {
365
+ # 每个 P-01/P-02/P-09 用例节的公共底座:worker 真实的 $script:W 形状 + 空表 + 无 deadline。
366
+ $script:W = Get-WorkerAssignmentValue '$script:W'
367
+ $script:W.dl = [Int64]::MaxValue
368
+ $script:W.lastMatch = $null
369
+ $script:W.windows = @{}
370
+ $script:W.winByHwnd = @{}
371
+ $script:W.refs = @{}
372
+ $script:W.refOrder = New-Object System.Collections.Generic.List[string]
373
+ $script:W.refSeq = 0
374
+ $script:W.totalRefs = 0
375
+ $script:nativeLoaded = $true
376
+ $script:escCache = @{}
377
+ $script:snapProps = Get-WorkerAssignmentValue '$script:snapProps'
378
+ $script:snapPatterns = Get-WorkerAssignmentValue '$script:snapPatterns'
379
+ $script:cachedPatProps = Get-WorkerAssignmentValue '$script:cachedPatProps'
380
+ $script:snapReq = $null
381
+ $script:subTreeReq = $null
382
+ $script:findReq = $null
383
+ $script:mockRootCalls = 0
384
+ $script:mockRootBefore = @()
385
+ $script:mockRootAfter = @()
386
+ }
387
+
388
+ # type_text 用例的 [Native] 桩:worker 源码按类名引用 [Native],测试环境不编译原生助手,给一个
389
+ # 纯内存实现(键盘路径返回固定计数),这样 via 缺省=keyboard 的正测也不会真发 SendInput。
390
+ if (-not ('Native' -as [type])) {
391
+ Add-Type -TypeDefinition 'public static class Native { public static int SendUnicode(string s) { return s.Length * 2; } public static uint KeyDownVk(int vk) { return 1u; } public static uint KeyUpVk(int vk) { return 1u; } public static System.IntPtr GetForegroundWindow() { return System.IntPtr.Zero; } public static bool IsWindowVisible(System.IntPtr h) { return true; } }'
392
+ }
393
+
394
+ # 真实 worker 函数(不含任何桌面调用)
395
+ Assert-SourceEncoding
396
+ try {
397
+ Initialize-WorkerSource
398
+ } catch {
399
+ Write-Host ('FAIL 0.1 ' + $_.Exception.Message)
400
+ exit 2
401
+ }
402
+ Write-Pass ('0.1 worker 静态解析通过 (' + $script:fnAst.Count + ' 个函数)')
403
+
404
+ $workerDeps = @(
405
+ 'Normalize-NameText', 'Get-NameSimilarity', 'Test-ExplicitFalse', 'Join-UiaCondition', 'Get-MatchScore',
406
+ 'Get-LocatorFields', 'New-MatchCandidate', 'New-MatchCandidateList', 'Select-DescriptorHit', 'Find-ByDescriptor',
407
+ 'Dict', 'ArgOf', 'Err', 'TruncStr', 'TickNow', 'Test-Deadline', 'RectOf', 'ControlTypeName',
408
+ 'Cmd-DescriptorMatch', 'Window-Entry', 'StrArg', 'JsonOf', 'Esc', 'OneLine',
409
+ 'Cmd-PrepareBatch', 'Cmd-CommitBatch', 'ListOf', 'IntArg', 'BoolArg', 'Split-Err', 'MsFrom',
410
+ 'DescriptorOf', 'Read-Value', 'SupportedActionOf', 'Resolve-Ref', 'New-Ref', 'RuntimeIdKey', 'Apply-ModeArg',
411
+ # GetPattern 缓存层:Read-Value 第三参路由到这里,不加载就会在 commit 用例里 CommandNotFound。
412
+ 'Get-RefPattern',
413
+ # 屏外元素先滚动到可见:Cmd-CommitBatch 每步动作前都会调用它,缺了就在 15.x 里整批失败。
414
+ 'Ensure-InView',
415
+ # verify 求值管道:Eval-Once(scroll_percent_changed 用例)/ Target-Element(其目标解析)/
416
+ # Read-ScrollPercent(滚动百分比动作前读数)。
417
+ 'Eval-Once', 'Target-Element', 'Read-ScrollPercent',
418
+ # 快照/扫描/输入通道(P-01/P-02/P-05):一次性子树路径 + walker 回退、缓存可用性、find_text
419
+ # 缓存扫描、type_text via 分支,全部走真实源码(walker/前台/根窗口由下面 mock 区顶替)。
420
+ 'Build-Snapshot', 'Build-SnapshotNode', 'Snapshot-CacheRequest', 'Subtree-CacheRequest',
421
+ 'New-SnapshotCacheRequest', 'Find-CacheRequest', 'Cached-PatternsOf', 'Cached-ValueOf',
422
+ 'Cmd-FindText', 'Cmd-TypeText', 'Ensure-Pointer', 'Log', 'Evict-ForReservation',
423
+ # Snapshot nodes read state now: without these two the per-node catch turns every node into
424
+ # nodeProviderError and the whole tree comes back empty.
425
+ 'State-Of', 'State-Missing'
426
+ )
427
+ try {
428
+ Invoke-Expression (Get-WorkerFunctionSource $workerDeps)
429
+ } catch {
430
+ Write-Host ('FAIL 0.2 抽取 worker 函数失败: ' + $_.Exception.Message)
431
+ exit 2
432
+ }
433
+ Write-Pass ('0.2 从 AST 抽取并加载 ' + $workerDeps.Count + ' 个真实函数(未执行 worker)')
434
+
435
+ # ================================================================ 用例
436
+ Section '1. strict 精确匹配(向后兼容基线)'
437
+ $e1 = New-MockElement '会话 A 刚刚' 'Button' 'ChatRow' 'row-1' 10 10 200 24
438
+ $by1 = @{ name = '会话 A 刚刚'; controlType = 'Button'; automationId = 'row-1' }
439
+ $el = Invoke-Match @($e1) $by1
440
+ $lm = Get-MatchInfo
441
+ Assert-True '1.1 命中元素(返回元素对象,不是包装体)' ($null -ne $el) 'expected an AutomationElement'
442
+ $gotName = ''
443
+ if ($null -ne $el) { $gotName = [string]$el.Current.Name }
444
+ Assert-Equal '1.2 返回的就是该元素本身(.Current.Name 可读)' $gotName '会话 A 刚刚'
445
+ Assert-Equal '1.3 matchedBy=strict' $lm.matchedBy 'strict'
446
+ Assert-Equal '1.4 ladder=strict' $lm.ladder 'strict'
447
+ Assert-Bool '1.5 degraded=false(未降级)' $lm.degraded $false
448
+ Assert-Score '1.6 score=1.0' $lm.score 1.0
449
+ Assert-Equal '1.7 scanned=first(strict 无消歧时走 FindFirst 快路径)' $lm.scanned 'first'
450
+ # F: 快路径诚实化——FindFirst 只见第一个命中,真实命中数未知。旧行为伪造 candidateCount=1,
451
+ # descriptor_match 读到的就是谎言。现在钉住:count 留 0(表示"未知")且 candidateCountKnown=false,
452
+ # 由只读诊断 descriptor_match 用同条件全量枚举补上真实数(见 1.10x 用例)。
453
+ Assert-Int '1.8 快路径不伪造 candidateCount(未知=0)' $lm.candidateCount 0
454
+ Assert-Bool '1.9 nameExact 记录为 true' $lm.nameExact $true
455
+ Assert-Bool '1.10 candidateCountKnown=false(FindFirst 无法知道总数)' $lm.candidateCountKnown $false
456
+ Assert-True '1.11 fastCond 保留(供 descriptor_match 重枚举)' ($null -ne $lm.fastCond) 'fastCond is null'
457
+
458
+ Section '2. 动态时间戳:strict 失败 → normalizedName 命中并报告降级'
459
+ $e2 = New-MockElement '会话 A 3分钟' 'Button' 'ChatRow' '' 10 10 200 24
460
+ $by2 = @{ name = '会话 A 刚刚'; controlType = 'Button' }
461
+ $el = Invoke-Match @($e2) $by2
462
+ $lm = Get-MatchInfo
463
+ Assert-True '2.1 归一化后命中' ($null -ne $el) 'expected the row whose name churned'
464
+ Assert-Equal '2.2 matchedBy=normalizedName' $lm.matchedBy 'normalizedName'
465
+ Assert-Equal '2.3 ladder=normalizedName' $lm.ladder 'normalizedName'
466
+ Assert-Bool '2.4 degraded=true(必须报告降级)' $lm.degraded $true
467
+ Assert-Score '2.5 score=0.7' $lm.score 0.7
468
+ $tried = ($lm.tried -join ',')
469
+ Assert-Equal '2.6 先 strict 再 normalizedName' $tried 'strict,normalizedName'
470
+ Assert-Int '2.7 candidateCount=1' $lm.candidateCount 1
471
+
472
+ Section '3. id-anchored:automationId 在、名称已变,仍命中'
473
+ $e3 = New-MockElement '会话 B 5分钟' 'Button' 'ChatRow' 'row-42' 10 40 200 24
474
+ $by3 = @{ name = '会话 B 刚刚'; controlType = 'Button'; automationId = 'row-42' }
475
+ $el = Invoke-Match @($e3) $by3
476
+ $lm = Get-MatchInfo
477
+ Assert-True '3.1 命中' ($null -ne $el) 'expected the id-anchored row'
478
+ Assert-Equal '3.2 matchedBy=id(名称不参与)' $lm.matchedBy 'id'
479
+ Assert-Equal '3.3 ladder=id' $lm.ladder 'id'
480
+ Assert-Bool '3.4 degraded=true' $lm.degraded $true
481
+ Assert-Score '3.5 score=0.8' $lm.score 0.8
482
+ $tried = ($lm.tried -join ',')
483
+ Assert-Equal '3.6 tried=strict,id(在 id 级停下)' $tried 'strict,id'
484
+ Assert-Int '3.7 candidateCount=1' $lm.candidateCount 1
485
+
486
+ Section '4. nameExact:false → prefix 字面包含;* ? [ ] 不得当通配符'
487
+ $e4 = New-MockElement '导出 [CSV] 报告' 'Button' 'Toolbar' 'btn-export' 10 70 120 24
488
+ $by4 = @{ name = '[CSV]'; nameExact = $false; controlType = 'Button' }
489
+ $el = Invoke-Match @($e4) $by4
490
+ $lm = Get-MatchInfo
491
+ Assert-True '4.1 方括号名称按字面命中' ($null -ne $el) 'expected literal substring match'
492
+ Assert-Equal '4.2 matchedBy=prefix' $lm.matchedBy 'prefix'
493
+ Assert-Equal '4.3 ladder=prefix' $lm.ladder 'prefix'
494
+ Assert-Bool '4.4 degraded=true' $lm.degraded $true
495
+ Assert-Score '4.5 score=0.55' $lm.score 0.55
496
+ Assert-Bool '4.6 nameExact 记录为 false' $lm.nameExact $false
497
+ $e4b = New-MockElement 'axb' 'Button' 'Toolbar' '' 10 100 120 24
498
+ $by4b = @{ name = 'a*b'; nameExact = $false; controlType = 'Button' }
499
+ $el = Invoke-Match @($e4b) $by4b
500
+ $lm = Get-MatchInfo
501
+ Assert-True '4.7 * 不是通配符(a*b 不匹配 axb)' ($null -eq $el) 'matched something, substring must be literal'
502
+ Assert-Equal '4.8 未命中原因=no_match' $lm.reason 'no_match'
503
+ Assert-True '4.9 仍给出最接近的候选' ($lm.candidates.Count -ge 1) ('candidates=' + $lm.candidates.Count)
504
+ $cand0 = $lm.candidates[0]
505
+ $candReason = Get-CandidateReason $cand0
506
+ Assert-True '4.10 候选标注 name-differs' ($candReason.IndexOf('name-differs') -ge 0) ('reason=' + $candReason)
507
+ $e4c = New-MockElement 'C' 'Button' 'Toolbar' '' 10 120 40 24
508
+ $by4c = @{ name = '[CSV]'; nameExact = $false; controlType = 'Button' }
509
+ $el = Invoke-Match @($e4c) $by4c
510
+ Assert-True '4.11 方括号不是字符集([CSV] 不匹配 C)' ($null -eq $el) 'brackets were treated as a character class'
511
+ $e4d = New-MockElement '导出 [CSV] 报告' 'Button' 'Toolbar' 'btn-export' 10 70 120 24
512
+ $by4d = @{ name = '[CSV]'; nameExact = 'false'; controlType = 'Button' }
513
+ $el = Invoke-Match @($e4d) $by4d
514
+ $lm = Get-MatchInfo
515
+ Assert-Equal '4.12 字符串 "false" 同样表示显式不精确' $lm.matchedBy 'prefix'
516
+
517
+ Section '5. 歧义:同 id 同类型、无 nth/nearPoint → 失败并带候选'
518
+ $e5a = New-MockElement '行 甲' 'Button' 'Row' 'row-x' 10 10 100 20
519
+ $e5b = New-MockElement '行 乙' 'Button' 'Row' 'row-x' 10 40 100 20
520
+ $by5 = @{ name = '行 丙'; controlType = 'Button'; automationId = 'row-x' }
521
+ $el = Invoke-Match @($e5a, $e5b) $by5
522
+ $lm = Get-MatchInfo
523
+ Assert-True '5.1 未命中(不静默取第一个)' ($null -eq $el) 'ambiguous descriptor resolved to an element'
524
+ Assert-Equal '5.2 reason=ambiguous' $lm.reason 'ambiguous'
525
+ Assert-Equal '5.3 ambiguityAt=id' $lm.ambiguityAt 'id'
526
+ Assert-True '5.4 candidates >= 2' ($lm.candidates.Count -ge 2) ('candidates=' + $lm.candidates.Count)
527
+ $c0 = $lm.candidates[0]
528
+ $c1 = $lm.candidates[1]
529
+ Assert-Equal '5.5 候选1 name' ([string]($c0['name'])) '行 甲'
530
+ Assert-Equal '5.6 候选1 automationId' ([string]($c0['automationId'])) 'row-x'
531
+ Assert-Equal '5.7 候选1 controlType' ([string]($c0['controlType'])) 'Button'
532
+ Assert-Int '5.8 候选1 可用 nth=1 复现' ([int]($c0['nth'])) 1
533
+ Assert-Int '5.9 候选2 可用 nth=2 复现' ([int]($c1['nth'])) 2
534
+ $r0 = Get-CandidateReason $c0
535
+ Assert-True '5.10 候选标注 ambiguous' ($r0.IndexOf('ambiguous') -ge 0) ('reason=' + $r0)
536
+ Assert-Int '5.11 candidateCount=2' $lm.candidateCount 2
537
+
538
+ Section '6. nth / nearPoint 在 id 分支下仍然生效(防退化)'
539
+ $by6a = @{ name = '行 丙'; controlType = 'Button'; automationId = 'row-x'; nth = 2 }
540
+ $el = Invoke-Match @($e5a, $e5b) $by6a
541
+ $lm = Get-MatchInfo
542
+ $n6 = ''
543
+ if ($null -ne $el) { $n6 = [string]$el.Current.Name }
544
+ Assert-Equal '6.1 nth=2 取到第二个' $n6 '行 乙'
545
+ Assert-Equal '6.2 matchedBy=nth' $lm.matchedBy 'nth'
546
+ Assert-Equal '6.3 ladder=id(仍由 id 级定集)' $lm.ladder 'id'
547
+ Assert-Score '6.4 score=0.75(0.8-0.05)' $lm.score 0.75
548
+ $by6b = @{ name = '行 丙'; controlType = 'Button'; automationId = 'row-x'; nearPoint = @{ x = 60; y = 20 } }
549
+ $el = Invoke-Match @($e5a, $e5b) $by6b
550
+ $lm = Get-MatchInfo
551
+ $n6b = ''
552
+ if ($null -ne $el) { $n6b = [string]$el.Current.Name }
553
+ Assert-Equal '6.5 nearPoint 取到最近的' $n6b '行 甲'
554
+ Assert-Equal '6.6 matchedBy=nearPoint' $lm.matchedBy 'nearPoint'
555
+ Assert-Equal '6.7 ladder=id' $lm.ladder 'id'
556
+ Assert-Score '6.8 score=0.77(0.8-0.03)' $lm.score 0.77
557
+
558
+ Section '7. 归一化函数自身的边界(逐条规则)'
559
+ $just = -join @([char]0x521A, [char]0x521A)
560
+ $min2 = -join @([char]0x5206, [char]0x949F)
561
+ $hour = -join @([char]0x5C0F, [char]0x65F6)
562
+ $dayw = -join @([char]0x5929)
563
+ $lp = [char]0xFF08
564
+ $rp = [char]0xFF09
565
+ $itemw = -join @([char]0x9879)
566
+
567
+ $s = ' 会话 A ' + $just + ' '
568
+ Assert-Equal ('7.1 空白折叠+去首尾: ' + $s) (Normalize-NameText $s) '会话 A'
569
+ $s = '会话 A ' + $just
570
+ Assert-Equal '7.2 去尾随相对时间(刚刚)' (Normalize-NameText $s) '会话 A'
571
+ $s = '会话 A 3' + $min2
572
+ Assert-Equal '7.3 去尾随 N分钟' (Normalize-NameText $s) '会话 A'
573
+ $s = '会话 A 2' + $hour
574
+ Assert-Equal '7.4 去尾随 N小时' (Normalize-NameText $s) '会话 A'
575
+ $s = '会话 A 1' + $dayw
576
+ Assert-Equal '7.5 去尾随 N天' (Normalize-NameText $s) '会话 A'
577
+ $s = '会话 A 14:03'
578
+ Assert-Equal '7.6 去尾随时间戳 H:MM' (Normalize-NameText $s) '会话 A'
579
+ $s = '会话 A 14:03:59'
580
+ Assert-Equal '7.7 去尾随时间戳 H:MM:SS' (Normalize-NameText $s) '会话 A'
581
+ $s = '收件箱 (3)'
582
+ Assert-Equal '7.8 去尾随纯计数括号 (3)' (Normalize-NameText $s) '收件箱'
583
+ $s = '收件箱 ' + $lp + '12' + $rp
584
+ Assert-Equal '7.9 去尾随纯计数括号(全角)' (Normalize-NameText $s) '收件箱'
585
+ $s = '设置 (2 ' + $itemw + ')'
586
+ Assert-Equal '7.10 非纯计数括号不动:设置 (2 项)' (Normalize-NameText $s) $s
587
+ $s = '普通标题'
588
+ Assert-Equal '7.11 普通标题不动' (Normalize-NameText $s) $s
589
+ $s = '设置'
590
+ Assert-Equal '7.12 短标题不动' (Normalize-NameText $s) $s
591
+ $s = '倒计时3' + $min2
592
+ Assert-Equal '7.13 粘连的时间尾段不猜(无分隔符)' (Normalize-NameText $s) $s
593
+ $s = $just + ' 会话 A'
594
+ Assert-Equal '7.14 只处理尾段,头部不动' (Normalize-NameText $s) $s
595
+ $s = '会话 A ' + $just + ' (2)'
596
+ Assert-Equal '7.15 时间+计数组合一次归一' (Normalize-NameText $s) '会话 A'
597
+ $s = $null
598
+ Assert-Equal '7.16 null 归一为空串' (Normalize-NameText $s) ''
599
+ $s = ''
600
+ Assert-Equal '7.17 空串保持空串' (Normalize-NameText $s) ''
601
+
602
+ $idem = @(
603
+ ('会话 A ' + $just), ('会话 A 3' + $min2), ('收件箱 (3)'), ('设置 (2 ' + $itemw + ')'),
604
+ ('倒计时3' + $min2), ('普通标题'), (' A B '), ('会话 A ' + $just + ' (2)')
605
+ )
606
+ $idemOk = $true
607
+ $idemBad = ''
608
+ foreach ($v in $idem) {
609
+ $once = Normalize-NameText $v
610
+ $twice = Normalize-NameText $once
611
+ if (-not [string]::Equals($once, $twice, [StringComparison]::Ordinal)) { $idemOk = $false; $idemBad = $v }
612
+ }
613
+ Assert-True '7.18 幂等性:归一化两次等于一次' $idemOk ('not idempotent for: ' + $idemBad)
614
+
615
+ Section '8. id 级歧义被更精确的 normalizedName 级化解(并如实报告)'
616
+ $e8a = New-MockElement ('群聊 3' + $min2) 'Button' 'Row' 'row-z' 10 10 100 20
617
+ $e8b = New-MockElement ('私聊 5' + $min2) 'Button' 'Row' 'row-z' 10 40 100 20
618
+ $by8 = @{ name = ('群聊 ' + $just); controlType = 'Button'; automationId = 'row-z' }
619
+ $el = Invoke-Match @($e8a, $e8b) $by8
620
+ $lm = Get-MatchInfo
621
+ $n8 = ''
622
+ if ($null -ne $el) { $n8 = [string]$el.Current.Name }
623
+ Assert-Equal ('8.1 归一化名称唯一定位到 群聊 3' + $min2) $n8 ('群聊 3' + $min2)
624
+ Assert-Equal '8.2 matchedBy=normalizedName' $lm.matchedBy 'normalizedName'
625
+ Assert-Equal '8.3 ambiguityAt=id(id 级歧义被记录,未静默吞掉)' $lm.ambiguityAt 'id'
626
+ Assert-Bool '8.4 degraded=true' $lm.degraded $true
627
+
628
+ Section '9. 老配方基线:同名多命中、无消歧 → 仍取树序第一个'
629
+ $e9a = New-MockElement '复制' 'Button' 'Toolbar' 'btn-copy' 10 10 60 20
630
+ $e9b = New-MockElement '复制' 'Button' 'Menu' 'btn-copy2' 10 40 60 20
631
+ $by9 = @{ name = '复制'; controlType = 'Button' }
632
+ $el = Invoke-Match @($e9a, $e9b) $by9
633
+ $lm = Get-MatchInfo
634
+ $n9 = ''
635
+ $y9 = -1.0
636
+ if ($null -ne $el) { $n9 = [string]$el.Current.Name; $y9 = [double]$el.Current.BoundingRectangle.Y }
637
+ Assert-Equal '9.1 取到同名元素' $n9 '复制'
638
+ Assert-Score '9.2 首元素 Y=10(树序第一个)' $y9 10
639
+ Assert-Equal '9.3 matchedBy=strict' $lm.matchedBy 'strict'
640
+ Assert-Score '9.4 score=1.0(已有配方仍是最强匹配)' $lm.score 1.0
641
+ Assert-Equal '9.5 scanned=first(未枚举,与旧 FindFirst 一致)' $lm.scanned 'first'
642
+
643
+ Section '10. nth 越界 = 终止失败,不静默降级到别的元素'
644
+ $e10 = New-MockElement ('上行 3' + $min2) 'Button' 'Row' 'row-x' 10 10 100 20
645
+ $by10 = @{ name = ('上行 ' + $just); controlType = 'Button'; automationId = 'row-x'; nth = 3 }
646
+ $el = Invoke-Match @($e10) $by10
647
+ $lm = Get-MatchInfo
648
+ Assert-True '10.1 未命中(不拿第一个顶替)' ($null -eq $el) 'nth out of range silently resolved'
649
+ Assert-Equal '10.2 reason=nth_out_of_range' $lm.reason 'nth_out_of_range'
650
+ Assert-True '10.3 仍给出候选' ($lm.candidates.Count -ge 1) ('candidates=' + $lm.candidates.Count)
651
+ $c10 = $lm.candidates[0]
652
+ Assert-Int '10.4 候选标出 nth=1' ([int]($c10['nth'])) 1
653
+ $r10 = Get-CandidateReason $c10
654
+ Assert-True '10.5 候选原因含 nth_out_of_range' ($r10.IndexOf('nth_out_of_range') -ge 0) ('reason=' + $r10)
655
+
656
+ Section '11. 命令注册与状态槽(静态契约,不执行 worker)'
657
+ $handlers = Get-WorkerAssignmentValue '$handlers'
658
+ $budgets = Get-WorkerAssignmentValue '$defaultBudget'
659
+ $wInit = Get-WorkerAssignmentValue '$script:W'
660
+ $hasHandler = ($null -ne $handlers -and $handlers.ContainsKey('descriptor_match'))
661
+ Assert-True '11.1 $handlers 注册了 descriptor_match' $hasHandler 'no descriptor_match handler'
662
+ $hval = ''
663
+ if ($hasHandler) { $hval = [string]$handlers['descriptor_match'] }
664
+ Assert-Equal '11.2 descriptor_match → Cmd-DescriptorMatch' $hval 'Cmd-DescriptorMatch'
665
+ Assert-True '11.3 Cmd-DescriptorMatch 函数存在' ($script:fnAst.ContainsKey('Cmd-DescriptorMatch')) 'function missing'
666
+ $hasBudget = ($null -ne $budgets -and $budgets.ContainsKey('descriptor_match'))
667
+ Assert-True '11.4 $defaultBudget 配了 descriptor_match' $hasBudget 'no budget'
668
+ $bval = -1
669
+ if ($hasBudget) { $bval = [int]$budgets['descriptor_match'] }
670
+ Assert-True '11.5 budget 在 (0,12000] 区间' ($bval -gt 0 -and $bval -le 12000) ('budget=' + $bval)
671
+ Assert-True '11.6 $script:W 有 lastMatch 槽' ($null -ne $wInit -and $wInit.ContainsKey('lastMatch')) 'lastMatch missing'
672
+ $missing = New-Object System.Collections.Generic.List[string]
673
+ foreach ($k in @($handlers.Keys)) {
674
+ $fn = [string]$handlers[$k]
675
+ if (-not $script:fnAst.ContainsKey($fn)) { $missing.Add($k + '->' + $fn) | Out-Null }
676
+ }
677
+ Assert-True '11.7 所有 handler 都指向真实存在的函数' ($missing.Count -eq 0) ('broken: ' + ($missing -join ', '))
678
+ $missingTier = New-Object System.Collections.Generic.List[string]
679
+ foreach ($f in $workerDeps) { if (-not $script:fnAst.ContainsKey($f)) { $missingTier.Add($f) | Out-Null } }
680
+ Assert-True '11.8 阶梯相关函数齐全' ($missingTier.Count -eq 0) ('missing: ' + ($missingTier -join ', '))
681
+
682
+ Section '12. 只给结构条件的描述符(无 name)保持旧行为'
683
+ $e12 = New-MockElement '会话 C 刚刚' 'Button' 'ChatRow' 'row-77' 10 10 200 24
684
+ $by12 = @{ controlType = 'Button'; automationId = 'row-77' }
685
+ $el = Invoke-Match @($e12) $by12
686
+ $lm = Get-MatchInfo
687
+ $n12 = ''
688
+ if ($null -ne $el) { $n12 = [string]$el.Current.Name }
689
+ Assert-Equal '12.1 结构条件命中' $n12 '会话 C 刚刚'
690
+ Assert-Equal '12.2 matchedBy=strict' $lm.matchedBy 'strict'
691
+ Assert-Bool '12.3 degraded=false' $lm.degraded $false
692
+ Assert-Score '12.4 score=1.0' $lm.score 1.0
693
+ $tried = ($lm.tried -join ',')
694
+ Assert-Equal '12.5 无 name 时不跑多余层级' $tried 'strict'
695
+
696
+ Section '13. descriptor_match:旁路信息透出 + JSON 契约 + 只读'
697
+ $script:escCache = @{}
698
+ $script:W.refs = @{}
699
+ $script:W.windows = @{}
700
+ $entry13 = @{ id = 'w1'; hwnd = 4200; revision = 1; class = 'ChatWnd'; pid = 4242; snapshots = @() }
701
+ $script:W.windows['w1'] = $entry13
702
+ $e13 = New-MockElement '会话 D 刚刚' 'Button' 'ChatRow' 'row-9' 10 10 200 24
703
+ $script:mockAe = New-MockWindow @($e13)
704
+ $args13 = @{ windowId = 'w1'; by = @{ name = '会话 D 刚刚'; controlType = 'Button' } }
705
+ $res13 = Cmd-DescriptorMatch $args13
706
+ Assert-Bool '13.1 found=true' $res13['found'] $true
707
+ Assert-Equal '13.2 matchedBy=strict' ([string]($res13['matchedBy'])) 'strict'
708
+ Assert-Score '13.3 score=1.0' ([double]($res13['score'])) 1.0
709
+ Assert-Bool '13.4 degraded=false' $res13['degraded'] $false
710
+ $elem13 = $res13['element']
711
+ Assert-Equal '13.5 element.name' ([string]($elem13['name'])) '会话 D 刚刚'
712
+ Assert-Equal '13.6 element.controlType' ([string]($elem13['controlType'])) 'Button'
713
+ Assert-Equal '13.7 element.automationId' ([string]($elem13['automationId'])) 'row-9'
714
+ Assert-True '13.8 成功时 candidates 为空' ((Get-ItemCount $res13['candidates']) -eq 0) 'candidates not empty'
715
+ $json13 = JsonOf $res13
716
+ Write-Host (' JSON: ' + $json13)
717
+ $okJson13 = $true
718
+ $obj13 = $null
719
+ try { $obj13 = ConvertFrom-Json $json13 } catch { $okJson13 = $false }
720
+ Assert-True '13.9 JsonOf 产出可解析 JSON' $okJson13 $json13
721
+ if ($okJson13) {
722
+ Assert-Bool '13.10 JSON found=true' $obj13.found $true
723
+ Assert-Equal '13.11 JSON matchedBy' ([string]$obj13.matchedBy) 'strict'
724
+ Assert-Equal '13.12 JSON element.name' ([string]$obj13.element.name) '会话 D 刚刚'
725
+ }
726
+ Assert-Int '13.13 只读:未铸造 ref' ($script:W.refs.Count) 0
727
+ Assert-Int '13.14 只读:未改窗口 revision' ([int]$entry13.revision) 1
728
+ $e13b = New-MockElement '行 甲' 'Button' 'Row' 'row-x' 10 10 100 20
729
+ $e13c = New-MockElement '行 乙' 'Button' 'Row' 'row-x' 10 40 100 20
730
+ $script:mockAe = New-MockWindow @($e13b, $e13c)
731
+ $args13b = @{ windowId = 'w1'; by = @{ name = '行 丙'; controlType = 'Button'; automationId = 'row-x' } }
732
+ $res13b = Cmd-DescriptorMatch $args13b
733
+ Assert-Bool '13.15 失败时 found=false' $res13b['found'] $false
734
+ Assert-Equal '13.16 失败原因=ambiguous' ([string]($res13b['reason'])) 'ambiguous'
735
+ Assert-True '13.17 失败仍带候选' ((Get-ItemCount $res13b['candidates']) -ge 2) ('candidates=' + (Get-ItemCount $res13b['candidates']))
736
+ $json13b = JsonOf $res13b
737
+ $obj13b = ConvertFrom-Json $json13b
738
+ Assert-True '13.18 失败 JSON 省略 matchedBy/ladder' ($null -eq $obj13b.matchedBy -and $null -eq $obj13b.ladder) $json13b
739
+
740
+ Section '14. strict 级的老消歧(nth/nearPoint)重构后仍按原语义工作'
741
+ $e14a = New-MockElement '复制' 'Button' 'Toolbar' 'btn-copy' 10 10 60 20
742
+ $e14b = New-MockElement '复制' 'Button' 'Toolbar' 'btn-copy2' 10 40 60 20
743
+ $by14a = @{ name = '复制'; controlType = 'Button'; nth = 2 }
744
+ $el = Invoke-Match @($e14a, $e14b) $by14a
745
+ $lm = Get-MatchInfo
746
+ $y14 = -1.0
747
+ if ($null -ne $el) { $y14 = [double]$el.Current.BoundingRectangle.Y }
748
+ Assert-Score '14.1 strict+nth=2 取第二个(Y=40)' $y14 40
749
+ Assert-Equal '14.2 matchedBy=nth' $lm.matchedBy 'nth'
750
+ Assert-Equal '14.3 ladder=strict(集合仍由精确条件定)' $lm.ladder 'strict'
751
+ Assert-Score '14.4 score=0.95(1.0-0.05)' $lm.score 0.95
752
+ Assert-Int '14.5 candidateCount=2' $lm.candidateCount 2
753
+ $by14b = @{ name = '复制'; controlType = 'Button'; nearPoint = @{ x = 40; y = 15 } }
754
+ $el = Invoke-Match @($e14a, $e14b) $by14b
755
+ $lm = Get-MatchInfo
756
+ $y14b = -1.0
757
+ if ($null -ne $el) { $y14b = [double]$el.Current.BoundingRectangle.Y }
758
+ Assert-Score '14.6 strict+nearPoint 取最近的(Y=10)' $y14b 10
759
+ Assert-Equal '14.7 matchedBy=nearPoint' $lm.matchedBy 'nearPoint'
760
+ Assert-Equal '14.8 ladder=strict' $lm.ladder 'strict'
761
+ Assert-Score '14.9 score=0.97(1.0-0.03)' $lm.score 0.97
762
+
763
+ Section '15. prepare/commit 逐步结果携带定位置信度(ref 分支不带)'
764
+ # 以 worker 真实的 $script:W 初始化做底(actionNames/stats/refs 形状都对),再补窗口与引用表。
765
+ $script:W = Get-WorkerAssignmentValue '$script:W'
766
+ $script:W.dl = [Int64]::MaxValue
767
+ $script:W.lastMatch = $null
768
+ $script:W.windows = @{}
769
+ $script:W.winByHwnd = @{}
770
+ $script:W.refs = @{}
771
+ $script:W.refOrder = New-Object System.Collections.Generic.List[string]
772
+ $script:W.refSeq = 0
773
+ $script:W.totalRefs = 0
774
+ $script:escCache = @{}
775
+ $entry15 = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 3; snapshots = (New-Object System.Collections.Generic.List[object]) }
776
+ $script:W.windows['w1'] = $entry15
777
+ $e15ok = New-MockElement '确定' 'Button' 'Dialog' 'btn-ok' 10 10 60 20
778
+ $e15row = New-MockElement '会话 E 3分钟' 'Button' 'ChatRow' '' 10 40 200 24
779
+ $script:mockAe = New-MockWindow @($e15ok, $e15row)
780
+ $script:W.refs['e9'] = @{
781
+ ref = 'e9'
782
+ windowId = 'w1'
783
+ revision = 3
784
+ ae = $e15ok
785
+ runtimeId = '4242,1'
786
+ controlType = 'Button'
787
+ name = '确定'
788
+ className = 'Dialog'
789
+ automationId = 'btn-ok'
790
+ patterns = @('Invoke')
791
+ enabled = $true
792
+ isOffscreen = $false
793
+ rect = @{ x = 10; y = 10; w = 60; h = 20 }
794
+ depth = 2
795
+ rebound = $false
796
+ }
797
+ $script:W.refOrder.Add('e9') | Out-Null
798
+ $step15a = @{ by = @{ name = '确定'; controlType = 'Button'; automationId = 'btn-ok' }; action = 'invoke' }
799
+ $step15b = @{ by = @{ name = '会话 E 刚刚'; controlType = 'Button' }; action = 'invoke' }
800
+ $step15c = @{ ref = 'e9'; action = 'invoke' }
801
+ $prep15 = Cmd-PrepareBatch @{ windowId = 'w1'; steps = @($step15a, $step15b, $step15c) }
802
+ Assert-Bool '15.1 prepare 全部解析成功' $prep15['allResolved'] $true
803
+ $d15 = $prep15['descriptors']
804
+ Assert-Int '15.2 prepare 返回 3 条描述符' (Get-ItemCount $d15) 3
805
+ $d0 = $d15[0]
806
+ $d1 = $d15[1]
807
+ $d2 = $d15[2]
808
+ Assert-Equal '15.3 strict 步 matchedBy=strict' ([string]($d0['matchedBy'])) 'strict'
809
+ Assert-Equal '15.4 strict 步 ladder=strict' ([string]($d0['ladder'])) 'strict'
810
+ Assert-Score '15.5 strict 步 score=1.0' ([double]($d0['score'])) 1.0
811
+ Assert-Bool '15.6 strict 步 degraded=false' $d0['degraded'] $false
812
+ Assert-Equal '15.7 归一化步 matchedBy=normalizedName' ([string]($d1['matchedBy'])) 'normalizedName'
813
+ Assert-Equal '15.8 归一化步 ladder=normalizedName' ([string]($d1['ladder'])) 'normalizedName'
814
+ Assert-Score '15.9 归一化步 score=0.7' ([double]($d1['score'])) 0.7
815
+ Assert-Bool '15.10 归一化步 degraded=true' $d1['degraded'] $true
816
+ Assert-True '15.11 ref 步没有 matchedBy 字段' (-not $d2.Contains('matchedBy')) 'ref step carries matchedBy'
817
+ Assert-True '15.12 ref 步没有 ladder/score/degraded 字段' (-not ($d2.Contains('ladder') -or $d2.Contains('score') -or $d2.Contains('degraded'))) 'ref step carries locator fields'
818
+ $o15 = ConvertFrom-Json (JsonOf $prep15)
819
+ $j0 = $o15.descriptors[0]
820
+ $j1 = $o15.descriptors[1]
821
+ $j2 = $o15.descriptors[2]
822
+ Assert-Bool '15.13 JSON strict 步 degraded=false' $j0.degraded $false
823
+ Assert-Equal '15.14 JSON 归一化步 matchedBy' ([string]$j1.matchedBy) 'normalizedName'
824
+ Assert-True '15.15 JSON ref 步无 matchedBy' ($null -eq $j2.matchedBy) 'ref step has matchedBy in JSON'
825
+ Write-Host (' prepare[1] normalizedName: ' + (JsonOf $d1))
826
+ Write-Host (' prepare[2] ref (无置信度): ' + (JsonOf $d2))
827
+ $comm15 = Cmd-CommitBatch @{ windowId = 'w1'; revision = 3; steps = @($step15a, $step15b, $step15c) }
828
+ $r15 = $comm15['results']
829
+ Assert-Int '15.16 commit 执行了 3 步' ([int]$comm15['performedCount']) 3
830
+ Assert-Bool '15.17 commit batchOk=true' $comm15['batchOk'] $true
831
+ $r0 = $r15[0]
832
+ $r1 = $r15[1]
833
+ $r2 = $r15[2]
834
+ Assert-Equal '15.18 commit strict 步 matchedBy=strict' ([string]($r0['matchedBy'])) 'strict'
835
+ Assert-Bool '15.19 commit strict 步 degraded=false' $r0['degraded'] $false
836
+ Assert-Equal '15.20 commit 归一化步 matchedBy=normalizedName' ([string]($r1['matchedBy'])) 'normalizedName'
837
+ Assert-Bool '15.21 commit 归一化步 degraded=true' $r1['degraded'] $true
838
+ Assert-Score '15.22 commit 归一化步 score=0.7' ([double]($r1['score'])) 0.7
839
+ Assert-True '15.23 commit ref 步没有 matchedBy 字段' (-not $r2.Contains('matchedBy')) 'ref step carries matchedBy'
840
+ $st15 = (@($r15 | ForEach-Object { [string]$_['status'] }) -join ',')
841
+ Assert-Equal '15.24 commit 三步都 passed' $st15 'passed,passed,passed'
842
+ $o15c = ConvertFrom-Json (JsonOf $comm15)
843
+ $jc2 = $o15c.results[2]
844
+ Assert-True '15.25 JSON commit ref 步无 matchedBy' ($null -eq $jc2.matchedBy) 'ref step has matchedBy in commit JSON'
845
+ Write-Host (' commit[1] normalizedName : ' + (JsonOf $r1))
846
+ Write-Host (' commit[2] ref (无置信度) : ' + (JsonOf $r2))
847
+
848
+ Section '16. Eval-Once scroll_percent_changed:滚动百分比的确定性判据(命中/未命中两例)'
849
+ # mock 元素带 ScrollPattern,Current.VerticalScrollPercent 走 ScriptProperty 读
850
+ # $script:mockScrollPct——同一个"元素"在动作前后能给出不同读数,才能测"滚了但列表没动"。
851
+ # GetPattern mock 只认带 ScrollPattern 属性的元素,其余保持返回 $null(不影响已跑完的用例)。
852
+ $script:mockScrollPct = 20.0
853
+ $scrollCur16 = New-Object PSObject
854
+ $scrollCur16 | Add-Member -MemberType ScriptProperty -Name VerticalScrollPercent -Value { return [double]$script:mockScrollPct }
855
+ $scrollPat16 = New-Object PSObject
856
+ $scrollPat16 | Add-Member -MemberType NoteProperty -Name Current -Value $scrollCur16
857
+ function GetPattern($el, $name) {
858
+ if ($name -eq 'Scroll' -and $null -ne $el.PSObject.Properties['ScrollPattern']) { return $el.ScrollPattern }
859
+ return $null
860
+ }
861
+ $el16 = New-MockElement '列表' 'List' 'ListBox' 'list-1' 10 10 300 400
862
+ $el16 | Add-Member -MemberType NoteProperty -Name ScrollPattern -Value $scrollPat16
863
+ # 复用第 15 节搭好的 $script:W(窗口 w1 revision=3):Resolve-Ref 要求 ref.revision 与窗口一致。
864
+ $script:W.refs['s1'] = @{
865
+ ref = 's1'
866
+ windowId = 'w1'
867
+ revision = 3
868
+ ae = $el16
869
+ runtimeId = '4242,16'
870
+ controlType = 'List'
871
+ name = '列表'
872
+ className = 'ListBox'
873
+ automationId = 'list-1'
874
+ patterns = @('Scroll')
875
+ enabled = $true
876
+ isOffscreen = $false
877
+ rect = @{ x = 10; y = 10; w = 300; h = 400 }
878
+ depth = 1
879
+ rebound = $false
880
+ patCache = @{}
881
+ }
882
+ $entry16 = $script:W.windows['w1']
883
+ $cond16 = @{ type = 'scroll_percent_changed'; ref = 's1'; expect = 5 }
884
+ # 命中:动作前 20%,动作后 40%——差值 20 ≥ expect 5。
885
+ $before16 = Read-ScrollPercent $script:W.refs['s1']
886
+ Assert-Equal '16.1 动作前滚动百分比读数=20' $before16 20
887
+ $script:mockScrollPct = 40.0
888
+ $r16a = Eval-Once 'scroll_percent_changed' $entry16 $cond16 $null $null $before16
889
+ Assert-Bool '16.2 命中(差值 20 ≥ expect 5)' ([bool]$r16a['matched']) $true
890
+ Assert-Equal '16.3 observed=percent=40' ([string]$r16a['observed']) 'percent=40'
891
+ Assert-Equal '16.4 before=percent=20' ([string]$r16a['before']) 'percent=20'
892
+ # 未命中:动作前 40%,"滚了"但读数没动——差值 0 < expect 5,这就是要拦的无效滚动。
893
+ $script:mockScrollPct = 40.0
894
+ $before16b = Read-ScrollPercent $script:W.refs['s1']
895
+ Assert-Equal '16.5 动作前滚动百分比读数=40' $before16b 40
896
+ $r16b = Eval-Once 'scroll_percent_changed' $entry16 $cond16 $null $null $before16b
897
+ Assert-Bool '16.6 未命中(差值 0 < expect 5)' ([bool]$r16b['matched']) $false
898
+ Assert-Equal '16.7 observed=percent=40' ([string]$r16b['observed']) 'percent=40'
899
+
900
+
901
+
902
+
903
+ Section '17. snapshot 快照:一次性子树(GetUpdatedCache)与 walker 回退,契约不变(P-01)'
904
+ Reset-WorkerState
905
+ $g17 = New-MockSnapElement '孙' 'Button' @()
906
+ $c17a = New-MockSnapElement '子甲' 'Button' @($g17)
907
+ $c17b = New-MockSnapElement '子乙' 'Edit' @()
908
+ $root17 = New-MockSnapElement '根窗' 'Window' @($c17a, $c17b)
909
+ $entry17 = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
910
+ $script:W.windows['w1'] = $entry17
911
+ $script:mockAe = New-MockSnapshotWindow $root17
912
+ $snap17 = Build-Snapshot $entry17 @{ windowId = 'w1' }
913
+ Assert-Int '17.1 一次性路径节点数=整树 4 节点' ([int]$snap17['nodeCount']) 4
914
+ Assert-Int '17.2 visited=4' ([int]$snap17['visited']) 4
915
+ Assert-Bool '17.3 truncated=false' ([bool]$snap17['truncated']) $false
916
+ Assert-Int '17.4 revision 已 bump' ([int]$snap17['revision']) 2
917
+ Assert-True '17.5 无 partialReason' (-not $snap17.Contains('partialReason')) ('partialReason=' + [string]$snap17['partialReason'])
918
+ Assert-Int '17.6 ref 登记数=节点数' ([int]$script:W.refs.Count) 4
919
+ Assert-Int '17.7 refOrder 登记数=节点数' ([int]$script:W.refOrder.Count) 4
920
+ Assert-True '17.8 GetUpdatedCache 恰好调用一次(一次性路径生效)' ([int]$script:mockAe.GetUpdatedCalls -eq 1) ('calls=' + $script:mockAe.GetUpdatedCalls)
921
+ $n17 = $snap17['nodes']
922
+ Assert-Equal '17.9 树序首节点=根' ([string]$n17[0]['name']) '根窗'
923
+ Assert-Equal '17.10 首节点 ref=e1' ([string]$n17[0]['ref']) 'e1'
924
+ Assert-Equal '17.11 第二节点=子甲' ([string]$n17[1]['name']) '子甲'
925
+ Assert-Int '17.12 子甲 depth=1' ([int]$n17[1]['depth']) 1
926
+ Assert-Equal '17.13 第三节点=孙' ([string]$n17[2]['name']) '孙'
927
+ Assert-Int '17.14 孙 depth=2' ([int]$n17[2]['depth']) 2
928
+ Assert-Equal '17.15 第四节点=子乙' ([string]$n17[3]['name']) '子乙'
929
+ Assert-Equal '17.16 节点 patterns 来自 mock' ((@($n17[0]['patterns']) -join ',')) 'Invoke'
930
+ Assert-Equal '17.17 ref 的 runtimeId 来自缓存' ([string]$script:W.refs['e2']['runtimeId']) '77,102'
931
+ Assert-True '17.18 节点字段齐全' (($n17[1].Contains('controlType') -and $n17[1].Contains('automationId') -and $n17[1].Contains('enabled') -and $n17[1].Contains('isOffscreen') -and $n17[1].Contains('rect'))) 'missing node fields'
932
+
933
+ # maxNodes 截断:emit 层契约不变(truncated + partialReason['maxNodes'],ref 只铸已产出节点)。
934
+ Reset-WorkerState
935
+ $entry17b = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
936
+ $script:W.windows['w1'] = $entry17b
937
+ $script:mockAe = New-MockSnapshotWindow $root17
938
+ $snap17b = Build-Snapshot $entry17b @{ windowId = 'w1'; maxNodes = 2 }
939
+ Assert-Int '17.19 maxNodes=2 截断到 2 节点' ([int]$snap17b['nodeCount']) 2
940
+ Assert-Bool '17.20 truncated=true' ([bool]$snap17b['truncated']) $true
941
+ Assert-True '17.21 partialReason 含 maxNodes' (([string]$snap17b['partialReason']).IndexOf('maxNodes') -ge 0) ('partialReason=' + [string]$snap17b['partialReason'])
942
+ Assert-Int '17.22 ref 只铸已产出节点' ([int]$script:W.refs.Count) 2
943
+
944
+ # maxDepth 截断:一次性路径在导航计数阶段剪枝,标记同 walker。
945
+ Reset-WorkerState
946
+ $entry17c = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
947
+ $script:W.windows['w1'] = $entry17c
948
+ $script:mockAe = New-MockSnapshotWindow $root17
949
+ $snap17c = Build-Snapshot $entry17c @{ windowId = 'w1'; maxDepth = 1 }
950
+ Assert-Int '17.23 maxDepth=1 收 3 节点(depth 0..1,孙不入树)' ([int]$snap17c['nodeCount']) 3
951
+ Assert-Bool '17.24 truncated=true' ([bool]$snap17c['truncated']) $true
952
+ Assert-True '17.25 partialReason 含 maxDepth' (([string]$snap17c['partialReason']).IndexOf('maxDepth') -ge 0) ('partialReason=' + [string]$snap17c['partialReason'])
953
+ $n17c = $snap17c['nodes']
954
+ Assert-True '17.23b 孙(depth=2)未入树' (($n17c | Where-Object { [string]$_['name'] -eq '孙' } | Measure-Object).Count -eq 0) 'grandchild emitted'
955
+
956
+ # emit 过滤在内存层照旧(filter 只减 emit,不减 visited)。
957
+ Reset-WorkerState
958
+ $entry17d = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
959
+ $script:W.windows['w1'] = $entry17d
960
+ $script:mockAe = New-MockSnapshotWindow $root17
961
+ $snap17d = Build-Snapshot $entry17d @{ windowId = 'w1'; filter = @{ controlType = 'Button' } }
962
+ Assert-Int '17.26 filter=Button 只 emit 两个 Button' ([int]$snap17d['nodeCount']) 2
963
+ Assert-Int '17.27 visited 不受 filter 影响' ([int]$snap17d['visited']) 4
964
+
965
+ # walker 回退路径:窗口对象没有 GetUpdatedCache(mock 元素调用抛错)→ 沿用 per-child walker,
966
+ # 契约一致。root17 本身就是快照 mock 元素形状(Current/Cached/Children 齐全,无 GetUpdatedCache)。
967
+ Reset-WorkerState
968
+ $entry17e = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 1; snapshots = (New-Object System.Collections.Generic.List[object]) }
969
+ $script:W.windows['w1'] = $entry17e
970
+ $script:mockAe = $root17
971
+ $snap17e = Build-Snapshot $entry17e @{ windowId = 'w1' }
972
+ Assert-Int '17.28 回退路径节点数=4' ([int]$snap17e['nodeCount']) 4
973
+ Assert-Bool '17.29 回退路径 truncated=false' ([bool]$snap17e['truncated']) $false
974
+ Assert-Int '17.30 回退路径 ref 登记数=4' ([int]$script:W.refs.Count) 4
975
+ Assert-True '17.31 回退路径无 childProviderError' (([string]$snap17e['partialReason']).IndexOf('childProviderError') -lt 0) ('partialReason=' + [string]$snap17e['partialReason'])
976
+
977
+ Section '18. find_text:缓存扫描契约(命中/ref/nth/by/matchedTotal/truncated)(P-02)'
978
+ Reset-WorkerState
979
+ $ft1 = New-MockSnapElement '保存' 'Button' @()
980
+ $ft2 = New-MockSnapElement '保存' 'Button' @()
981
+ $ft3 = New-MockSnapElement '保存的草稿' 'Text' @()
982
+ $root18 = New-MockSnapElement '' 'Window' @($ft1, $ft2, $ft3)
983
+ $entry18 = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 5; snapshots = (New-Object System.Collections.Generic.List[object]) }
984
+ $script:W.windows['w1'] = $entry18
985
+ $script:mockAe = New-MockSnapshotWindow $root18 @($root18, $ft1, $ft2, $ft3)
986
+ $ft = Cmd-FindText @{ windowId = 'w1'; text = '保存' }
987
+ $ftMatches = $ft['matches']
988
+ Assert-Int '18.1 count=3' ([int]$ft['count']) 3
989
+ Assert-Int '18.2 matchedTotal=3(诚实总数)' ([int]$ft['matchedTotal']) 3
990
+ Assert-Int '18.3 scanned=4(含根)' ([int]$ft['scanned']) 4
991
+ Assert-Bool '18.4 truncated=false' ([bool]$ft['truncated']) $false
992
+ Assert-True '18.5 首项带 ref' ($null -ne $ftMatches[0]['ref']) 'first match has no ref'
993
+ Assert-Equal '18.6 首项 by.controlType=Button' ([string]$ftMatches[0]['by']['controlType']) 'Button'
994
+ Assert-Int '18.7 次同名项 nth=2' ([int]$ftMatches[1]['nth']) 2
995
+ Assert-True '18.8 by 携带 nth=2(回放可寻址)' ([int]$ftMatches[1]['by']['nth'] -eq 2) 'by.nth missing'
996
+ Assert-Int '18.9 首项 center.x=55(rect 中心)' ([int]$ftMatches[0]['center']['x']) 55
997
+ Assert-True '18.10 结果带 ms(采集耗时)' ([int]$ft['ms'] -ge 0) ('ms=' + [string]$ft['ms'])
998
+ $ft1b = Cmd-FindText @{ windowId = 'w1'; text = '保存'; max = 1 }
999
+ Assert-Int '18.11 max=1 只返回 1 个' ([int]$ft1b['count']) 1
1000
+ Assert-Bool '18.12 truncated=true' ([bool]$ft1b['truncated']) $true
1001
+ Assert-Int '18.13 matchedTotal 仍=3' ([int]$ft1b['matchedTotal']) 3
1002
+ $ft0 = Cmd-FindText @{ windowId = 'w1'; text = '不存在的词' }
1003
+ Assert-Int '18.14 无命中 count=0' ([int]$ft0['count']) 0
1004
+ Assert-Int '18.15 无命中 matchedTotal=0' ([int]$ft0['matchedTotal']) 0
1005
+ Assert-Int '18.16 ref 表登记=3+1(max 截断的不铸)' ([int]$script:W.refs.Count) 4
1006
+
1007
+ Section '19. commit_batch:批次前后顶层窗口 diff(newWindows 两态 + 指示层 pid 排除)(P-09)'
1008
+ Reset-WorkerState
1009
+ $entry19 = @{ id = 'w1'; hwnd = 4200; pid = 4242; class = 'ChatWnd'; revision = 3; snapshots = (New-Object System.Collections.Generic.List[object]) }
1010
+ $script:W.windows['w1'] = $entry19
1011
+ $el19 = New-MockElement '确定' 'Button' 'Dialog' 'btn-ok' 10 10 60 20
1012
+ $script:W.refs['e9'] = @{
1013
+ ref = 'e9'
1014
+ windowId = 'w1'
1015
+ revision = 3
1016
+ ae = $el19
1017
+ runtimeId = '4242,1'
1018
+ controlType = 'Button'
1019
+ name = '确定'
1020
+ className = 'Dialog'
1021
+ automationId = 'btn-ok'
1022
+ patterns = @('Invoke')
1023
+ enabled = $true
1024
+ isOffscreen = $false
1025
+ rect = @{ x = 10; y = 10; w = 60; h = 20 }
1026
+ depth = 2
1027
+ rebound = $false
1028
+ patCache = @{}
1029
+ }
1030
+ $script:W.refOrder.Add('e9') | Out-Null
1031
+ $step19 = @{ ref = 'e9'; action = 'invoke' }
1032
+ $m19a = New-MockRootWindow 4200 4242 '目标窗'
1033
+ $m19b = New-MockRootWindow 9999 4243 '弹出对话框'
1034
+ # RootWindows mock 按调用奇偶切 before/after:commit A 前后同集(无新窗口);commit B 的 after
1035
+ # 多出 9999(构造「新窗口」)。
1036
+ $script:mockRootBefore = @($m19a)
1037
+ $script:mockRootAfter = @($m19a)
1038
+ $comm19a = Cmd-CommitBatch @{ windowId = 'w1'; revision = 3; steps = @($step19) }
1039
+ Assert-Bool '19.1 无新窗口时结果无 newWindows 键' (-not $comm19a.Contains('newWindows')) $true
1040
+ $script:mockRootAfter = @($m19a, $m19b)
1041
+ $comm19b = Cmd-CommitBatch @{ windowId = 'w1'; revision = 3; steps = @($step19) }
1042
+ Assert-Bool '19.2 有新窗口时带 newWindows 键' $comm19b.Contains('newWindows') $true
1043
+ $nw19 = $comm19b['newWindows']
1044
+ Assert-Int '19.3 newWindows 一条' ([int]$nw19.Count) 1
1045
+ Assert-Equal '19.4 新窗口标题' ([string]$nw19[0]['title']) '弹出对话框'
1046
+ Assert-Int '19.5 新窗口 pid' ([int]$nw19[0]['pid']) 4243
1047
+ Assert-Int '19.6 新窗口 hwnd' ([int]$nw19[0]['hwnd']) 9999
1048
+ $script:mockRootAfter = @($m19a, $m19b)
1049
+ $comm19c = Cmd-CommitBatch @{ windowId = 'w1'; revision = 3; steps = @($step19); indicatorPid = 4243 }
1050
+ Assert-Bool '19.7 指示层 pid 被排除(无 newWindows 键)' (-not $comm19c.Contains('newWindows')) $true
1051
+ $json19 = JsonOf $comm19b
1052
+ $obj19 = ConvertFrom-Json $json19
1053
+ Assert-Equal '19.8 JSON newWindows[0].title' ([string]$obj19.newWindows[0].title) '弹出对话框'
1054
+
1055
+ Section '20. type_text:via 非法值负测(不触桌面)(P-05)'
1056
+ Reset-WorkerState
1057
+ $code20 = ''
1058
+ try { Cmd-TypeText @{ text = 'hi'; via = 'mouse' } } catch { $c20, $m20 = Split-Err $_; $code20 = $c20 }
1059
+ Assert-Equal '20.1 via=mouse 报 bad_arg' $code20 'bad_arg'
1060
+ $code20 = ''
1061
+ try { $r20 = Cmd-TypeText @{ text = 'hi' } } catch { $code20 = 'threw' }
1062
+ Assert-Equal '20.2 缺省 via=keyboard 正常([Native] 桩,不真发输入)' $code20 ''
1063
+ Assert-Int '20.3 键盘路径 chars=2' ([int]$r20['chars']) 2
1064
+
1065
+ # ================================================================ 汇总
1066
+ $total = $script:pass + $script:fail
1067
+ Write-Host ''
1068
+ Write-Host ('==== ' + $script:pass + '/' + $total + ' passed, ' + $script:fail + ' failed ====')
1069
+ if ($script:fail -gt 0) {
1070
+ Write-Host '失败明细:'
1071
+ foreach ($f in $script:failures) { Write-Host (' - ' + $f) }
1072
+ exit 1
1073
+ }
1074
+ exit 0