github.com/google/capslock@v0.2.3-0.20240517042941-dac19fc347c0/analyzer/analyzer_test.go (about)

     1  // Copyright 2023 Google LLC
     2  //
     3  // Use of this source code is governed by a BSD-style
     4  // license that can be found in the LICENSE file or at
     5  // https://developers.google.com/open-source/licenses/bsd
     6  
     7  package analyzer
     8  
     9  import (
    10  	"os"
    11  	"testing"
    12  
    13  	"github.com/google/capslock/interesting"
    14  	cpb "github.com/google/capslock/proto"
    15  	"github.com/google/go-cmp/cmp"
    16  	"golang.org/x/tools/go/analysis/analysistest"
    17  	"golang.org/x/tools/go/packages"
    18  	"google.golang.org/protobuf/proto"
    19  	"google.golang.org/protobuf/testing/protocmp"
    20  )
    21  
    22  var filemap = map[string]string{"testlib/foo.go": `package testlib
    23  
    24  import "os"
    25  
    26  func Foo() {
    27  	println(os.Getpid())
    28  }`}
    29  
    30  func TestAnalysis(t *testing.T) {
    31  	dir, cleanup, err := analysistest.WriteFiles(filemap)
    32  	if err != nil {
    33  		t.Fatalf("analysistest.WriteFiles: %v", err)
    34  	}
    35  	defer cleanup()
    36  	env := []string{"GOPATH=" + dir, "GO111MODULE=off", "GOPROXY=off"}
    37  	cfg := &packages.Config{
    38  		Mode: PackagesLoadModeNeeded,
    39  		Dir:  dir,
    40  		Env:  append(os.Environ(), env...),
    41  	}
    42  	pkgs, err := packages.Load(cfg, "testlib")
    43  	if err != nil {
    44  		t.Fatalf("packages.Load: %v", err)
    45  	}
    46  	queriedPackages := GetQueriedPackages(pkgs)
    47  	cil := GetCapabilityInfo(pkgs, queriedPackages, &Config{
    48  		Classifier:     interesting.DefaultClassifier(),
    49  		DisableBuiltin: false,
    50  	})
    51  	expected := &cpb.CapabilityInfoList{
    52  		CapabilityInfo: []*cpb.CapabilityInfo{{
    53  			PackageName: proto.String("testlib"),
    54  			Capability:  cpb.Capability_CAPABILITY_READ_SYSTEM_STATE.Enum(),
    55  			Path: []*cpb.Function{
    56  				&cpb.Function{Name: proto.String("testlib.Foo")},
    57  				&cpb.Function{Name: proto.String("os.Getpid")},
    58  			},
    59  			PackageDir:     proto.String("testlib"),
    60  			CapabilityType: cpb.CapabilityType_CAPABILITY_TYPE_DIRECT.Enum(),
    61  		}},
    62  	}
    63  	opts := []cmp.Option{
    64  		protocmp.Transform(),
    65  		protocmp.IgnoreFields(&cpb.CapabilityInfoList{}, "package_info"),
    66  		protocmp.IgnoreFields(&cpb.CapabilityInfo{}, "dep_path"),
    67  		protocmp.IgnoreFields(&cpb.Function{}, "site"),
    68  		protocmp.IgnoreFields(&cpb.Function_Site{}, "filename"),
    69  		protocmp.IgnoreFields(&cpb.Function_Site{}, "line"),
    70  		protocmp.IgnoreFields(&cpb.Function_Site{}, "column"),
    71  	}
    72  	if diff := cmp.Diff(expected, cil, opts...); diff != "" {
    73  		t.Errorf("GetCapabilityInfo(%v): got %v, want %v; diff %s",
    74  			filemap, cil, expected, diff)
    75  	}
    76  }