github.com/anchore/syft@v1.38.2/syft/pkg/cataloger/golang/config_test.go (about) 1 package golang 2 3 import ( 4 "path/filepath" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 9 "github.com/anchore/go-homedir" 10 ) 11 12 func Test_Config(t *testing.T) { 13 type opts struct { 14 local bool 15 cacheDir string 16 vendorDir string 17 remote bool 18 proxy string 19 noProxy string 20 } 21 22 restoreCache(t) 23 homedir.SetCacheEnable(false) 24 25 allEnv := map[string]string{ 26 "HOME": "/usr/home", 27 "GOPATH": "", 28 "GOPROXY": "", 29 "GOPRIVATE": "", 30 "GONOPROXY": "", 31 } 32 33 tests := []struct { 34 name string 35 env map[string]string 36 opts opts 37 expected CatalogerConfig 38 }{ 39 { 40 name: "set via env defaults", 41 env: map[string]string{ 42 "GOPATH": "/go", 43 "GOPROXY": "https://my.proxy", 44 "GOPRIVATE": "my.private", 45 "GONOPROXY": "no.proxy", 46 }, 47 opts: opts{ 48 // defaults to $cwd/vendor, we need to set it to make the output predictable 49 vendorDir: "/vendor", 50 }, 51 expected: CatalogerConfig{ 52 SearchLocalModCacheLicenses: false, 53 LocalModCacheDir: filepath.Join("/go", "pkg", "mod"), 54 SearchLocalVendorLicenses: false, 55 LocalVendorDir: "/vendor", 56 SearchRemoteLicenses: false, 57 Proxies: []string{"https://my.proxy"}, 58 NoProxy: []string{"my.private", "no.proxy"}, 59 MainModuleVersion: DefaultMainModuleVersionConfig(), 60 }, 61 }, 62 { 63 name: "set via configuration", 64 env: map[string]string{ 65 "GOPATH": "/go", 66 "GOPROXY": "https://my.proxy", 67 "GOPRIVATE": "my.private", 68 "GONOPROXY": "no.proxy", 69 }, 70 opts: opts{ 71 local: true, 72 cacheDir: "/go-cache", 73 vendorDir: "/vendor", 74 remote: true, 75 proxy: "https://alt.proxy,direct", 76 noProxy: "alt.no.proxy", 77 }, 78 expected: CatalogerConfig{ 79 SearchLocalModCacheLicenses: true, 80 LocalModCacheDir: "/go-cache", 81 SearchLocalVendorLicenses: true, 82 LocalVendorDir: "/vendor", 83 SearchRemoteLicenses: true, 84 Proxies: []string{"https://alt.proxy", "direct"}, 85 NoProxy: []string{"alt.no.proxy"}, 86 MainModuleVersion: DefaultMainModuleVersionConfig(), 87 }, 88 }, 89 } 90 91 for _, test := range tests { 92 t.Run(test.name, func(t *testing.T) { 93 for k, v := range allEnv { 94 t.Setenv(k, v) 95 } 96 for k, v := range test.env { 97 t.Setenv(k, v) 98 } 99 got := DefaultCatalogerConfig(). 100 WithSearchLocalModCacheLicenses(test.opts.local). 101 WithLocalModCacheDir(test.opts.cacheDir). 102 WithSearchLocalVendorLicenses(test.opts.local). 103 WithLocalVendorDir(test.opts.vendorDir). 104 WithSearchRemoteLicenses(test.opts.remote). 105 WithProxy(test.opts.proxy). 106 WithNoProxy(test.opts.noProxy) 107 108 assert.Equal(t, test.expected, got) 109 }) 110 } 111 } 112 113 // restoreCache ensures cache settings are restored after test 114 func restoreCache(t testing.TB) { 115 t.Helper() 116 origEnabled := homedir.CacheEnabled() 117 118 t.Cleanup(func() { 119 homedir.SetCacheEnable(origEnabled) 120 homedir.Reset() 121 }) 122 }