Debian Codegraph @

gopls/internal/vulncheck/vulntest/db_test.go

raw symbols SCIP
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package vulntest
6
7 import (
8 "context"
9 "encoding/json"
10 "flag"
11 "os"
12 "path/filepath"
13 "testing"
14 "time"
15
16 "github.com/google/go-cmp/cmp"
17 "golang.org/x/tools/gopls/internal/protocol"
18 "golang.org/x/tools/gopls/internal/vulncheck/osv"
19 )
20
21 var update = flag.Bool("update", false, "update golden files in testdata/")
22
23 func TestNewDatabase(t *testing.T) {
24 ctx := context.Background()
25
26 in, err := os.ReadFile("testdata/report.yaml")
27 if err != nil {
28 t.Fatal(err)
29 }
30 in = append([]byte("-- GO-2020-0001.yaml --\n"), in...)
31
32 db, err := NewDatabase(ctx, in)
33 if err != nil {
34 t.Fatal(err)
35 }
36 defer db.Clean()
37 dbpath := protocol.DocumentURI(db.URI()).Path()
38
39 // The generated JSON file will be in DB/GO-2022-0001.json.
40 got := readOSVEntry(t, filepath.Join(dbpath, "GO-2020-0001.json"))
41 got.Modified = time.Time{}
42
43 if *update {
44 updateTestData(t, got, "testdata/GO-2020-0001.json")
45 }
46
47 want := readOSVEntry(t, "testdata/GO-2020-0001.json")
48 want.Modified = time.Time{}
49 if diff := cmp.Diff(want, got); diff != "" {
50 t.Errorf("mismatch (-want +got):\n%s", diff)
51 }
52 }
53
54 func updateTestData(t *testing.T, got *osv.Entry, fname string) {
55 content, err := json.MarshalIndent(got, "", "\t")
56 if err != nil {
57 t.Fatal(err)
58 }
59 if err := os.WriteFile(fname, content, 0666); err != nil {
60 t.Fatal(err)
61 }
62 t.Logf("updated %v", fname)
63 }
64
65 func readOSVEntry(t *testing.T, filename string) *osv.Entry {
66 t.Helper()
67 content, err := os.ReadFile(filename)
68 if err != nil {
69 t.Fatal(err)
70 }
71 var entry osv.Entry
72 if err := json.Unmarshal(content, &entry); err != nil {
73 t.Fatal(err)
74 }
75 return &entry
76 }