Repository navigation
Expand file tree
/
Copy pathparser_test.go
More file actions
599 lines (490 loc) · 17.1 KB
/
Copy pathparser_test.go
File metadata and controls
599 lines (490 loc) · 17.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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
package publiccode
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"testing"
"time"
)
// Test that the exported YAML passes validation again, and that re-exporting it
// matches the first export (lossless roundtrip).
func TestExport(t *testing.T) {
parser, err := NewParser(ParserConfig{DisableNetwork: true})
if err != nil {
t.Errorf("Can't create Parser: %v", err)
}
publiccode, err := parser.Parse("testdata/v0/valid/valid.yml")
if err != nil {
t.Errorf("Failed to parse valid file: %v", err)
}
yaml1, err := publiccode.ToYAML()
if err != nil {
t.Errorf("Failed to export YAML: %v", err)
}
// var p2 *Parser
// if p2, err = NewParser("/dev/null"); err != nil {
// t.Errorf("Can't create Parser: %v", err)
// }
publiccode2, err := parser.ParseStream(bytes.NewBuffer(yaml1))
if err != nil {
t.Errorf("Failed to parse exported file: %v", err)
}
yaml2, err := publiccode2.ToYAML()
if err != nil {
t.Errorf("Failed to export YAML again: %v", err)
}
if !bytes.Equal(yaml1, yaml2) {
t.Errorf("Exported YAML files do not match; roundtrip is not lossless")
}
}
// Test that the export leaves out keys the source manifest does not set.
func TestExportOmitsUnsetFields(t *testing.T) {
parser, err := NewParser(ParserConfig{DisableNetwork: true})
if err != nil {
t.Fatalf("Can't create Parser: %v", err)
}
// IT.conforme.gdpr is deprecated, so the parser returns warnings.
publiccode, err := parser.Parse("testdata/v0/valid_with_warnings/no-network/it_conforme_without_optional_fields.yml")
if results, ok := errors.AsType[ValidationResults](err); ok {
for _, result := range results {
if _, ok := errors.AsType[ValidationWarning](result); !ok {
t.Fatalf("Failed to parse manifest: %v", err)
}
}
} else if err != nil {
t.Fatalf("Failed to parse manifest: %v", err)
}
exportedYAML, err := publiccode.ToYAML()
if err != nil {
t.Fatalf("Failed to export YAML: %v", err)
}
exportedJSON, err := json.Marshal(publiccode)
if err != nil {
t.Fatalf("Failed to export JSON: %v", err)
}
for _, key := range []string{"releaseDate", "countryExtensionVersion", "piattaforme"} {
if bytes.Contains(exportedYAML, []byte(key)) {
t.Errorf("Exported YAML contains %q:\n%s", key, exportedYAML)
}
if bytes.Contains(exportedJSON, []byte(`"`+key+`"`)) {
t.Errorf("Exported JSON contains %q: %s", key, exportedJSON)
}
}
if !bytes.Contains(exportedYAML, []byte("gdpr: true")) {
t.Errorf("Exported YAML lost IT.conforme.gdpr:\n%s", exportedYAML)
}
}
// TestParseConcurrent verifies that multiple goroutines can call Parse on the same
// Parser instance simultaneously without data races, and that each call uses the
// correct baseURL for its file.
//
// Run with "go test -race".
func TestParseConcurrent(t *testing.T) {
const goroutines = 40
parser, err := NewParser(ParserConfig{DisableNetwork: true})
if err != nil {
t.Fatalf("can't create parser: %v", err)
}
// Has a logo and screenshots that only exist under no-network/assets/img/
fileA := "testdata/v0/valid/no-network/valid.yml"
// lives in the parent directory and has no screenshots
fileB := "testdata/v0/valid/categories_empty.yml"
_, errA := parser.Parse(fileA)
_, errB := parser.Parse(fileB)
var wg sync.WaitGroup
type result struct {
file string
err error
}
results := make([]result, goroutines)
for i := range goroutines {
wg.Add(1)
go func(i int) {
defer wg.Done()
file := fileA
if i%2 == 1 {
file = fileB
}
_, results[i].err = parser.Parse(file)
results[i].file = file
}(i)
}
wg.Wait()
for i, r := range results {
var expected error
// If base URLs leaked between goroutines, a fileA goroutine
// receiving fileB's baseURL would fail to locate the screenshots
// and return spurious validation errors.
if r.file == fileA {
expected = errA
} else {
expected = errB
}
if !reflect.DeepEqual(r.err, expected) {
t.Errorf("goroutine %d (%s): got %v, want %v", i, r.file, r.err, expected)
}
}
}
// TestDefaultTimeout checks that the default HTTP timeout is set when
// ParserConfig.Timeout is zero.
func TestDefaultTimeout(t *testing.T) {
p, err := NewParser(ParserConfig{})
if err != nil {
t.Fatal(err)
}
if p.client.Timeout != defaultHTTPTimeout {
t.Errorf("expected default timeout %v, got %v", defaultHTTPTimeout, p.client.Timeout)
}
}
// TestParseTimeout checks that Parse() fails when the server exceeds the
// configured timeout while fetching the publiccode.yml itself.
func TestParseTimeout(t *testing.T) {
fixture, err := os.ReadFile("testdata/v0/valid/valid.yml")
if err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(50 * time.Millisecond)
w.Header().Set("Content-Type", "text/yaml")
w.Write(fixture) //nolint:errcheck
}))
defer srv.Close()
p, err := NewParser(ParserConfig{Timeout: 1 * time.Millisecond, AllowNetworkToPrivateHosts: true})
if err != nil {
t.Fatal(err)
}
_, err = p.Parse(srv.URL + "/publiccode.yml")
if err == nil {
t.Fatal("expected timeout error, got nil")
}
if lower := strings.ToLower(err.Error()); !strings.Contains(lower, "deadline exceeded") && !strings.Contains(lower, "timeout") {
t.Errorf("expected timeout error, got: %v", err)
}
}
// TestValidationTimeout checks that external validation checks (logo) fail when
// the server exceeds the configured timeout.
func TestValidationTimeout(t *testing.T) {
fixture, err := os.ReadFile("testdata/v0/valid/logo_with_url.yml")
if err != nil {
t.Fatal(err)
}
logo, err := os.ReadFile("testdata/v0/valid/assets/img/logo.png")
if err != nil {
t.Fatal(err)
}
for _, slow := range []bool{false, true} {
t.Run(fmt.Sprintf("slow=%t", slow), func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if slow {
timer := time.NewTimer(time.Second)
defer timer.Stop()
select {
case <-r.Context().Done():
return
case <-timer.C:
}
}
_, _ = w.Write(logo)
}))
defer srv.Close()
p, err := NewParser(ParserConfig{
Timeout: 100 * time.Millisecond,
AllowNetworkToPrivateHosts: true,
BaseURL: srv.URL,
})
if err != nil {
t.Fatal(err)
}
transport := p.client.Transport
p.client.Transport = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
// The repository check must not use the network or consume the logo timeout.
if r.URL.String() == "https://github.com/italia/developers.italia.it.git" {
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader("")),
}, nil
}
// Logo URL resolution also checks for self hosted VCS services.
if r.URL.String() == srv.URL+"/api" || r.URL.String() == srv.URL+"/swagger.v1.json" {
return &http.Response{
StatusCode: http.StatusNotFound,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader("")),
}, nil
}
if r.URL.String() != srv.URL+"/logo.png" {
t.Errorf("unexpected request: %s", r.URL)
return nil, fmt.Errorf("unexpected request: %s", r.URL)
}
return transport.RoundTrip(r)
})
yml := bytes.ReplaceAll(fixture,
[]byte("https://raw.githubusercontent.com/publiccodeyml/libpubliccode/2a1f25a36e0f2ab2d71efb67db8b66ff00573fbe/testdata/v0/valid/assets/img/logo.png"),
[]byte(srv.URL+"/logo.png"),
)
_, err = p.ParseStream(bytes.NewReader(yml))
if !slow {
if err != nil {
t.Fatalf("unexpected validation error for fast logo: %v", err)
}
return
}
var results ValidationResults
if !errors.As(err, &results) || len(results) != 1 {
t.Fatalf("expected one logo validation error, got: %v", err)
}
var validationError ValidationError
if !errors.As(results[0], &validationError) || validationError.Key != "logo" {
t.Fatalf("expected logo validation error, got: %v", results[0])
}
description := strings.ToLower(validationError.Description)
if !strings.Contains(description, "context deadline exceeded") && !strings.Contains(description, "client.timeout exceeded") {
t.Errorf("expected logo timeout, got: %v", validationError)
}
})
}
}
// Test the toURL function.
func TestToURL(t *testing.T) {
cwd := testWorkingDir(t)
var err error
expected := map[string]*url.URL{
"file.txt": {Scheme: "file", Path: cwd + "/file.txt"},
"/path/file.txt": {Scheme: "file", Path: "/path/file.txt"},
"https://developers.italia.it/": {Scheme: "https", Host: "developers.italia.it", Path: "/"},
"https://developers.italia.it/file.txt": {Scheme: "https", Host: "developers.italia.it", Path: "/file.txt"},
"http://developers.italia.it/": {Scheme: "http", Host: "developers.italia.it", Path: "/"},
}
for in, out := range expected {
var u *url.URL
if u, err = toURL(in); err != nil {
t.Errorf("%s: got error %v", in, err)
}
if *u != *out {
t.Errorf("%s: expected %v got %v", in, out, u)
}
}
}
// The diagnostics must name the file that was validated, wherever it sits and
// whatever it is called, or an editor reading the errorformat output jumps to
// the wrong file.
func TestParseReportsInputFileName(t *testing.T) {
source, err := os.ReadFile("testdata/v0/invalid/categories_invalid.yml")
if err != nil {
t.Fatalf("can't read the fixture: %v", err)
}
dir := filepath.Join(t.TempDir(), "sub")
if err = os.Mkdir(dir, 0o700); err != nil {
t.Fatalf("can't create the fixture directory: %v", err)
}
file := filepath.Join(dir, "my-amazing-code.yaml")
//nolint:gosec // The destination is a fixed filename under t.TempDir().
if err = os.WriteFile(file, source, 0o600); err != nil {
t.Fatalf("can't write the fixture copy: %v", err)
}
parser, err := NewParser(ParserConfig{DisableExternalChecks: true})
if err != nil {
t.Fatalf("can't create parser: %v", err)
}
_, err = parser.Parse(file)
var results ValidationResults
if !errors.As(err, &results) {
t.Fatalf("expected validation results, got %T: %v", err, err)
}
for _, result := range results {
var ve ValidationError
if errors.As(result, &ve) && ve.File != file {
t.Errorf("got file %q, want %q", ve.File, file)
}
}
want := file + ":13:5: error: "
if !strings.HasPrefix(results.Error(), want) {
t.Errorf("got %q, want a diagnostic starting with %q", results.Error(), want)
}
}
// A stream carries no name, so its diagnostics keep the default one.
func TestParseStreamReportsDefaultFileName(t *testing.T) {
source, err := os.ReadFile("testdata/v0/invalid/categories_invalid.yml")
if err != nil {
t.Fatalf("can't read the fixture: %v", err)
}
parser, err := NewParser(ParserConfig{DisableExternalChecks: true})
if err != nil {
t.Fatalf("can't create parser: %v", err)
}
_, err = parser.ParseStream(bytes.NewReader(source))
if err == nil {
t.Fatal("expected validation results, got nil")
}
want := "publiccode.yml:13:5: error: "
if !strings.HasPrefix(err.Error(), want) {
t.Errorf("got %q, want a diagnostic starting with %q", err.Error(), want)
}
}
// Test the diagnosticFileName function.
func TestDiagnosticFileName(t *testing.T) {
expected := []struct {
uri string
in *url.URL
want string
}{
{"sub/publiccode.yml", &url.URL{Scheme: "file", Path: "/cwd/sub/publiccode.yml"}, "sub/publiccode.yml"},
{"/path/to/my-amazing-code.yaml", &url.URL{Scheme: "file", Path: "/path/to/my-amazing-code.yaml"}, "/path/to/my-amazing-code.yaml"},
{"https://example.org/dir/publiccode.yml", &url.URL{Scheme: "https", Host: "example.org", Path: "/dir/publiccode.yml"}, "publiccode.yml"},
{"https://example.org/", &url.URL{Scheme: "https", Host: "example.org", Path: "/"}, ""},
}
for _, test := range expected {
if got := diagnosticFileName(test.uri, test.in); got != test.want {
t.Errorf("%q: expected %q got %q", test.uri, test.want, got)
}
}
}
func TestMalformedURLsSkipNetworkChecks(t *testing.T) {
var results [2]error
for i, disableNetwork := range []bool{true, false} {
parser, err := NewParser(ParserConfig{DisableNetwork: disableNetwork})
if err != nil {
t.Fatal(err)
}
_, results[i] = parser.Parse("testdata/v0/invalid/no-network/urls_malformed.yml")
}
if results[0] == nil || !reflect.DeepEqual(results[0], results[1]) {
t.Fatalf("network checks changed malformed URL diagnostics: offline %v, online %v", results[0], results[1])
}
}
// parseV0WithWarnings parses source, expects only warnings back and returns
// the decoded v0 struct.
func parseV0WithWarnings(t *testing.T, source []byte) PublicCodeV0 {
t.Helper()
parser, err := NewParser(ParserConfig{DisableExternalChecks: true})
if err != nil {
t.Fatalf("can't create parser: %v", err)
}
pc, err := parser.ParseStream(bytes.NewReader(source))
var results ValidationResults
if err != nil && !errors.As(err, &results) {
t.Fatalf("expected validation results, got %T: %v", err, err)
}
for _, result := range results {
if ve, ok := errors.AsType[ValidationError](result); ok {
t.Fatalf("expected warnings only, got error: %v", ve)
}
}
v0, ok := pc.(PublicCodeV0)
if !ok {
t.Fatalf("got %T, want PublicCodeV0", pc)
}
return v0
}
func readFixture(t *testing.T, name string) []byte {
t.Helper()
source, err := os.ReadFile(name)
if err != nil {
t.Fatalf("can't read the fixture: %v", err)
}
return source
}
// v0 callers read the Italian section from IT, even when the file uses the
// deprecated lowercase key.
func TestParseV0CopiesLowercaseItSection(t *testing.T) {
v0 := parseV0WithWarnings(t, readFixture(t,
"testdata/v0/valid_with_warnings/valid_with_country_specific_section_downcase.yml"))
if v0.IT == nil {
t.Fatal("IT is nil, want the content of the it section")
}
if v0.IT.CountryExtensionVersion == nil || *v0.IT.CountryExtensionVersion != "1.0" {
t.Errorf("got IT.countryExtensionVersion %v, want 1.0", v0.IT.CountryExtensionVersion)
}
}
// v0 callers read the organisation from organisation, even when the file only
// sets IT.riuso.codiceIPA and legal.repoOwner.
func TestParseV0DerivesOrganisationFromCodiceIPA(t *testing.T) {
v0 := parseV0WithWarnings(t, readFixture(t,
"testdata/v0/valid_with_warnings/no-network/IT_riuso_codiceIPA_with_legal_repoOwner.yml"))
if v0.Organisation == nil {
t.Fatal("organisation is nil, want one derived from IT.riuso.codiceIPA")
}
if want := "urn:x-italian-pa:pcm"; v0.Organisation.URI != want {
t.Errorf("got organisation.uri %q, want %q", v0.Organisation.URI, want)
}
want := "Example Municipality"
if v0.Organisation.Name == nil || *v0.Organisation.Name != want {
t.Errorf("got organisation.name %v, want %q", v0.Organisation.Name, want)
}
}
// An organisation the file sets is kept as written, codiceIPA or not.
func TestParseV0KeepsDeclaredOrganisation(t *testing.T) {
v0 := parseV0WithWarnings(t, readFixture(t,
"testdata/v0/valid_with_warnings/no-network/IT_riuso_codiceIPA_with_organisation.yml"))
if v0.Organisation == nil {
t.Fatal("organisation is nil, want the declared one")
}
if want := "urn:x-custom:id"; v0.Organisation.URI != want {
t.Errorf("got organisation.uri %q, want %q", v0.Organisation.URI, want)
}
if want := "Custom Org"; v0.Organisation.Name == nil || *v0.Organisation.Name != want {
t.Errorf("got organisation.name %v, want %q", v0.Organisation.Name, want)
}
}
// Warnings name the input file, like errors do.
func TestParseReportsInputFileNameOnWarnings(t *testing.T) {
source := readFixture(t,
"testdata/v0/valid_with_warnings/valid_with_country_specific_section_downcase.yml")
file := filepath.Join(t.TempDir(), "my-amazing-code.yaml")
if err := os.WriteFile(file, source, 0o600); err != nil {
t.Fatalf("can't write the fixture copy: %v", err)
}
parser, err := NewParser(ParserConfig{DisableExternalChecks: true})
if err != nil {
t.Fatalf("can't create parser: %v", err)
}
_, err = parser.Parse(file)
var results ValidationResults
if !errors.As(err, &results) {
t.Fatalf("expected validation results, got %T: %v", err, err)
}
warnings := 0
for _, result := range results {
var vw ValidationWarning
if !errors.As(result, &vw) {
continue
}
warnings++
if vw.File != file {
t.Errorf("got file %q on warning %q, want %q", vw.File, vw.Key, file)
}
}
if warnings == 0 {
t.Fatalf("expected warnings, got %v", results)
}
}
func TestAnchoredMappingDiagnosticPosition(t *testing.T) {
for _, fixture := range []string{"legal_license_deprecated.yml", "legal_license_deprecated_anchored.yml"} {
t.Run(fixture, func(t *testing.T) {
p, err := NewParser(ParserConfig{DisableNetwork: true})
if err != nil {
t.Fatal(err)
}
_, err = p.Parse("testdata/v0/valid_with_warnings/anchored_mapping_positions/" + fixture)
var results ValidationResults
if !errors.As(err, &results) || len(results) != 1 {
t.Fatalf("expected one license warning, got %v", err)
}
warning, ok := errors.AsType[ValidationWarning](results[0])
if !ok || warning.Key != "legal.license" || warning.Line != 39 || warning.Column != 3 {
t.Fatalf("expected legal.license warning at 39:3, got %#v", results[0])
}
})
}
}