golang.org/x/tools/gopls@v0.15.3/internal/vulncheck/vulntest/db_test.go (about)

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