-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcts_test.go
More file actions
414 lines (375 loc) · 11.1 KB
/
Copy pathcts_test.go
File metadata and controls
414 lines (375 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package jsonpath
import (
"encoding/json"
"fmt"
"os"
"reflect"
"sort"
"strings"
"testing"
)
// CTS test suite structures
type ctsTest struct {
Name string `json:"name"`
Selector string `json:"selector"`
Document json.RawMessage `json:"document"`
Result json.RawMessage `json:"result"`
Results []json.RawMessage `json:"results"`
ResultPaths []string `json:"result_paths"`
InvalidSelector bool `json:"invalid_selector"`
Tags []string `json:"tags"`
}
type ctsSuite struct {
Description string `json:"description"`
Tests []ctsTest `json:"tests"`
}
func loadCTS(t *testing.T) *ctsSuite {
t.Helper()
data, err := os.ReadFile("cts.json")
if err != nil {
t.Skip("cts.json not found, skipping CTS tests")
}
var suite ctsSuite
if err := json.Unmarshal(data, &suite); err != nil {
t.Fatalf("Failed to parse cts.json: %v", err)
}
return &suite
}
// normalizeForCompare recursively normalizes JSON values for comparison
func normalizeForCompare(v interface{}) interface{} {
switch val := v.(type) {
case []interface{}:
normalized := make([]interface{}, len(val))
for i, elem := range val {
normalized[i] = normalizeForCompare(elem)
}
return normalized
case map[string]interface{}:
normalized := make(map[string]interface{}, len(val))
for k, v := range val {
normalized[k] = normalizeForCompare(v)
}
return normalized
case float64:
// Normalize integer-valued floats
if val == float64(int64(val)) {
return val
}
return val
default:
return v
}
}
// wrapInNodelist wraps the Query() result into a nodelist (array) format
// that matches the CTS expected output.
// Query() returns a NodeList ([]Node), each Node having Location and Value.
// CTS expects a flat array of values (not Node structs).
func wrapInNodelist(result interface{}) []interface{} {
if result == nil {
return []interface{}{}
}
switch v := result.(type) {
case NodeList:
out := make([]interface{}, len(v))
for i, n := range v {
out[i] = n.Value
}
return out
case []interface{}:
return v
default:
return []interface{}{result}
}
}
// parseCTSResult parses the expected result from CTS JSON
func parseCTSResult(raw json.RawMessage) (interface{}, error) {
if len(raw) == 0 {
return nil, nil
}
var result interface{}
if err := json.Unmarshal(raw, &result); err != nil {
return nil, fmt.Errorf("failed to parse expected result: %v", err)
}
return normalizeForCompare(result), nil
}
// deepEqual compares two values for deep equality
func deepEqual(a, b interface{}) bool {
return reflect.DeepEqual(normalizeForCompare(a), normalizeForCompare(b))
}
// resultMatchesAny checks if the actual nodelist matches any of the valid non-deterministic results
func resultMatchesAny(actualNodelist []interface{}, expectedResults []json.RawMessage) bool {
for _, raw := range expectedResults {
expected, err := parseCTSResult(raw)
if err != nil {
continue
}
expectedArr, ok := expected.([]interface{})
if !ok {
continue
}
if nodelistsEqual(actualNodelist, expectedArr) {
return true
}
}
return false
}
// nodelistsEqual compares two nodelists, handling non-deterministic object member order
func nodelistsEqual(actual, expected []interface{}) bool {
if len(actual) != len(expected) {
return false
}
for i := range actual {
if !deepEqual(actual[i], expected[i]) {
return false
}
}
return true
}
func TestCTS(t *testing.T) {
suite := loadCTS(t)
var pass, fail, skip, invalidPass, invalidFail int
var failures []string
var failureCategories map[string][]string = make(map[string][]string)
for _, tc := range suite.Tests {
t.Run(tc.Name, func(t *testing.T) {
// Handle invalid selector tests
if tc.InvalidSelector {
// Some invalid selector tests have no document
if len(tc.Document) > 0 {
var doc interface{}
_ = json.Unmarshal(tc.Document, &doc)
_, err := Query(doc, tc.Selector)
if err != nil {
invalidPass++
} else {
invalidFail++
failures = append(failures, fmt.Sprintf("FAIL [invalid_not_caught] %s: selector %q should be invalid but got result", tc.Name, tc.Selector))
cat := extractCategory(tc.Name)
failureCategories[cat] = append(failureCategories[cat], tc.Selector)
}
} else {
// No document - just test that the selector is rejected
_, err := Query(map[string]interface{}{}, tc.Selector)
if err != nil {
invalidPass++
} else {
invalidFail++
failures = append(failures, fmt.Sprintf("FAIL [invalid_not_caught] %s: selector %q should be invalid but got result", tc.Name, tc.Selector))
cat := extractCategory(tc.Name)
failureCategories[cat] = append(failureCategories[cat], tc.Selector)
}
}
return
}
// Parse the input document
var doc interface{}
if err := json.Unmarshal(tc.Document, &doc); err != nil {
t.Fatalf("Failed to parse document: %v", err)
}
// Run the query
actual, err := Query(doc, tc.Selector)
if err != nil {
// Valid selector but our implementation errored
fail++
failures = append(failures, fmt.Sprintf("FAIL [error] %s: selector %q got error: %v", tc.Name, tc.Selector, err))
cat := extractCategory(tc.Name)
failureCategories[cat] = append(failureCategories[cat], tc.Selector)
return
}
// Wrap actual result into nodelist format
actualNodelist := wrapInNodelist(actual)
// Check against expected result(s)
if len(tc.Results) > 0 {
// Non-deterministic result - must match at least one alternative
if resultMatchesAny(actualNodelist, tc.Results) {
pass++
} else {
fail++
var expectedStrs []string
for _, raw := range tc.Results {
expectedStrs = append(expectedStrs, string(raw))
}
failures = append(failures, fmt.Sprintf("FAIL [mismatch] %s: selector %q\n expected one of: %s\n got: %v", tc.Name, tc.Selector, strings.Join(expectedStrs, " | "), actualNodelist))
cat := extractCategory(tc.Name)
failureCategories[cat] = append(failureCategories[cat], tc.Selector)
}
} else if len(tc.Result) > 0 {
// Deterministic result
expected, parseErr := parseCTSResult(tc.Result)
if parseErr != nil {
skip++
t.Logf("SKIP: failed to parse expected result: %v", parseErr)
return
}
expectedArr, ok := expected.([]interface{})
if !ok {
skip++
t.Logf("SKIP: expected result is not an array")
return
}
if nodelistsEqual(actualNodelist, expectedArr) {
pass++
} else {
fail++
failures = append(failures, fmt.Sprintf("FAIL [mismatch] %s: selector %q\n expected: %v\n got: %v", tc.Name, tc.Selector, expectedArr, actualNodelist))
cat := extractCategory(tc.Name)
failureCategories[cat] = append(failureCategories[cat], tc.Selector)
}
} else {
skip++
}
})
}
// Print summary
t.Logf("\n========== CTS RESULTS ==========")
t.Logf("Valid selectors - Pass: %d, Fail: %d, Skip: %d", pass, fail, skip)
t.Logf("Invalid selectors - Correctly rejected: %d, Not caught: %d", invalidPass, invalidFail)
total := pass + fail + skip + invalidPass + invalidFail
rate := float64(0)
if pass+fail+invalidPass+invalidFail > 0 {
rate = float64(pass+invalidPass) / float64(pass+fail+invalidPass+invalidFail) * 100
}
t.Logf("Total: %d/%d passed (%.1f%%)", pass+invalidPass, total, rate)
if len(failureCategories) > 0 {
t.Logf("\n========== FAILURES BY CATEGORY ==========")
var cats []string
for c := range failureCategories {
cats = append(cats, c)
}
sort.Strings(cats)
for _, cat := range cats {
sels := failureCategories[cat]
t.Logf("\n[%s] (%d failures)", cat, len(sels))
limit := len(sels)
if limit > 10 {
limit = 10
}
for i := 0; i < limit; i++ {
t.Logf(" %s", sels[i])
}
if len(sels) > 10 {
t.Logf(" ... and %d more", len(sels)-10)
}
}
}
if len(failures) > 0 {
t.Logf("\n========== DETAILED FAILURES (first 30) ==========")
limit := len(failures)
if limit > 30 {
limit = 30
}
for i := 0; i < limit; i++ {
t.Log(failures[i])
}
if len(failures) > 30 {
t.Logf("... and %d more failures", len(failures)-30)
}
}
}
func extractCategory(name string) string {
for _, prefix := range []string{"basic", "filter", "index", "name selector", "slice", "functions", "whitespace", "descendant"} {
if strings.HasPrefix(name, prefix) {
return prefix
}
}
return "other"
}
// TestCTSSummary runs the CTS and produces a categorized summary
func TestCTSSummary(t *testing.T) {
suite := loadCTS(t)
type categoryStats struct {
total int
pass int
fail int
skip int
invPass int
invFail int
}
categories := make(map[string]*categoryStats)
for _, tc := range suite.Tests {
cat := extractCategory(tc.Name)
stats, ok := categories[cat]
if !ok {
stats = &categoryStats{}
categories[cat] = stats
}
stats.total++
// Handle invalid selector tests
if tc.InvalidSelector {
if len(tc.Document) > 0 {
var doc interface{}
_ = json.Unmarshal(tc.Document, &doc)
_, err := Query(doc, tc.Selector)
if err != nil {
stats.invPass++
} else {
stats.invFail++
}
} else {
_, err := Query(map[string]interface{}{}, tc.Selector)
if err != nil {
stats.invPass++
} else {
stats.invFail++
}
}
continue
}
var doc interface{}
if err := json.Unmarshal(tc.Document, &doc); err != nil {
stats.skip++
continue
}
actual, err := Query(doc, tc.Selector)
if err != nil {
stats.fail++
continue
}
actualNodelist := wrapInNodelist(actual)
if len(tc.Results) > 0 {
if resultMatchesAny(actualNodelist, tc.Results) {
stats.pass++
} else {
stats.fail++
}
} else if len(tc.Result) > 0 {
expected, parseErr := parseCTSResult(tc.Result)
if parseErr != nil {
stats.skip++
} else if expectedArr, ok := expected.([]interface{}); ok && nodelistsEqual(actualNodelist, expectedArr) {
stats.pass++
} else {
stats.fail++
}
} else {
stats.skip++
}
}
// Print categorized summary
t.Logf("\n========== CTS SUMMARY BY CATEGORY ==========")
t.Logf("%-20s %5s %5s %5s %5s %5s %5s %6s", "Category", "Total", "Pass", "Fail", "Skip", "InvOk", "InvFl", "Rate")
var cats []string
for c := range categories {
cats = append(cats, c)
}
sort.Strings(cats)
totalPass, totalFail, totalSkip, totalInvPass, totalInvFail := 0, 0, 0, 0, 0
for _, c := range cats {
s := categories[c]
rate := float64(0)
if s.pass+s.fail+s.invPass+s.invFail > 0 {
rate = float64(s.pass+s.invPass) / float64(s.pass+s.fail+s.invPass+s.invFail) * 100
}
t.Logf("%-20s %5d %5d %5d %5d %5d %5d %5.1f%%", c, s.total, s.pass, s.fail, s.skip, s.invPass, s.invFail, rate)
totalPass += s.pass
totalFail += s.fail
totalSkip += s.skip
totalInvPass += s.invPass
totalInvFail += s.invFail
}
totalRate := float64(0)
if totalPass+totalFail+totalInvPass+totalInvFail > 0 {
totalRate = float64(totalPass+totalInvPass) / float64(totalPass+totalFail+totalInvPass+totalInvFail) * 100
}
t.Logf("%-20s %5d %5d %5d %5d %5d %5d %5.1f%%", "TOTAL", len(suite.Tests), totalPass, totalFail, totalSkip, totalInvPass, totalInvFail, totalRate)
}