ci(deps): fix gocritic in ".*_test.go$" (#6763)

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
This commit is contained in:
Matthieu MOREL
2024-05-24 11:03:26 +02:00
committed by GitHub
parent e3738333b4
commit e86bacbd6d
36 changed files with 78 additions and 68 deletions

View File

@@ -106,13 +106,24 @@ issues:
- path: ".*_test.go$"
linters:
- bodyclose
- gocritic
- goconst
- gosec
- govet
- ineffassign
- misspell
- unused
- path: ".*_test.go$"
linters:
- gocritic
text: "commentFormatting:"
- path: ".*_test.go$"
linters:
- gocritic
text: "exitAfterDefer:"
- path: ".*_test.go$"
linters:
- gocritic
text: "importShadow:"
- linters:
- gosec
text: "G304: Potential file inclusion"

View File

@@ -59,7 +59,7 @@ func TestParse(t *testing.T) {
Version: "4.1.2",
Licenses: []string{"ISC"},
},
Dependencies: map[string]string{},
Dependencies: make(map[string]string),
DevDependencies: map[string]string{
"@babel/cli": "^7.14.5",
"@babel/core": "^7.14.6",

View File

@@ -4,7 +4,6 @@ import (
"os"
"path"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -65,7 +64,7 @@ func TestParse(t *testing.T) {
func sortDeps(deps []ftypes.Dependency) {
sort.Slice(deps, func(i, j int) bool {
return strings.Compare(deps[i].ID, deps[j].ID) < 0
return deps[i].ID < deps[j].ID
})
for i := range deps {

View File

@@ -109,7 +109,7 @@ func TestParseDependency(t *testing.T) {
name: "pkgsVersions doesn't contain required version",
packageName: "test",
versionRange: ">=1.0.0",
pkgsVersions: map[string][]string{},
pkgsVersions: make(map[string][]string),
wantErr: "no version found",
},
}

View File

@@ -1261,9 +1261,9 @@ func TestResolveDependency(t *testing.T) {
if err = json.NewDecoder(f).Decode(&apkIndexArchive); err != nil {
t.Fatalf("unexpected error: %s", err)
}
circularDependencyCheck := map[string]struct{}{}
circularDependencyCheck := make(map[string]struct{})
pkgs := analyzer.resolveDependency(apkIndexArchive, v.pkgName, circularDependencyCheck)
actual := map[string]struct{}{}
actual := make(map[string]struct{})
for _, pkg := range pkgs {
actual[pkg] = struct{}{}
}

View File

@@ -47,7 +47,7 @@ func TestManager_Versions(t *testing.T) {
{
name: "disable hooks",
disable: []types.HandlerType{"fake"},
want: map[string]int{},
want: make(map[string]int),
},
}

View File

@@ -101,7 +101,7 @@ func TestSkipDir(t *testing.T) {
},
{
name: "two stars",
skipDirs: []string{filepath.Join("/etc/*/*")},
skipDirs: []string{"/etc/*/*"},
wants: map[string]bool{
"/etc/foo": false,
"/etc/foo/bar": true,
@@ -109,11 +109,11 @@ func TestSkipDir(t *testing.T) {
},
{
name: "multiple dirs",
skipDirs: []string{filepath.Join("/etc/*/*"), filepath.Join("/var/log/*")},
skipDirs: []string{"/etc/*/*", "/var/log/*"},
wants: map[string]bool{
filepath.Join("/etc/foo"): false,
filepath.Join("/etc/foo/bar"): true,
filepath.Join("/var/log/bar"): true,
"/etc/foo": false,
"/etc/foo/bar": true,
"/var/log/bar": true,
},
},
{
@@ -126,10 +126,10 @@ func TestSkipDir(t *testing.T) {
},
{
name: "error bad pattern",
skipDirs: []string{filepath.Join(`[^etc`)}, // filepath.Match returns ErrBadPattern
skipDirs: []string{`[^etc`}, // filepath.Match returns ErrBadPattern
wants: map[string]bool{
filepath.Join("/etc/foo"): false,
filepath.Join("/etc/foo/bar"): false,
"/etc/foo": false,
"/etc/foo/bar": false,
},
},
}

View File

@@ -45,7 +45,7 @@ func Test_AdaptWindowsVM(t *testing.T) {
Type: azure2.NewValue("Microsoft.Compute/virtualMachines", types.NewTestMetadata()),
Properties: azure2.NewValue(map[string]azure2.Value{
"osProfile": azure2.NewValue(map[string]azure2.Value{
"windowsConfiguration": azure2.NewValue(map[string]azure2.Value{}, types.NewTestMetadata()),
"windowsConfiguration": azure2.NewValue(make(map[string]azure2.Value), types.NewTestMetadata()),
}, types.NewTestMetadata()),
}, types.NewTestMetadata()),
},

View File

@@ -16,7 +16,7 @@ func Test_AdaptStorageDefaults(t *testing.T) {
Resources: []azure2.Resource{
{
Type: azure2.NewValue("Microsoft.Storage/storageAccounts", types.NewTestMetadata()),
Properties: azure2.NewValue(map[string]azure2.Value{}, types.NewTestMetadata()),
Properties: azure2.NewValue(make(map[string]azure2.Value), types.NewTestMetadata()),
},
},
}

View File

@@ -237,7 +237,7 @@ resource "google_container_cluster" "example" {
},
EnableShieldedNodes: iacTypes.Bool(true, iacTypes.NewTestMetadata()),
EnableLegacyABAC: iacTypes.Bool(false, iacTypes.NewTestMetadata()),
ResourceLabels: iacTypes.Map(map[string]string{}, iacTypes.NewTestMetadata()),
ResourceLabels: iacTypes.Map(make(map[string]string), iacTypes.NewTestMetadata()),
RemoveDefaultNodePool: iacTypes.Bool(false, iacTypes.NewTestMetadata()),
},
},

View File

@@ -21,7 +21,7 @@ func Test_SliceConversion(t *testing.T) {
}
input[0].Z.A = 123
converted := SliceToRego(reflect.ValueOf(input))
assert.Equal(t, []interface{}{map[string]interface{}{"z": map[string]interface{}{}}}, converted)
assert.Equal(t, []interface{}{map[string]interface{}{"z": make(map[string]interface{})}}, converted)
}
func Test_SliceTypesConversion(t *testing.T) {

View File

@@ -17,5 +17,5 @@ func Test_StructConversion(t *testing.T) {
}{}
input.Z.A = 123
converted := StructToRego(reflect.ValueOf(input))
assert.Equal(t, map[string]interface{}{"z": map[string]interface{}{}}, converted)
assert.Equal(t, map[string]interface{}{"z": make(map[string]interface{})}, converted)
}

View File

@@ -11,7 +11,7 @@ import (
func Test_Array_Empty(t *testing.T) {
example := []byte(`[]`)
target := []int{}
var target []int
metadata := types.NewTestMetadata()
require.NoError(t, Unmarshal(example, &target, &metadata))
assert.Empty(t, target)
@@ -19,7 +19,7 @@ func Test_Array_Empty(t *testing.T) {
func Test_Array_ToSlice(t *testing.T) {
example := []byte(`[1, 2, 3]`)
target := []int{}
var target []int
metadata := types.NewTestMetadata()
require.NoError(t, Unmarshal(example, &target, &metadata))
assert.Len(t, target, 3)

View File

@@ -16,7 +16,7 @@ func Test_CreateObject(t *testing.T) {
{
name: "CreateObject with no args",
args: []interface{}{},
expected: map[string]interface{}{},
expected: make(map[string]interface{}),
},
{
name: "CreateObject with one arg",
@@ -36,7 +36,7 @@ func Test_CreateObject(t *testing.T) {
{
name: "CreateObject with odd number of args",
args: []interface{}{"foo", "bar", "baz"},
expected: map[string]interface{}{},
expected: make(map[string]interface{}),
},
{
name: "CreateObject with odd number of args",

View File

@@ -43,7 +43,7 @@ func Test_Empty(t *testing.T) {
{
name: "map is empty",
args: []interface{}{
map[string]interface{}{},
make(map[string]interface{}),
},
expected: true,
},

View File

@@ -13,7 +13,7 @@ import (
"github.com/aquasecurity/trivy/internal/testutil"
)
func parseFile(t *testing.T, source string, name string) (FileContexts, error) {
func parseFile(t *testing.T, source, name string) (FileContexts, error) {
tmp, err := os.MkdirTemp(os.TempDir(), "defsec")
require.NoError(t, err)
defer func() { _ = os.RemoveAll(tmp) }()

View File

@@ -82,7 +82,7 @@ deny[res] {
Terraform: (*scan.TerraformCustomCheck)(nil),
},
RegoPackage: "data.builtin.dockerfile.DS006",
Frameworks: map[framework.Framework][]string{},
Frameworks: make(map[framework.Framework][]string),
}, results.GetFailed()[0].Rule())
failure := results.GetFailed()[0]

View File

@@ -252,7 +252,7 @@ USER root
CustomChecks: scan.CustomChecks{
Terraform: (*scan.TerraformCustomCheck)(nil)},
RegoPackage: "data.builtin.dockerfile.DS006",
Frameworks: map[framework.Framework][]string{},
Frameworks: make(map[framework.Framework][]string),
},
results.GetFailed()[0].Rule(),
)
@@ -607,7 +607,7 @@ COPY --from=dep /binary /`
CustomChecks: scan.CustomChecks{
Terraform: (*scan.TerraformCustomCheck)(nil)},
RegoPackage: "data.builtin.dockerfile.DS006",
Frameworks: map[framework.Framework][]string{},
Frameworks: make(map[framework.Framework][]string),
},
results.GetFailed()[0].Rule(),
)

View File

@@ -73,6 +73,6 @@ deny[res] {
Terraform: (*scan.TerraformCustomCheck)(nil),
},
RegoPackage: "data.builtin.json.lol",
Frameworks: map[framework.Framework][]string{},
Frameworks: make(map[framework.Framework][]string),
}, results.GetFailed()[0].Rule())
}

View File

@@ -119,7 +119,7 @@ deny[res] {
CloudFormation: &scan.EngineMetadata{},
CustomChecks: scan.CustomChecks{Terraform: (*scan.TerraformCustomCheck)(nil)},
RegoPackage: "data.builtin.kubernetes.KSV011",
Frameworks: map[framework.Framework][]string{},
Frameworks: make(map[framework.Framework][]string),
}, results.GetFailed()[0].Rule())
failure := results.GetFailed()[0]
@@ -279,7 +279,7 @@ deny[res] {
CloudFormation: &scan.EngineMetadata{},
CustomChecks: scan.CustomChecks{Terraform: (*scan.TerraformCustomCheck)(nil)},
RegoPackage: "data.builtin.kubernetes.KSV011",
Frameworks: map[framework.Framework][]string{},
Frameworks: make(map[framework.Framework][]string),
}, results.GetFailed()[0].Rule())
failure := results.GetFailed()[0]

View File

@@ -1510,7 +1510,7 @@ func parse(t *testing.T, files map[string]string) terraform.Modules {
return modules
}
func compareSets(a []int, b []int) bool {
func compareSets(a, b []int) bool {
m := make(map[int]bool)
for _, el := range a {
m[el] = true

View File

@@ -13,7 +13,7 @@ import (
"github.com/aquasecurity/trivy/pkg/iac/terraform"
)
func createModulesFromSource(t *testing.T, source string, ext string) terraform.Modules {
func createModulesFromSource(t *testing.T, source, ext string) terraform.Modules {
fs := testutil.CreateFS(t, map[string]string{
"source" + ext: source,
})
@@ -29,7 +29,7 @@ func createModulesFromSource(t *testing.T, source string, ext string) terraform.
return modules
}
func scanHCLWithWorkspace(t *testing.T, source string, workspace string) scan.Results {
func scanHCLWithWorkspace(t *testing.T, source, workspace string) scan.Results {
return scanHCL(t, source, ScannerWithWorkspaceName(workspace))
}

View File

@@ -76,7 +76,7 @@ deny[res] {
CustomChecks: scan.CustomChecks{
Terraform: (*scan.TerraformCustomCheck)(nil)},
RegoPackage: "data.builtin.toml.lol",
Frameworks: map[framework.Framework][]string{},
Frameworks: make(map[framework.Framework][]string),
},
results.GetFailed()[0].Rule(),
)

View File

@@ -79,7 +79,7 @@ deny[res] {
CustomChecks: scan.CustomChecks{
Terraform: (*scan.TerraformCustomCheck)(nil)},
RegoPackage: "data.builtin.yaml.lol",
Frameworks: map[framework.Framework][]string{},
Frameworks: make(map[framework.Framework][]string),
},
results.GetFailed()[0].Rule(),
)

View File

@@ -507,18 +507,18 @@ func TestFindNodeName(t *testing.T) {
Namespace: "kube-system",
Kind: "Cluster",
Name: "k8s.io/kubernetes",
RawResource: map[string]interface{}{},
RawResource: make(map[string]interface{}),
},
{
Namespace: "kube-system",
Kind: "ControlPlaneComponents",
Name: "k8s.io/apiserver",
RawResource: map[string]interface{}{},
RawResource: make(map[string]interface{}),
},
{
Kind: "NodeComponents",
Name: "kind-control-plane",
RawResource: map[string]interface{}{},
RawResource: make(map[string]interface{}),
},
},
want: "kind-control-plane",
@@ -530,13 +530,13 @@ func TestFindNodeName(t *testing.T) {
Namespace: "kube-system",
Kind: "Cluster",
Name: "k8s.io/kubernetes",
RawResource: map[string]interface{}{},
RawResource: make(map[string]interface{}),
},
{
Namespace: "kube-system",
Kind: "ControlPlaneComponents",
Name: "k8s.io/apiserver",
RawResource: map[string]interface{}{},
RawResource: make(map[string]interface{}),
},
},
want: "",

View File

@@ -46,7 +46,7 @@ func TestScanner_Scan(t *testing.T) {
},
{
name: "unknown",
categories: map[types.LicenseCategory][]string{},
categories: make(map[types.LicenseCategory][]string),
licenseName: licensing.BSD3Clause,
wantCategory: types.CategoryUnknown,
wantSeverity: "UNKNOWN",

View File

@@ -197,7 +197,7 @@ func TestSlogtest(t *testing.T) {
results := func(*testing.T) map[string]any {
for _, line := range strings.Split(buf.String(), "\n") {
if len(line) == 0 {
if line == "" {
continue
}
m, err := parseLogLine(line)

View File

@@ -171,8 +171,8 @@ func TestScanner_Scan(t *testing.T) {
func Test_createPolicyFS(t *testing.T) {
t.Run("outside pwd", func(t *testing.T) {
tmpDir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(tmpDir, "subdir/testdir"), 0750))
f, got, err := CreatePolicyFS([]string{filepath.Join(tmpDir, "subdir/testdir")})
require.NoError(t, os.MkdirAll(filepath.Join(tmpDir, "subdir", "testdir"), 0750))
f, got, err := CreatePolicyFS([]string{filepath.Join(tmpDir, "subdir", "testdir")})
assertFS(t, tmpDir, f, got, err)
})
}
@@ -180,8 +180,8 @@ func Test_createPolicyFS(t *testing.T) {
func Test_CreateDataFS(t *testing.T) {
t.Run("outside pwd", func(t *testing.T) {
tmpDir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(tmpDir, "subdir/testdir"), 0750))
f, got, err := CreateDataFS([]string{filepath.Join(tmpDir, "subdir/testdir")})
require.NoError(t, os.MkdirAll(filepath.Join(tmpDir, "subdir", "testdir"), 0750))
f, got, err := CreateDataFS([]string{filepath.Join(tmpDir, "subdir", "testdir")})
assertFS(t, tmpDir, f, got, err)
})
}

View File

@@ -35,7 +35,7 @@ func TestManager_Register(t *testing.T) {
Analyzers: map[string]int{
"happy": 1,
},
PostAnalyzers: map[string]int{},
PostAnalyzers: make(map[string]int),
},
wantPostScannerVersions: map[string]int{
"happy": 1,
@@ -48,16 +48,16 @@ func TestManager_Register(t *testing.T) {
Analyzers: map[string]int{
"analyzer": 1,
},
PostAnalyzers: map[string]int{},
PostAnalyzers: make(map[string]int),
},
wantPostScannerVersions: map[string]int{},
wantPostScannerVersions: make(map[string]int),
},
{
name: "only post scanner",
moduleDir: "testdata/scanner",
wantAnalyzerVersions: analyzer.Versions{
Analyzers: map[string]int{},
PostAnalyzers: map[string]int{},
Analyzers: make(map[string]int),
PostAnalyzers: make(map[string]int),
},
wantPostScannerVersions: map[string]int{
"scanner": 2,
@@ -67,10 +67,10 @@ func TestManager_Register(t *testing.T) {
name: "no module dir",
moduleDir: "no-such-dir",
wantAnalyzerVersions: analyzer.Versions{
Analyzers: map[string]int{},
PostAnalyzers: map[string]int{},
Analyzers: make(map[string]int),
PostAnalyzers: make(map[string]int),
},
wantPostScannerVersions: map[string]int{},
wantPostScannerVersions: make(map[string]int),
},
{
name: "pass enabled modules",
@@ -84,7 +84,7 @@ func TestManager_Register(t *testing.T) {
"happy": 1,
"analyzer": 1,
},
PostAnalyzers: map[string]int{},
PostAnalyzers: make(map[string]int),
},
wantPostScannerVersions: map[string]int{
"happy": 1,

View File

@@ -70,15 +70,15 @@ func TestClient_LoadBuiltinPolicies(t *testing.T) {
name: "happy path",
cacheDir: "testdata/happy",
want: []string{
filepath.Join("testdata/happy/policy/content/kubernetes"),
filepath.Join("testdata/happy/policy/content/docker"),
filepath.Join("testdata", "happy", "policy", "content", "kubernetes"),
filepath.Join("testdata", "happy", "policy", "content", "docker"),
},
},
{
name: "empty roots",
cacheDir: "testdata/empty",
want: []string{
filepath.Join("testdata/empty/policy/content"),
filepath.Join("testdata", "empty", "policy", "content"),
},
},
{

View File

@@ -780,7 +780,7 @@ func TestPackageURL_LangType(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p := (purl.PackageURL)(tt.purl)
p := purl.PackageURL(tt.purl)
assert.Equalf(t, tt.want, p.LangType(), "LangType()")
})
}

View File

@@ -110,7 +110,7 @@ func TestGet(t *testing.T) {
name: "keychain",
args: args{
imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr),
config: fmt.Sprintf(`{"auths": {"%s": {"auth": %q}}}`, serverAddr, encode("test", "testpass")),
config: fmt.Sprintf(`{"auths": {%q: {"auth": %q}}}`, serverAddr, encode("test", "testpass")),
option: types.RegistryOptions{
Insecure: true,
},
@@ -180,7 +180,7 @@ func TestGet(t *testing.T) {
name: "bad keychain",
args: args{
imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr),
config: fmt.Sprintf(`{"auths": {"%s": {"auth": %q}}}`, serverAddr, encode("foo", "bar")),
config: fmt.Sprintf(`{"auths": {%q: {"auth": %q}}}`, serverAddr, encode("foo", "bar")),
option: types.RegistryOptions{
Insecure: true,
},

View File

@@ -263,7 +263,7 @@ func Test_newServeMux(t *testing.T) {
if tt.header == nil {
resp, err = http.Get(url)
} else {
req, err := http.NewRequest(http.MethodPost, url, nil)
req, err := http.NewRequest(http.MethodPost, url, http.NoBody)
require.NoError(t, err)
req.Header = tt.header

View File

@@ -115,7 +115,7 @@ func TestScanServer_Scan(t *testing.T) {
Severity: common.Severity_MEDIUM,
SeveritySource: "nvd",
Layer: &common.Layer{},
Cvss: map[string]*common.CVSS{},
Cvss: make(map[string]*common.CVSS),
VendorSeverity: map[string]common.Severity{
string(vulnerability.NVD): common.Severity_MEDIUM,
},

View File

@@ -533,7 +533,7 @@ func TestEncoder_Encode(t *testing.T) {
uuid.MustParse("3ff14136-e09f-4df9-80ea-000000000005"): nil,
uuid.MustParse("3ff14136-e09f-4df9-80ea-000000000006"): nil,
},
wantVulns: map[uuid.UUID][]core.Vulnerability{},
wantVulns: make(map[uuid.UUID][]core.Vulnerability),
},
{
name: "invalid digest",

View File

@@ -18,7 +18,7 @@ func touch(t *testing.T, name string) {
}
}
func write(t *testing.T, name string, content string) {
func write(t *testing.T, name, content string) {
err := os.WriteFile(name, []byte(content), 0666)
if err != nil {
t.Fatal(err)