Repository navigation
Expand file tree
/
Copy pathparser_internal_test.go
More file actions
509 lines (472 loc) · 16 KB
/
Copy pathparser_internal_test.go
File metadata and controls
509 lines (472 loc) · 16 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package publiccode
import (
"errors"
"os"
"strings"
"testing"
"github.com/goccy/go-yaml/parser"
)
func TestGetPositionInFileEmptyDocs(t *testing.T) {
// An empty YAML file results in a parsed file with no docs.
file, err := parser.ParseBytes([]byte(""), 0)
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}
line, col := getPositionInFile("someKey", file)
if line != 0 || col != 0 {
t.Errorf("expected 0,0 for empty file, got %d,%d", line, col)
}
}
func TestGetPositionInFileNilBody(t *testing.T) {
// Parse YAML that produces a doc with nil body.
// A YAML file with only comments has a doc with nil Body.
file, err := parser.ParseBytes([]byte("# just a comment\n"), 0)
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}
line, col := getPositionInFile("someKey", file)
if line != 0 || col != 0 {
t.Errorf("expected 0,0 for comment-only file, got %d,%d", line, col)
}
}
func TestDecodeUnknownField(t *testing.T) {
// Parse a YAML with an unknown field, which should be caught by
// the decode function as an UnknownFieldError.
yaml := `publiccodeYmlVersion: "0"
name: test
unknownField: value
`
file, err := parser.ParseBytes([]byte(yaml), 0)
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}
v0 := &PublicCodeV0{}
results, _ := decode([]byte(yaml), v0, file)
if results == nil {
t.Error("expected error for unknown field")
}
}
func TestDecodeWrongType(t *testing.T) {
// Parse YAML where a field has wrong type (e.g. name is a list).
yaml := `publiccodeYmlVersion: "0"
name:
- item1
- item2
`
file, err := parser.ParseBytes([]byte(yaml), 0)
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}
v0 := &PublicCodeV0{}
results, _ := decode([]byte(yaml), v0, file)
if results == nil {
t.Error("expected error for wrong type")
}
}
func TestDecodeReportsEveryUnknownKey(t *testing.T) {
tests := map[string]struct {
yaml string
fixture string
want ValidationResults
}{
"keys in a flow mapping": {
yaml: `publiccodeYmlVersion: "0"
legal: {license: MIT, b: 1, a: 2}
`,
want: ValidationResults{
ValidationError{File: "", Key: "legal.b", Description: `unknown field "b"`, Line: 2, Column: 23},
ValidationError{File: "", Key: "legal.a", Description: `unknown field "a"`, Line: 2, Column: 29},
},
},
"key of an anchor used twice": {
yaml: `publiccodeYmlVersion: "0"
fundedBy:
- &org {uri: "urn:x-test:a", foo: 1}
- *org
`,
want: ValidationResults{
ValidationError{File: "", Key: "fundedBy[0].foo", Description: `unknown field "foo"`, Line: 3, Column: 32},
},
},
"key brought in by a merge key": {
yaml: `publiccodeYmlVersion: "0"
x: &base {type: internal, bar: 1}
maintenance:
<<: *base
baz: 2
`,
want: ValidationResults{
ValidationError{File: "", Key: "x", Description: `unknown field "x"`, Line: 2, Column: 1},
ValidationError{File: "", Key: "maintenance.bar", Description: `unknown field "bar"`, Line: 2, Column: 27},
ValidationError{File: "", Key: "maintenance.baz", Description: `unknown field "baz"`, Line: 5, Column: 3},
},
},
"anchor holding an alias of itself": {
yaml: `publiccodeYmlVersion: "0"
fundedBy: &x [*x]
foo: 1
`,
want: ValidationResults{
ValidationError{File: "", Key: "foo", Description: `unknown field "foo"`, Line: 3, Column: 1},
ValidationError{File: "", Key: "fundedBy", Description: "wrong type for this field", Line: 2, Column: 1},
},
},
"mapping merging an alias of itself": {
yaml: `publiccodeYmlVersion: "0"
maintenance: &x {type: internal, foo: 1, <<: *x}
`,
want: ValidationResults{
ValidationError{File: "", Key: "maintenance.foo", Description: `unknown field "foo"`, Line: 2, Column: 34},
newValidationError("", "cannot find anchor by alias name x"),
},
},
"tagged, quoted and anchored keys": {
yaml: `publiccodeYmlVersion: "0"
!!str zzTagged: 1
"zzQuoted": 2
&k zzAnchored: 3
!!str 4: 4
`,
want: ValidationResults{
ValidationError{File: "", Key: "zzTagged", Description: `unknown field "zzTagged"`, Line: 2, Column: 1},
ValidationError{File: "", Key: "zzQuoted", Description: `unknown field "zzQuoted"`, Line: 3, Column: 1},
ValidationError{File: "", Key: "zzAnchored", Description: `unknown field "zzAnchored"`, Line: 4, Column: 1},
ValidationError{File: "", Key: "4", Description: `unknown field "4"`, Line: 5, Column: 1},
},
},
"keys that are not strings": {
fixture: "testdata/decode/non_string_keys.yml",
want: ValidationResults{
ValidationError{File: "", Key: "true", Description: `unknown field "true"`, Line: 3, Column: 1},
ValidationError{File: "", Key: "5", Description: `unknown field "5"`, Line: 4, Column: 1},
ValidationError{File: "", Key: "1.5", Description: `unknown field "1.5"`, Line: 5, Column: 1},
ValidationError{File: "", Key: "~", Description: `unknown field "~"`, Line: 6, Column: 1},
ValidationError{File: "", Key: "!!int 6", Description: `unknown field "!!int 6"`, Line: 7, Column: 1},
ValidationError{File: "", Key: "x", Description: `unknown field "x"`, Line: 8, Column: 1},
ValidationError{File: "", Key: "7", Description: `unknown field "7"`, Line: 9, Column: 1},
ValidationError{File: "", Key: "legal.null", Description: `unknown field "null"`, Line: 11, Column: 3},
},
},
"explicit and block scalar keys": {
fixture: "testdata/decode/explicit_and_block_scalar_keys.yml",
want: ValidationResults{
ValidationError{File: "", Key: "5", Description: `unknown field "5"`, Line: 13, Column: 1},
ValidationError{File: "", Key: "!!int 6", Description: `unknown field "!!int 6"`, Line: 15, Column: 1},
},
},
"block scalar keys that are not fields": {
fixture: "testdata/decode/block_scalar_unknown_keys.yml",
want: ValidationResults{
ValidationError{File: "", Key: "zz", Description: `unknown field "zz"`, Line: 3, Column: 1},
ValidationError{File: "", Key: "!!int 7", Description: `unknown field "!!int 7"`, Line: 6, Column: 1},
},
},
"tagged keys that name a field": {
fixture: "testdata/decode/tagged_field_names.yml",
want: ValidationResults{
ValidationError{File: "", Key: "!!int applicationSuite", Description: `unknown field "!!int applicationSuite"`, Line: 3, Column: 1},
ValidationError{File: "", Key: "!!null roadmap", Description: `unknown field "!!null roadmap"`, Line: 4, Column: 1},
ValidationError{File: "", Key: "!!bool landingURL", Description: `unknown field "!!bool landingURL"`, Line: 5, Column: 1},
ValidationError{File: "", Key: "legal.!!float license", Description: `unknown field "!!float license"`, Line: 7, Column: 3},
},
},
"key next to a wrong type": {
yaml: `publiccodeYmlVersion: "0"
name: [a]
foo: 1
`,
want: ValidationResults{
ValidationError{File: "", Key: "foo", Description: `unknown field "foo"`, Line: 3, Column: 1},
ValidationError{File: "", Key: "name", Description: "must be a string", Line: 2, Column: 1},
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
if test.fixture != "" {
data, err := os.ReadFile(test.fixture)
if err != nil {
t.Fatal(err)
}
test.yaml = string(data)
}
file, err := parser.ParseBytes([]byte(test.yaml), 0)
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}
got, _ := decode([]byte(test.yaml), &PublicCodeV0{}, file)
if got.Error() != test.want.Error() {
t.Errorf("got:\n%v\nwant:\n%v", got, test.want)
}
})
}
}
func TestDecodeMergeKeyOverride(t *testing.T) {
tests := map[string]struct {
yaml string
name string
want ValidationResults
}{
"key after the merge key": {
yaml: `publiccodeYmlVersion: "0"
description:
en-GB: &d {localisedName: GB, shortDescription: short}
en-US:
<<: *d
localisedName: US
`,
name: "US",
},
"key after a merge of merges": {
yaml: `publiccodeYmlVersion: "0"
x: &a {localisedName: A}
description:
en-GB: &d {<<: *a, shortDescription: short}
en-US: {<<: *d, localisedName: US}
`,
name: "US",
want: ValidationResults{
ValidationError{File: "", Key: "x", Description: `unknown field "x"`, Line: 2, Column: 1},
},
},
"key before the merge key": {
yaml: `publiccodeYmlVersion: "0"
description:
en-GB: &d {localisedName: GB, shortDescription: short}
en-US:
localisedName: US
<<: *d
`,
name: "GB",
want: ValidationResults{
ValidationError{File: "", Key: "description.en-US.localisedName", Description: `set before a "<<" merge key that sets it too, write "<<" first`, Line: 5, Column: 1},
},
},
"key before a merged list": {
yaml: `publiccodeYmlVersion: "0"
description:
en-GB: &d {localisedName: GB, shortDescription: short}
en-US: {localisedName: US, <<: [*d]}
`,
want: ValidationResults{
ValidationError{File: "", Key: "description.en-US", Description: "wrong type for this field", Line: 4, Column: 3},
ValidationError{File: "", Key: "description.en-US.localisedName", Description: `set before a "<<" merge key that sets it too, write "<<" first`, Line: 4, Column: 1},
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
file, err := parser.ParseBytes([]byte(test.yaml), 0)
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}
v0 := &PublicCodeV0{}
got, _ := decode([]byte(test.yaml), v0, file)
if got.Error() != test.want.Error() {
t.Errorf("got:\n%v\nwant:\n%v", got, test.want)
}
if test.name == "" {
return
}
desc := v0.Description["en-US"]
if desc.LocalisedName == nil || *desc.LocalisedName != test.name {
t.Errorf("got localisedName %v, want %q", desc.LocalisedName, test.name)
}
if desc.ShortDescription != "short" {
t.Errorf("got shortDescription %q, want the merged one", desc.ShortDescription)
}
})
}
}
func TestToURLLocalPath(t *testing.T) {
// toURL with a local file path should return a file:// URL.
u, err := toURL("./testdata/v0/valid/valid.yml")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if u.Scheme != "file" {
t.Errorf("expected file scheme, got %q", u.Scheme)
}
}
func TestToURLHTTPS(t *testing.T) {
u, err := toURL("https://example.com/publiccode.yml")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if u.Host != "example.com" {
t.Errorf("unexpected host: %s", u.Host)
}
}
func TestFindKeyPosNilNode(t *testing.T) {
line, col := findKeyPos(nil, []string{"key"})
if line != 0 || col != 0 {
t.Errorf("expected 0,0 for nil node, got %d,%d", line, col)
}
}
func TestFindKeyAtLineNilNode(t *testing.T) {
result := findKeyAtLine(nil, 1, "")
if result != "" {
t.Errorf("expected empty string for nil node, got %q", result)
}
}
func TestFindKeyPosDocumentNode(t *testing.T) {
file, err := parser.ParseBytes([]byte("key: value\n"), 0)
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}
// file.Docs[0] is a *ast.DocumentNode: exercises the DocumentNode case in findKeyPos
line, col := findKeyPos(file.Docs[0], []string{"key"})
if line == 0 {
t.Errorf("expected non-zero line for 'key', got %d,%d", line, col)
}
}
func TestFindKeyAtLineDocumentNode(t *testing.T) {
file, err := parser.ParseBytes([]byte("key: value\n"), 0)
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}
// file.Docs[0] is a *ast.DocumentNode: exercises the DocumentNode case in findKeyAtLine
result := findKeyAtLine(file.Docs[0], 1, "")
_ = result
}
func TestParseStreamDeprecatedVersionWarning(t *testing.T) {
// An older but supported version should produce a deprecation warning.
p, _ := NewParser(ParserConfig{DisableNetwork: true})
yaml := `publiccodeYmlVersion: "0.2"
name: test
url: "https://github.com/example/repo.git"
platforms:
- web
developmentStatus: stable
softwareType: "standalone/web"
description:
en:
genericName: Test
shortDescription: "A short description."
longDescription: >
Long description that is longer than one hundred and fifty characters to
satisfy the minimum length requirement for this field in publiccode.yml.
Adding more text here to ensure we definitely hit the 150 character minimum.
features:
- feature1
legal:
license: MIT
maintenance:
type: none
localisation:
localisationReady: true
availableLanguages:
- en
`
_, err := p.ParseStream(strings.NewReader(yaml))
// Should produce a deprecation warning but no validation errors.
if err == nil {
return // no errors at all is also fine
}
var vr ValidationResults
ok := errors.As(err, &vr)
if !ok {
t.Fatalf("expected ValidationResults, got %T: %v", err, err)
}
hasWarning := false
for _, e := range vr {
if _, ok := errors.AsType[ValidationWarning](e); ok {
hasWarning = true
}
if _, ok := errors.AsType[ValidationError](e); ok {
t.Errorf("unexpected validation error: %v", e)
}
}
if !hasWarning {
t.Error("expected at least one deprecation warning for old version")
}
}
func TestDecodeTaggedMappingAsList(t *testing.T) {
for _, field := range []string{"platforms", "usedBy", "isBasedOn"} {
t.Run(field, func(t *testing.T) {
input := "publiccodeYmlVersion: \"0\"\n" + field + ": !custom {key: value}\n"
file, err := parser.ParseBytes([]byte(input), 0)
if err != nil {
t.Fatal(err)
}
var document PublicCodeV0
results, _ := decode([]byte(input), &document, file)
if len(results) != 1 {
t.Fatalf("expected one decoding error, got %v", results)
}
if _, ok := errors.AsType[ValidationError](results[0]); !ok {
t.Fatalf("expected ValidationError, got %T", results[0])
}
})
}
}
func TestDecodeUnknownFieldAliasChain(t *testing.T) {
data, err := os.ReadFile("testdata/v0/invalid/unknown_field_alias_chain.yml")
if err != nil {
t.Fatal(err)
}
file, err := parser.ParseBytes(data, 0)
if err != nil {
t.Fatal(err)
}
var document PublicCodeV0
results, wrongTypes := decode(data, &document, file)
if len(results) != 11 || len(wrongTypes) != 0 || document.Name != "Medusa" {
t.Fatalf("unexpected decoded result: name=%q, wrong types=%v, errors=%v", document.Name, wrongTypes, results)
}
}
func TestGetPositionInAnchoredMapping(t *testing.T) {
tests := []struct {
name string
fixture string
key string
line, column int
}{
{"block mapping", "testdata/v0/invalid/anchored_mapping_positions/block_mapping.yml", "legal.license", 2, 3},
{"flow mapping", "testdata/v0/invalid/anchored_mapping_positions/flow_mapping.yml", "legal.license", 1, 16},
{"nested anchors", "testdata/v0/invalid/anchored_mapping_positions/nested_anchors.yml", "description[en].shortDescription", 3, 5},
{"sequence entry", "testdata/v0/invalid/anchored_mapping_positions/sequence_entry.yml", "maintenance.contacts[0].name", 4, 7},
{"scalar anchor", "testdata/v0/invalid/anchored_mapping_positions/scalar_anchor.yml", "legal.license", 1, 15},
{"alias reference", "testdata/v0/invalid/anchored_mapping_positions/alias_reference.yml", "legal.license", 2, 8},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
source, err := os.ReadFile(test.fixture)
if err != nil {
t.Fatal(err)
}
file, err := parser.ParseBytes(source, 0)
if err != nil {
t.Fatal(err)
}
line, column := getPositionInFile(test.key, file)
if line != test.line || column != test.column {
t.Errorf("got %d:%d, want %d:%d", line, column, test.line, test.column)
}
})
}
}
func TestParseRejectsAliasedLongStrings(t *testing.T) {
p, err := NewParser(ParserConfig{DisableExternalChecks: true})
if err != nil {
t.Fatal(err)
}
source := "publiccodeYmlVersion: '0'\ndescription:\n en:\n features:\n - &f " + strings.Repeat("x", 1024) + "\n" + strings.Repeat(" - *f\n", maxAliasBytes/1024+1)
pc, err := p.ParseStream(strings.NewReader(source))
if pc != nil {
t.Fatal("returned a document with excessive alias expansion")
}
var results ValidationResults
if !errors.As(err, &results) || len(results) != 1 {
t.Fatalf("expected one validation error, got %v", err)
}
want := ValidationError{
Key: "description.en.features[4097]",
Description: "YAML aliases expand to more than 4194304 scalar bytes",
Line: 4102,
Column: 9,
}
if !errors.Is(results[0], want) {
t.Fatalf("got %#v, want %#v", results[0], want)
}
}