github.com/adevinta/lava@v0.7.2/cmd/lava/internal/scan/scan_test.go (about) 1 // Copyright 2023 Adevinta 2 3 package scan 4 5 import ( 6 "flag" 7 "log/slog" 8 "os" 9 "runtime/debug" 10 "testing" 11 12 "github.com/jroimartin/clilog" 13 ) 14 15 func TestMain(m *testing.M) { 16 flag.Parse() 17 18 level := slog.LevelError 19 if testing.Verbose() { 20 level = slog.LevelDebug 21 } 22 23 h := clilog.NewCLIHandler(os.Stderr, &clilog.HandlerOptions{Level: level}) 24 slog.SetDefault(slog.New(h)) 25 26 os.Exit(m.Run()) 27 } 28 29 func TestRunScan(t *testing.T) { 30 tests := []struct { 31 name string 32 path string 33 version string 34 wantNilErr bool 35 wantExitCode int 36 }{ 37 { 38 name: "good path", 39 path: "testdata/goodpath", 40 version: "v1.0.0", 41 wantNilErr: true, 42 wantExitCode: 0, 43 }, 44 { 45 name: "vulnerable path", 46 path: "testdata/vulnpath", 47 version: "v1.0.0", 48 wantNilErr: true, 49 wantExitCode: 103, 50 }, 51 { 52 name: "incompatible", 53 path: "testdata/vulnpath", 54 version: "v0.1.0", 55 wantNilErr: false, 56 }, 57 { 58 name: "skip compatibility check", 59 path: "testdata/vulnpath", 60 version: "(devel)", 61 wantNilErr: true, 62 wantExitCode: 103, 63 }, 64 } 65 66 for _, tt := range tests { 67 t.Run(tt.name, func(t *testing.T) { 68 oldPwd := mustGetwd() 69 oldScanC := scanC 70 oldOsExit := osExit 71 oldDebugReadBuildInfo := debugReadBuildInfo 72 defer func() { 73 mustChdir(oldPwd) 74 scanC = oldScanC 75 osExit = oldOsExit 76 debugReadBuildInfo = oldDebugReadBuildInfo 77 }() 78 79 scanC = "lava.yaml" 80 81 var exitCode int 82 osExit = func(status int) { 83 exitCode = status 84 } 85 86 debugReadBuildInfo = func() (*debug.BuildInfo, bool) { 87 bi := &debug.BuildInfo{ 88 Main: debug.Module{ 89 Version: tt.version, 90 }, 91 } 92 return bi, true 93 } 94 95 mustChdir(tt.path) 96 if err := runScan(nil); (err == nil) != tt.wantNilErr { 97 t.Fatalf("unexpected error: %v", err) 98 } 99 100 if exitCode != tt.wantExitCode { 101 t.Errorf("unexpected exit code: got: %v, want: %v", exitCode, tt.wantExitCode) 102 } 103 }) 104 } 105 } 106 107 // mustGetwd returns a rooted path name corresponding to the current 108 // directory. It panics on error. 109 func mustGetwd() string { 110 wd, err := os.Getwd() 111 if err != nil { 112 panic(err) 113 } 114 return wd 115 } 116 117 // mustChdir changes the current working directory to the named 118 // directory. It panics on error. 119 func mustChdir(path string) { 120 if err := os.Chdir(path); err != nil { 121 panic(err) 122 } 123 }