github.com/seilagamo/poc-lava-release@v0.3.3-rc3/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  	"testing"
    10  
    11  	"github.com/jroimartin/clilog"
    12  )
    13  
    14  func TestMain(m *testing.M) {
    15  	flag.Parse()
    16  
    17  	level := slog.LevelError
    18  	if testing.Verbose() {
    19  		level = slog.LevelDebug
    20  	}
    21  
    22  	h := clilog.NewCLIHandler(os.Stderr, &clilog.HandlerOptions{Level: level})
    23  	slog.SetDefault(slog.New(h))
    24  
    25  	os.Exit(m.Run())
    26  }
    27  
    28  func TestRun(t *testing.T) {
    29  	tests := []struct {
    30  		name         string
    31  		wantExitCode int
    32  		path         string
    33  	}{
    34  		{
    35  			name:         "good path",
    36  			wantExitCode: 0,
    37  			path:         "testdata/goodpath",
    38  		},
    39  		{
    40  			name:         "vulnerable path",
    41  			wantExitCode: 103,
    42  			path:         "testdata/vulnpath",
    43  		},
    44  	}
    45  
    46  	for _, tt := range tests {
    47  		t.Run(tt.name, func(t *testing.T) {
    48  			oldPwd := mustGetwd()
    49  			oldCfgfile := *cfgfile
    50  			oldOsExit := osExit
    51  			defer func() {
    52  				mustChdir(oldPwd)
    53  				*cfgfile = oldCfgfile
    54  				osExit = oldOsExit
    55  			}()
    56  
    57  			*cfgfile = "lava.yaml"
    58  
    59  			var exitCode int
    60  			osExit = func(status int) {
    61  				exitCode = status
    62  			}
    63  
    64  			mustChdir(tt.path)
    65  			if err := run(nil); err != nil {
    66  				t.Fatalf("run error: %v", err)
    67  			}
    68  
    69  			if exitCode != tt.wantExitCode {
    70  				t.Errorf("unexpected exit code: got: %v, want: %v", exitCode, tt.wantExitCode)
    71  			}
    72  		})
    73  	}
    74  }
    75  
    76  // mustGetwd returns a rooted path name corresponding to the current
    77  // directory. It panics on error.
    78  func mustGetwd() string {
    79  	wd, err := os.Getwd()
    80  	if err != nil {
    81  		panic(err)
    82  	}
    83  	return wd
    84  }
    85  
    86  // mustChdir changes the current working directory to the named
    87  // directory. It panics on error.
    88  func mustChdir(path string) {
    89  	if err := os.Chdir(path); err != nil {
    90  		panic(err)
    91  	}
    92  }