Update full linter list and enable some easily resolved new ones

This commit is contained in:
Katrina Verey
2022-03-30 14:07:54 -04:00
parent 0a9c5cb0cf
commit 71bf0d5d14
61 changed files with 185 additions and 184 deletions

View File

@@ -1,58 +0,0 @@
run:
deadline: 5m
linters:
disable-all: true
enable:
- bodyclose
- deadcode
- depguard
- dogsled
- dupl
# - errcheck
- exportloopref
# - funlen
- gochecknoinits
- goconst
- gocritic
- gocyclo
- gofmt
- goimports
- gosec
- gosimple
- govet
- ineffassign
- lll
- misspell
- nakedret
- nolintlint
- revive
- staticcheck
- structcheck
# - stylecheck # seems redundant with revive, which replaced golint
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace
linters-settings:
dupl:
threshold: 400
lll:
line-length: 170
gocyclo:
min-complexity: 15
revive:
rules:
- name: var-naming
arguments:
- [ "ID", "API", "JSON" ] # AllowList
- [ ] # DenyList
issues:
exclude-rules:
- linters:
- revive
text: "don't use leading"

View File

@@ -3,47 +3,91 @@
run:
deadline: 5m
skip-dirs:
- yaml/internal/k8sgen/pkg
- internal/forked
linters:
# please, do not use `enable-all`: it's deprecated and will be removed soon.
# inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint
disable-all: true
enable:
- asciicheck
- bidichk
- bodyclose
- contextcheck
# - cyclop
- deadcode
- depguard
- dogsled
- dupl
# - errcheck
- durationcheck
# - errcheck # TODO: enable going forward
# - errname # TODO: enable going forward
# - errorlint # TODO: enable going forward
# - exhaustive # TODO: enable going forward
# - exhaustivestruct
- exportloopref
# - forbidigo
# - forcetypeassert # TODO: enable going forward
# - funlen
# - gci
# - gochecknoglobals
- gochecknoinits
# - gocognit
- goconst
- gocritic
- gocyclo
# - godot
# - godox
# - goerr113 # TODO: enable going forward
- gofmt
# - gofumpt
- goheader
- goimports
# - gomnd
- gomoddirectives
- gomodguard
- goprintffuncname
- gosec
- gosimple
- govet
# - ifshort
- importas
- ineffassign
# - ireturn
- lll
- makezero
- misspell
- nakedret
# - nestif # TODO: enable going forward
# - nilerr # TODO: enable going forward
# - nilnil
# - nlreturn
# - noctx
- nolintlint
# - paralleltest
# - prealloc # TODO: enable going forward
- predeclared
- promlinter
- revive
- rowserrcheck
- sqlclosecheck
- staticcheck
- structcheck
# - stylecheck # seems redundant with revive, which replaced golint
# - stylecheck
- tagliatelle
- tenv
# - testpackage # TODO: enable going forward
- thelper
- tparallel
- typecheck
- unconvert
- unparam
- unused
- varcheck
# - varnamelen
- wastedassign
- whitespace
# - wrapcheck # TODO: enable going forward
# - wsl
linters-settings:
dupl:
@@ -58,11 +102,14 @@ linters-settings:
arguments:
- [ "ID", "API", "JSON" ] # AllowList
- [ ] # DenyList
gomoddirectives:
replace-local: true
gosec:
config:
G306: "0644"
issues:
max-same-issues: 0
exclude-rules:
- linters:
- revive

View File

@@ -203,15 +203,15 @@ clean-kustomize-external-go-plugin:
.PHONY: lint-kustomize
lint-kustomize: $(MYGOBIN)/golangci-lint-kustomize $(builtinplugins)
cd api; $(MYGOBIN)/golangci-lint-kustomize \
-c ../.golangci-kustomize.yml \
-c ../.golangci.yml \
--path-prefix api \
run ./...
cd kustomize; $(MYGOBIN)/golangci-lint-kustomize \
-c ../.golangci-kustomize.yml \
-c ../.golangci.yml \
--path-prefix kustomize \
run ./...
cd cmd/pluginator; $(MYGOBIN)/golangci-lint-kustomize \
-c ../../.golangci-kustomize.yml \
-c ../../.golangci.yml \
--path-prefix cmd/pluginator \
run ./...

View File

@@ -341,6 +341,7 @@ data:
// The return value indicates whether we should skip the rest of the test case
// due to the error result.
func SkipRest(t *testing.T, desc string, err error, contains string) bool {
t.Helper()
if err != nil {
if len(contains) == 0 {
t.Errorf("case %q, expect nil error but got %q", desc, err.Error())

View File

@@ -22,6 +22,7 @@ import (
)
func makeResAccumulator(t *testing.T) *ResAccumulator {
t.Helper()
ra := MakeEmptyAccumulator()
err := ra.MergeConfig(builtinconfig.MakeDefaultConfig())
if err != nil {
@@ -133,6 +134,7 @@ func TestResolveVarsOneUnused(t *testing.T) {
}
func expectLog(t *testing.T, log bytes.Buffer, expect string) {
t.Helper()
if !strings.Contains(log.String(), expect) {
t.Fatalf("expected log containing '%s', got '%s'", expect, log.String())
}

View File

@@ -20,6 +20,7 @@ func makeAndLoadKustTarget(
t *testing.T,
fSys filesys.FileSystem,
root string) *target.KustTarget {
t.Helper()
kt := makeKustTargetWithRf(t, fSys, root, provider.NewDefaultDepProvider())
if err := kt.Load(); err != nil {
t.Fatalf("Unexpected load error %v", err)
@@ -32,6 +33,7 @@ func makeKustTargetWithRf(
fSys filesys.FileSystem,
root string,
pvd *provider.DepProvider) *target.KustTarget {
t.Helper()
ldr, err := fLdr.NewLoader(fLdr.RestrictionRootOnly, root, fSys)
if err != nil {
t.Fatal(err)

View File

@@ -179,9 +179,11 @@ func TestDefaultAbsPluginHomeNoXdgJustHomeDir(t *testing.T) {
}
func setenv(t *testing.T, key, value string) {
t.Helper()
require.NoError(t, os.Setenv(key, value))
}
func unsetenv(t *testing.T, key string) {
t.Helper()
require.NoError(t, os.Unsetenv(key))
}

View File

@@ -214,6 +214,7 @@ spec:
}
func skipIfNoDocker(t *testing.T) {
t.Helper()
if _, err := exec.LookPath("docker"); err != nil {
t.Skip("skipping because docker binary wasn't found in PATH")
}

View File

@@ -67,6 +67,7 @@ metadata:
}
func makeTmpDir(t *testing.T) string {
t.Helper()
base, err := os.Getwd()
if err != nil {
t.Fatalf("err %v", err)

View File

@@ -240,6 +240,7 @@ func commonSetupForLoaderRestrictionTest() (string, filesys.FileSystem, error) {
// in or below the loader root.
func doSanityChecksAndDropIntoBase(
t *testing.T, l ifc.Loader) ifc.Loader {
t.Helper()
data, err := l.Load(path.Join("base", "okayData"))
if err != nil {
t.Fatalf("unexpected error: %v", err)

View File

@@ -56,12 +56,14 @@ var origin2 = &resource.Origin{
}
func doAppend(t *testing.T, w ResMap, r *resource.Resource) {
t.Helper()
err := w.Append(r)
if err != nil {
t.Fatalf("append error: %v", err)
}
}
func doRemove(t *testing.T, w ResMap, id resid.ResId) {
t.Helper()
err := w.Remove(id)
if err != nil {
t.Fatalf("remove error: %v", err)

View File

@@ -13,6 +13,7 @@ import (
)
func setupRMForPatchTargets(t *testing.T) ResMap {
t.Helper()
result, err := rmF.NewResMapFromBytes([]byte(`
apiVersion: group1/v1
kind: Kind1

View File

@@ -26,7 +26,6 @@ type Resource struct {
refVarNames []string
}
// nolint
var BuildAnnotations = []string{
utils.BuildAnnotationPreviousKinds,
utils.BuildAnnotationPreviousNames,

View File

@@ -32,6 +32,7 @@ func run(input string, f kio.Filter) (string, error) {
// RunFilter runs filter and panic if there is error
func RunFilter(t *testing.T, input string, f kio.Filter) string {
t.Helper()
output, err := run(input, f)
if !assert.NoError(t, err) {
t.FailNow()
@@ -41,6 +42,7 @@ func RunFilter(t *testing.T, input string, f kio.Filter) string {
// RunFilterE runs filter and return error if there is
func RunFilterE(t *testing.T, input string, f kio.Filter) (string, error) {
t.Helper()
output, err := run(input, f)
if err != nil {
return "", err

View File

@@ -22,11 +22,13 @@ type Harness struct {
}
func MakeHarness(t *testing.T) Harness {
t.Helper()
return MakeHarnessWithFs(t, filesys.MakeFsInMemory())
}
func MakeHarnessWithFs(
t *testing.T, fSys filesys.FileSystem) Harness {
t.Helper()
return Harness{
t: t,
fSys: fSys,

View File

@@ -47,6 +47,7 @@ type HarnessEnhanced struct {
}
func MakeEnhancedHarness(t *testing.T) *HarnessEnhanced {
t.Helper()
r := makeBaseEnhancedHarness(t)
r.Harness = MakeHarnessWithFs(t, filesys.MakeFsInMemory())
// Point the Harness's file loader to the root ('/')
@@ -56,6 +57,7 @@ func MakeEnhancedHarness(t *testing.T) *HarnessEnhanced {
}
func MakeEnhancedHarnessWithTmpRoot(t *testing.T) *HarnessEnhanced {
t.Helper()
r := makeBaseEnhancedHarness(t)
fSys := filesys.MakeFsOnDisk()
r.Harness = MakeHarnessWithFs(t, fSys)
@@ -72,6 +74,7 @@ func MakeEnhancedHarnessWithTmpRoot(t *testing.T) *HarnessEnhanced {
}
func makeBaseEnhancedHarness(t *testing.T) *HarnessEnhanced {
t.Helper()
rf := resmap.NewFactory(
provider.NewDefaultDepProvider().GetResourceFactory())
return &HarnessEnhanced{

View File

@@ -26,6 +26,7 @@ func AssertActualEqualsExpectedWithTweak(
t *testing.T,
m resmap.ResMap,
tweaker func([]byte) []byte, expected string) {
t.Helper()
if m == nil {
t.Fatalf("Map should not be nil.")
}
@@ -49,13 +50,14 @@ func AssertActualEqualsExpectedWithTweak(
// Pretty printing of file differences.
func reportDiffAndFail(
t *testing.T, actual []byte, expected string) {
t.Helper()
sE, maxLen := convertToArray(expected)
sA, _ := convertToArray(string(actual))
fmt.Println("===== ACTUAL BEGIN ========================================")
fmt.Print(string(actual))
fmt.Println("===== ACTUAL END ==========================================")
format := fmt.Sprintf("%%s %%-%ds %%s\n", maxLen+4)
limit := 0
var limit int
if len(sE) < len(sA) {
limit = len(sE)
} else {

View File

@@ -25,6 +25,7 @@ type pluginTestEnv struct {
// newPluginTestEnv returns a new instance of pluginTestEnv.
func newPluginTestEnv(t *testing.T) *pluginTestEnv {
t.Helper()
return &pluginTestEnv{t: t}
}

View File

@@ -20,18 +20,22 @@ type rmBuilder struct {
}
func NewSeededRmBuilder(t *testing.T, rf *resource.Factory, m resmap.ResMap) *rmBuilder {
t.Helper()
return &rmBuilder{t: t, rf: rf, m: m}
}
func NewRmBuilder(t *testing.T, rf *resource.Factory) *rmBuilder {
t.Helper()
return NewSeededRmBuilder(t, rf, resmap.New())
}
func NewRmBuilderDefault(t *testing.T) *rmBuilder {
t.Helper()
return NewSeededRmBuilderDefault(t, resmap.New())
}
func NewSeededRmBuilderDefault(t *testing.T, m resmap.ResMap) *rmBuilder {
t.Helper()
return NewSeededRmBuilder(
t, provider.NewDefaultDepProvider().GetResourceFactory(), m)
}

View File

@@ -22,11 +22,13 @@ const SAD = "i'm not happy Bob, NOT HAPPY"
// MakeHappyMapValidator makes a fakeValidator that always passes.
func MakeHappyMapValidator(t *testing.T) *fakeValidator {
t.Helper()
return &fakeValidator{happy: true, t: t}
}
// MakeSadMapValidator makes a fakeValidator that always fails.
func MakeSadMapValidator(t *testing.T) *fakeValidator {
t.Helper()
return &fakeValidator{happy: false, t: t}
}

View File

@@ -71,7 +71,7 @@ type HelmChart struct {
// IncludeCRDs specifies if Helm should also generate CustomResourceDefinitions.
// Defaults to 'false'.
IncludeCRDs bool `json:"includeCRDs,omitempty" yaml:"includeCRDs,omitempty"`
IncludeCRDs bool `json:"includeCRDs,omitempty" yaml:"includeCRDs,omitempty"` // nolint: tagliatelle
}
// HelmChartArgs contains arguments to helm.

View File

@@ -1,66 +0,0 @@
# Copyright 2019 The Kubernetes Authors.
# SPDX-License-Identifier: Apache-2.0
run:
deadline: 5m
linters:
# please, do not use `enable-all`: it's deprecated and will be removed soon.
# inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint
disable-all: true
enable:
- bodyclose
- deadcode
- depguard
- dogsled
- dupl
# - errcheck
- exportloopref
# - funlen
- gochecknoinits
- goconst
- gocritic
- gocyclo
- gofmt
- goimports
- gosec
- gosimple
- govet
- ineffassign
- lll
- misspell
- nakedret
- nolintlint
- revive
- staticcheck
- structcheck
# - stylecheck # seems redundant with revive, which replaced golint
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace
linters-settings:
dupl:
threshold: 400
lll:
line-length: 170
gocyclo:
min-complexity: 30
revive:
rules:
- name: var-naming
arguments:
- [ "ID", "API", "JSON" ] # AllowList
- [ ] # DenyList
gosec:
config:
G306: "0644"
issues:
exclude-rules:
- linters:
- revive
text: "don't use leading"

View File

@@ -37,7 +37,8 @@ lint: $(GOBIN)/golangci-lint
$(GOBIN)/golangci-lint \
--skip-dirs $(k8sGenDir) \
run ./... \
--path-prefix=cmd/config
--path-prefix=cmd/config \
-c ../../.golangci.yml
license: $(GOBIN)/addlicense
$(GOBIN)/addlicense \

View File

@@ -88,6 +88,7 @@ func TestAnnotateCommand(t *testing.T) {
}
func initTestDir(t *testing.T) string {
t.Helper()
d, err := ioutil.TempDir("", "kustomize-annotate-test")
if !assert.NoError(t, err) {
t.FailNow()

View File

@@ -166,7 +166,6 @@ func (r *CatRunner) catFilters() []kio.Filter {
return fltrs
}
// nolint
func (r *CatRunner) out(w io.Writer) ([]kio.Writer, error) {
var outputs []kio.Writer
var functionConfig *yaml.RNode

View File

@@ -36,6 +36,7 @@ type test struct {
}
func runTests(t *testing.T, tests []test) {
t.Helper()
dir := build()
bin := filepath.Join(dir, kyamlBin)

View File

@@ -46,7 +46,6 @@ See discussion in https://github.com/kubernetes-sigs/kustomize/issues/3953.`)
return err
}
// nolint
func (r *SinkRunner) runE(c *cobra.Command, args []string) error {
var outputs []kio.Writer
if len(args) == 1 {

View File

@@ -132,11 +132,11 @@ var StackOnError bool
const cmdName = "kustomize fn"
// FixDocs replaces instances of old with new in the docs for c
func FixDocs(new string, c *cobra.Command) {
c.Use = strings.ReplaceAll(c.Use, cmdName, new)
c.Short = strings.ReplaceAll(c.Short, cmdName, new)
c.Long = strings.ReplaceAll(c.Long, cmdName, new)
c.Example = strings.ReplaceAll(c.Example, cmdName, new)
func FixDocs(newStr string, c *cobra.Command) {
c.Use = strings.ReplaceAll(c.Use, cmdName, newStr)
c.Short = strings.ReplaceAll(c.Short, cmdName, newStr)
c.Long = strings.ReplaceAll(c.Long, cmdName, newStr)
c.Example = strings.ReplaceAll(c.Example, cmdName, newStr)
}
// containsString returns true if slice contains s

View File

@@ -12,6 +12,7 @@ import (
)
func makeTempDir(t *testing.T) string {
t.Helper()
s, err := ioutil.TempDir("", "pluginator-*")
assert.NoError(t, err)
return s
@@ -99,6 +100,7 @@ items:
}
func runKrmFunction(t *testing.T, input []byte, dir string) []byte {
t.Helper()
cmd := exec.Command("go", "run", ".")
ib := bytes.NewReader(input)
cmd.Stdin = ib

View File

@@ -16,6 +16,7 @@ import (
var factory = provider.NewDefaultDepProvider().GetResourceFactory()
func readKustomizationFS(t *testing.T, fSys filesys.FileSystem) *types.Kustomization {
t.Helper()
kf, err := kustfile.NewKustomizationFile(fSys)
if err != nil {
t.Errorf("unexpected new error %v", err)

View File

@@ -16,6 +16,7 @@ import (
)
func makeKustomization(t *testing.T) *types.Kustomization {
t.Helper()
fSys := filesys.MakeFsInMemory()
testutils_test.WriteTestKustomization(fSys)
kf, err := kustfile.NewKustomizationFile(fSys)

View File

@@ -27,6 +27,7 @@ func makeKustomizationFS() filesys.FileSystem {
}
func readKustomizationFS(t *testing.T, fSys filesys.FileSystem) *types.Kustomization {
t.Helper()
kf, err := kustfile.NewKustomizationFile(fSys)
if err != nil {
t.Errorf("unexpected new error %v", err)
@@ -39,6 +40,7 @@ func readKustomizationFS(t *testing.T, fSys filesys.FileSystem) *types.Kustomiza
}
func makeKustomization(t *testing.T) *types.Kustomization {
t.Helper()
fSys := makeKustomizationFS()
return readKustomizationFS(t, fSys)
}

View File

@@ -43,6 +43,7 @@ type Case struct {
// collection Name (e.g. transformers or resources) and newRemoveCmdToTest function.
func ExecuteTestCases(t *testing.T, testCases []Case, collectionName string,
newRemoveCmdToTest func(filesys.FileSystem) *cobra.Command) {
t.Helper()
for _, tc := range testCases {
t.Run(tc.Description, func(t *testing.T) {
fSys := filesys.MakeFsInMemory()

View File

@@ -17,6 +17,7 @@ const invalidAnnotationKey string = "invalid annotation key: see the syntax and
"https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/"
func makeAnnotationKustomization(t *testing.T) *types.Kustomization {
t.Helper()
fSys := filesys.MakeFsInMemory()
testutils_test.WriteTestKustomization(fSys)
kf, err := kustfile.NewKustomizationFile(fSys)

View File

@@ -14,6 +14,7 @@ import (
)
func makeKustomization(t *testing.T) *types.Kustomization {
t.Helper()
fSys := filesys.MakeFsInMemory()
testutils_test.WriteTestKustomization(fSys)
kf, err := kustfile.NewKustomizationFile(fSys)

View File

@@ -34,7 +34,10 @@ clean:
lint: $(MYGOBIN)/golangci-lint
$(MYGOBIN)/golangci-lint \
run ./... \
--path-prefix=kyaml
--path-prefix=kyaml \
-c ../.golangci.yml \
--skip-dirs yaml/internal/k8sgen/pkg \
--skip-dirs internal/forked
license: $(MYGOBIN)/addlicense

View File

@@ -188,8 +188,7 @@ func SyncFile(src, dst string) error {
// deleteFile deletes file from path, returns no error if file doesn't exist
func deleteFile(path string) error {
_, err := os.Stat(path)
if err != nil {
if _, err := os.Stat(path); err != nil {
// return nil if file doesn't exist
return nil
}

View File

@@ -14,8 +14,7 @@ import (
func TestJoin(t *testing.T) {
fSys := MakeFsInMemory()
err := fSys.Mkdir("/foo")
if err != nil {
if err := fSys.Mkdir("/foo"); err != nil {
t.Fatalf("unexpected err: %v", err)
}
d, f, err := fSys.CleanedAbs("/foo")

View File

@@ -26,6 +26,7 @@ func TestNotExistErr(t *testing.T) {
}
func testNotExistErr(t *testing.T, fs FileSystem) {
t.Helper()
const path = "bad-dir/file.txt"
err := fs.RemoveAll(path)

View File

@@ -96,6 +96,7 @@ func TestMakeFsInMemory(t *testing.T) {
func runBasicOperations(
t *testing.T, tName string, isFSysRooted bool,
cases []pathCase, fSys FileSystem) {
t.Helper()
for _, c := range cases {
err := fSys.WriteFile(c.arg, []byte(content))
if c.errStr != "" {
@@ -370,6 +371,7 @@ func TestAddFile(t *testing.T) {
func checkNode(
t *testing.T, what string, f *fsNode, name string,
size int, isDir bool, path string) {
t.Helper()
if f.isNodeADir() != isDir {
t.Fatalf("%s; unexpected isNodeADir = %v", what, f.isNodeADir())
}
@@ -387,6 +389,7 @@ func checkNode(
func checkOsStat(
t *testing.T, what string, f File, name string,
size int, isDir bool) {
t.Helper()
info, err := f.Stat()
if err != nil {
t.Fatalf("%s; unexpected stat error %v", what, err)
@@ -473,6 +476,7 @@ var bunchOfFiles = []struct {
}
func makeLoadedFileTree(t *testing.T) *fsNode {
t.Helper()
n := MakeEmptyDirInMemory()
var err error
expectedFileCount := 0
@@ -487,8 +491,7 @@ func makeLoadedFileTree(t *testing.T) *fsNode {
t.Fatalf("unexpected error %v", err)
}
}
fc := n.FileCount()
if fc != expectedFileCount {
if fc := n.FileCount(); fc != expectedFileCount {
t.Fatalf("expected file count %d, got %d",
expectedFileCount, fc)
}
@@ -565,8 +568,7 @@ func TestRemove(t *testing.T) {
}
orgCount -= 1
fc := n.FileCount()
if fc != orgCount {
if fc := n.FileCount(); fc != orgCount {
t.Fatalf("expected file count %d, got %d",
orgCount, fc)
}

View File

@@ -17,6 +17,7 @@ import (
)
func makeTestDir(t *testing.T) (FileSystem, string) {
t.Helper()
fSys := MakeFsOnDisk()
td, err := ioutil.TempDir("", "kustomize_testing_dir")
if err != nil {

View File

@@ -121,7 +121,7 @@ func InsertPathPart(path string, pos int, part string) string {
result := make([]string, len(parts)+1)
copy(result, parts[0:pos])
result[pos] = part
return PathJoin(append(result, parts[pos:]...))
return PathJoin(append(result, parts[pos:]...)) // nolint: makezero
}
func IsHiddenFilePath(pattern string) bool {

View File

@@ -159,6 +159,7 @@ func TestPathSplitAndJoin(t *testing.T) {
}
for n, c := range cases {
f := func(t *testing.T, original string, expected []string) {
t.Helper()
actual := PathSplit(original)
if len(actual) != len(expected) {
t.Fatalf(

View File

@@ -81,6 +81,7 @@ type CommandResultsChecker struct {
// Assert runs the command with the input provided in each valid test directory
// and verifies that the actual output and error match the fixtures in the directory.
func (rc *CommandResultsChecker) Assert(t *testing.T) bool {
t.Helper()
if rc.ConfigInputFilename == "" {
rc.ConfigInputFilename = DefaultConfigInputFilename
}
@@ -109,6 +110,7 @@ func (rc *CommandResultsChecker) isTestDir(path string) bool {
}
func (rc *CommandResultsChecker) runInCurrentDir(t *testing.T) (string, string) {
t.Helper()
_, err := os.Stat(rc.ConfigInputFilename)
if os.IsNotExist(err) {
t.Errorf("Test case is missing FunctionConfig input file (default: %s)", DefaultConfigInputFilename)
@@ -180,6 +182,7 @@ type ProcessorResultsChecker struct {
// Assert runs the processor with the input provided in each valid test directory
// and verifies that the actual output and error match the fixtures in the directory.
func (rc *ProcessorResultsChecker) Assert(t *testing.T) bool {
t.Helper()
if rc.InputFilename == "" {
rc.InputFilename = DefaultInputFilename
}
@@ -205,6 +208,7 @@ func (rc *ProcessorResultsChecker) isTestDir(path string) bool {
}
func (rc *ProcessorResultsChecker) runInCurrentDir(t *testing.T) (string, string) {
t.Helper()
_, err := os.Stat(rc.InputFilename)
if os.IsNotExist(err) {
t.Errorf("Test case is missing input file (default: %s)", DefaultInputFilename)
@@ -232,6 +236,7 @@ type AssertionFunc func(t *testing.T, expected string, actual string)
// RequireEachLineMatches is an AssertionFunc that treats each line of expected string
// as a regex that must match the actual string.
func RequireEachLineMatches(t *testing.T, expected, actual string) {
t.Helper()
// Check that each expected line matches the output
actual = standardizeSpacing(actual)
for _, msg := range strings.Split(standardizeSpacing(expected), "\n") {
@@ -242,6 +247,7 @@ func RequireEachLineMatches(t *testing.T, expected, actual string) {
// RequireStrippedStringsEqual is an AssertionFunc that does a simple string comparison
// of expected and actual after normalizing whitespace.
func RequireStrippedStringsEqual(t *testing.T, expected, actual string) {
t.Helper()
require.Equal(t,
standardizeSpacing(expected),
standardizeSpacing(actual))
@@ -330,6 +336,7 @@ func (rc *checkerCore) shouldUpdateFixtures() bool {
}
func (rc *checkerCore) updateFixtures(t *testing.T, actualOutput string, actualError string) {
t.Helper()
if actualError != "" {
require.NoError(t, ioutil.WriteFile(rc.expectedErrorFilename, []byte(actualError), 0600))
}
@@ -340,14 +347,17 @@ func (rc *checkerCore) updateFixtures(t *testing.T, actualOutput string, actualE
}
func (rc *checkerCore) assertOutputMatches(t *testing.T, expected string, actual string) {
t.Helper()
rc.outputAssertionFunc(t, expected, actual)
}
func (rc *checkerCore) assertErrorMatches(t *testing.T, expected string, actual string) {
t.Helper()
rc.errorAssertionFunc(t, expected, actual)
}
func (rc *checkerCore) readAssertionFiles(t *testing.T) (string, string) {
t.Helper()
// read the expected results
var expectedOutput, expectedError string
if rc.expectedOutputFilename != "" {
@@ -385,6 +395,7 @@ func (rc *checkerCore) readAssertionFiles(t *testing.T) (string, string) {
// under test in each directory, and then runs assertions on the returned output and error results.
// It triggers a test failure if no valid test directories were found.
func runAllTestCases(t *testing.T, checker resultsChecker) {
t.Helper()
checker.resetTestCasesRun()
err := filepath.Walk(checker.rootDir(),
func(path string, info os.FileInfo, err error) error {
@@ -399,6 +410,7 @@ func runAllTestCases(t *testing.T, checker resultsChecker) {
}
func runDirectoryTestCase(t *testing.T, path string, checker resultsChecker) {
t.Helper()
// cd into the directory so we can test functions that refer to local files by relative paths
d, err := os.Getwd()
require.NoError(t, err)

View File

@@ -82,7 +82,7 @@ type KRMFunctionVersion struct {
type KRMFunctionValidation struct {
// OpenAPIV3Schema is the OpenAPI v3 schema for an instance of the KRM function.
OpenAPIV3Schema *spec.Schema `yaml:"openAPIV3Schema,omitempty" json:"openAPIV3Schema,omitempty"`
OpenAPIV3Schema *spec.Schema `yaml:"openAPIV3Schema,omitempty" json:"openAPIV3Schema,omitempty"` // nolint: tagliatelle
}
type KRMFunctionNames struct {

View File

@@ -242,6 +242,7 @@ func TestFilter_ExitCode(t *testing.T) {
}
func getWorkingDir(t *testing.T) string {
t.Helper()
wd, err := os.Getwd()
require.NoError(t, err)
return wd

View File

@@ -40,8 +40,7 @@ func (sf *Filter) String() string {
}
func (sf *Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
err := sf.setup()
if err != nil {
if err := sf.setup(); err != nil {
return nil, err
}
sf.FunctionFilter.Run = sf.Run

View File

@@ -91,8 +91,7 @@ func TestEmptyInput(t *testing.T) {
Outputs: []Writer{output},
}
err := p.Execute()
if err != nil {
if err := p.Execute(); err != nil {
t.Fatal(err)
}
@@ -132,8 +131,7 @@ func TestEmptyInputWithFilter(t *testing.T) {
Filters: filters,
}
err := p.Execute()
if err != nil {
if err := p.Execute(); err != nil {
t.Fatal(err)
}

View File

@@ -65,6 +65,7 @@ func TestLocalPackageReader_Read_pkg(t *testing.T) {
{path: "c_test.yaml", content: readFileC},
{path: "d_test.yaml", content: readFileD},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
FileSystem: filesys.FileSystemOrOnDisk{FileSystem: mockFS},
@@ -136,6 +137,7 @@ func TestLocalPackageReader_Read_pkgAndSkipFile(t *testing.T) {
{path: "c_test.yaml", content: readFileC},
{path: "d_test.yaml", content: readFileD},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
FileSkipFunc: func(relPath string) bool { return relPath == "d_test.yaml" },
@@ -207,6 +209,7 @@ func TestLocalPackageReader_Read_JSON(t *testing.T) {
}`),
},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
MatchFilesGlob: []string{"*.json"},
@@ -246,6 +249,7 @@ func TestLocalPackageReader_Read_file(t *testing.T) {
{path: "a_test.yaml", content: readFileA},
{path: "b_test.yaml", content: readFileB},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: filepath.Join(path, "a_test.yaml"),
FileSystem: filesys.FileSystemOrOnDisk{FileSystem: mockFS},
@@ -286,6 +290,7 @@ func TestLocalPackageReader_Read_pkgOmitAnnotations(t *testing.T) {
{path: "a_test.yaml", content: readFileA},
{path: "b_test.yaml", content: readFileB},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
OmitReaderAnnotations: true,
@@ -322,6 +327,7 @@ func TestLocalPackageReader_Read_PreserveSeqIndent(t *testing.T) {
{path: "a_test.yaml", content: readFileA},
{path: "b_test.yaml", content: readFileB},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
PreserveSeqIndent: true,
@@ -379,6 +385,7 @@ func TestLocalPackageReader_Read_nestedDirs(t *testing.T) {
{path: "a/b/a_test.yaml", content: readFileA},
{path: "a/b/b_test.yaml", content: readFileB},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
FileSystem: filesys.FileSystemOrOnDisk{FileSystem: mockFS},
@@ -433,6 +440,7 @@ func TestLocalPackageReader_Read_matchRegex(t *testing.T) {
{path: "a/b/a_test.yaml", content: readFileA},
{path: "a/b/b_test.yaml", content: readFileB},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
MatchFilesGlob: []string{`a*.yaml`},
@@ -478,6 +486,7 @@ func TestLocalPackageReader_Read_skipSubpackage(t *testing.T) {
{path: "a/c/c_test.yaml", content: readFileB},
{path: "a/c/pkgFile", content: pkgFile},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
PackageFileName: "pkgFile",
@@ -523,6 +532,7 @@ func TestLocalPackageReader_Read_includeSubpackage(t *testing.T) {
{path: "a/c/c_test.yaml", content: readFileB},
{path: "a/c/pkgFile", content: pkgFile},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
IncludeSubpackages: true,
@@ -581,6 +591,7 @@ type mockFile struct {
}
func testOnDiskAndOnMem(t *testing.T, files []mockFile, f func(t *testing.T, path string, fs filesys.FileSystem)) {
t.Helper()
t.Run("on_disk", func(t *testing.T) {
var dirs []string
for _, file := range files {
@@ -627,6 +638,7 @@ func TestLocalPackageReader_ReadBareSeqNodes(t *testing.T) {
{path: "a/c"},
{path: "e_test.yaml", content: readFileE},
}, func(t *testing.T, path string, mockFS filesys.FileSystem) {
t.Helper()
rfr := LocalPackageReader{
PackagePath: path,
FileSystem: filesys.FileSystemOrOnDisk{FileSystem: mockFS},

View File

@@ -25,6 +25,7 @@ import (
// - ReaderAnnotations are cleared when writing the Resources
func TestLocalPackageWriter_Write(t *testing.T) {
testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) {
t.Helper()
d, node1, node2, node3, cleanup := getWriterInputs(t, fs)
defer cleanup()
@@ -57,6 +58,7 @@ g:
// - ReaderAnnotations are kept when writing the Resources
func TestLocalPackageWriter_Write_keepReaderAnnotations(t *testing.T) {
testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) {
t.Helper()
d, node1, node2, node3, cleanup := getWriterInputs(t, fs)
defer cleanup()
@@ -108,6 +110,7 @@ metadata:
// - ClearAnnotations are removed from Resources
func TestLocalPackageWriter_Write_clearAnnotations(t *testing.T) {
testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) {
t.Helper()
d, node1, node2, node3, cleanup := getWriterInputs(t, fs)
defer cleanup()
@@ -141,6 +144,7 @@ g:
// - If a relative path above the package is defined, write fails
func TestLocalPackageWriter_Write_failRelativePath(t *testing.T) {
testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) {
t.Helper()
d, node1, node2, node3, cleanup := getWriterInputs(t, fs)
defer cleanup()
@@ -171,6 +175,7 @@ metadata:
// - If a non-int index is given, fail
func TestLocalPackageWriter_Write_invalidIndex(t *testing.T) {
testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) {
t.Helper()
d, node1, node2, node3, cleanup := getWriterInputs(t, fs)
defer cleanup()
@@ -201,6 +206,7 @@ metadata:
// - If config.kubernetes.io/path is absolute, fail
func TestLocalPackageWriter_Write_absPath(t *testing.T) {
testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) {
t.Helper()
d, node1, node2, node3, cleanup := getWriterInputs(t, fs)
defer cleanup()
@@ -232,6 +238,7 @@ metadata:
// - If config.kubernetes.io/path or index are missing, then default them
func TestLocalPackageWriter_Write_missingAnnotations(t *testing.T) {
testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) {
t.Helper()
d, node1, node2, node3, cleanup := getWriterInputs(t, fs)
defer cleanup()
@@ -263,6 +270,7 @@ metadata:
// - If config.kubernetes.io/path is a directory, fail
func TestLocalPackageWriter_Write_pathIsDir(t *testing.T) {
testWriterOnDiskAndOnMem(t, func(t *testing.T, fs filesys.FileSystem) {
t.Helper()
d, node1, node2, node3, cleanup := getWriterInputs(t, fs)
defer cleanup()
@@ -289,6 +297,7 @@ metadata:
}
func testWriterOnDiskAndOnMem(t *testing.T, f func(t *testing.T, fs filesys.FileSystem)) {
t.Helper()
t.Run("on_disk", func(t *testing.T) { f(t, filesys.MakeFsOnDisk()) })
// TODO: Once fsnode supports Windows, these tests should also be run.
if runtime.GOOS != "windows" {
@@ -297,6 +306,7 @@ func testWriterOnDiskAndOnMem(t *testing.T, f func(t *testing.T, fs filesys.File
}
func getWriterInputs(t *testing.T, mockFS filesys.FileSystem) (string, *yaml.RNode, *yaml.RNode, *yaml.RNode, func()) {
t.Helper()
node1, err := yaml.Parse(`a: b #first
metadata:
annotations:

View File

@@ -20,6 +20,7 @@ type Setup struct {
// setupDirectories creates directories for reading test configuration from
func SetupDirectories(t *testing.T, dirs ...string) Setup {
t.Helper()
d, err := ioutil.TempDir("", "kyaml-test")
require.NoError(t, err)
err = os.Chdir(d)
@@ -33,6 +34,7 @@ func SetupDirectories(t *testing.T, dirs ...string) Setup {
// writeFile writes a file under the test directory
func (s Setup) WriteFile(t *testing.T, path string, value []byte) {
t.Helper()
err := os.MkdirAll(filepath.Dir(filepath.Join(s.Root, path)), 0700)
require.NoError(t, err)
err = ioutil.WriteFile(filepath.Join(s.Root, path), value, 0600)

View File

@@ -316,9 +316,8 @@ func toTypeMeta(ext interface{}) (yaml.TypeMeta, bool) {
return yaml.TypeMeta{}, false
}
g := m[groupKey].(string)
apiVersion := m[versionKey].(string)
if g != "" {
if g := m[groupKey].(string); g != "" {
apiVersion = g + "/" + apiVersion
}
return yaml.TypeMeta{Kind: m[kindKey].(string), APIVersion: apiVersion}, true

View File

@@ -1170,6 +1170,7 @@ func TestCmd_Execute_enableLogSteps(t *testing.T) {
}
func getGeneratorFilterProvider(t *testing.T) func(runtimeutil.FunctionSpec, *yaml.RNode, currentUserFunc) (kio.Filter, error) {
t.Helper()
return func(f runtimeutil.FunctionSpec, node *yaml.RNode, currentUser currentUserFunc) (kio.Filter, error) {
return kio.FilterFunc(func(items []*yaml.RNode) ([]*yaml.RNode, error) {
if f.Container.Image == "generate" {
@@ -1238,6 +1239,7 @@ metadata:
// setupTest initializes a temp test directory containing test data
func setupTest(t *testing.T) string {
t.Helper()
dir, err := ioutil.TempDir("", "kustomize-kyaml-test")
if !assert.NoError(t, err) {
t.FailNow()
@@ -1264,6 +1266,7 @@ func setupTest(t *testing.T) string {
// a filter to s/kind: Deployment/kind: StatefulSet/g.
// this can be used to simulate running a filter.
func getFilterProvider(t *testing.T) func(runtimeutil.FunctionSpec, *yaml.RNode, currentUserFunc) (kio.Filter, error) {
t.Helper()
return func(f runtimeutil.FunctionSpec, node *yaml.RNode, currentUser currentUserFunc) (kio.Filter, error) {
// parse the filter from the input
filter := yaml.YFilter{}

View File

@@ -1002,6 +1002,7 @@ spec:
// initSchema initializes the openAPI with the definitions from s
func SettersSchema(t *testing.T, s string) *spec.Schema {
t.Helper()
dir, err := ioutil.TempDir("", "")
assert.NoError(t, err)
defer os.RemoveAll(dir)

View File

@@ -6,12 +6,11 @@ package testutil
import (
"bytes"
"runtime"
"testing"
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/yaml"
"testing"
goerrors "github.com/go-errors/errors"
"github.com/stretchr/testify/assert"
@@ -43,6 +42,7 @@ func UpdateYamlBytes(b []byte, function ...yaml.Filter) ([]byte, error) {
}
func AssertErrorContains(t *testing.T, err error, value string, msg ...string) {
t.Helper()
if !assert.Error(t, err, msg) {
t.FailNow()
}
@@ -52,6 +52,7 @@ func AssertErrorContains(t *testing.T, err error, value string, msg ...string) {
}
func AssertNoError(t *testing.T, err error, msg ...string) {
t.Helper()
if !assert.NoError(t, err, msg) {
gerr, ok := err.(*goerrors.Error)
if ok {
@@ -62,6 +63,7 @@ func AssertNoError(t *testing.T, err error, msg ...string) {
}
func SkipWindows(t *testing.T) {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip()
}

View File

@@ -281,7 +281,7 @@ func ExampleElementMatcher_Filter_objectNotFound() {
if err != nil {
log.Fatal(err)
}
append, err := Parse(`
toAppend, err := Parse(`
name: baz
image: nginx
`)
@@ -289,7 +289,7 @@ image: nginx
log.Fatal(err)
}
elem, err := obj.Pipe(ElementMatcher{
Keys: []string{"name"}, Values: []string{"baz"}, Create: append})
Keys: []string{"name"}, Values: []string{"baz"}, Create: toAppend})
if err != nil {
log.Fatal(err)
}
@@ -315,7 +315,7 @@ func ExampleElementMatcher_Filter_objectFound() {
if err != nil {
log.Fatal(err)
}
append, err := Parse(`
toAppend, err := Parse(`
name: baz
image: nginx
`)
@@ -323,7 +323,7 @@ image: nginx
log.Fatal(err)
}
elem, err := obj.Pipe(ElementMatcher{
Keys: []string{"name"}, Values: []string{"baz"}, Create: append})
Keys: []string{"name"}, Values: []string{"baz"}, Create: toAppend})
if err != nil {
log.Fatal(err)
}

View File

@@ -552,7 +552,6 @@ func (l PathGetter) getFilter(part, nextPart string, fieldPath *[]string) (Filte
}
func (l PathGetter) elemFilter(part string) (Filter, error) {
var match *RNode
name, value, err := SplitIndexNameValue(part)
if err != nil {
return nil, errors.Wrap(err)
@@ -567,10 +566,9 @@ func (l PathGetter) elemFilter(part string) (Filter, error) {
// append a ScalarNode
elem = NewScalarRNode(value)
elem.YNode().Style = l.Style
match = elem
} else {
// append a MappingNode
match = NewRNode(&yaml.Node{Kind: yaml.ScalarNode, Value: value, Style: l.Style})
match := NewRNode(&yaml.Node{Kind: yaml.ScalarNode, Value: value, Style: l.Style})
elem = NewRNode(&yaml.Node{
Kind: yaml.MappingNode,
Content: []*yaml.Node{{Kind: yaml.ScalarNode, Value: name}, match.YNode()},

View File

@@ -23,19 +23,19 @@ c: d
func TestResourceNode_SetValue(t *testing.T) {
instance := *NewScalarRNode("foo")
copy := instance
instanceCopy := instance
instance.SetYNode(&yaml.Node{Kind: yaml.ScalarNode, Value: "bar"})
assert.Equal(t, `bar
`, assertNoErrorString(t)(copy.String()))
`, assertNoErrorString(t)(instanceCopy.String()))
assert.Equal(t, `bar
`, assertNoErrorString(t)(instance.String()))
instance = *NewScalarRNode("foo")
copy = instance
instanceCopy = instance
instance.SetYNode(nil)
instance.SetYNode(&yaml.Node{Kind: yaml.ScalarNode, Value: "bar"})
assert.Equal(t, `foo
`, assertNoErrorString(t)(copy.String()))
`, assertNoErrorString(t)(instanceCopy.String()))
assert.Equal(t, `bar
`, assertNoErrorString(t)(instance.String()))
}
@@ -1279,6 +1279,7 @@ metadata:
}
func assertNoError(t *testing.T) func(o *RNode, err error) *RNode {
t.Helper()
return func(o *RNode, err error) *RNode {
assert.NoError(t, err)
return o
@@ -1286,6 +1287,7 @@ func assertNoError(t *testing.T) func(o *RNode, err error) *RNode {
}
func assertNoErrorString(t *testing.T) func(string, error) string {
t.Helper()
return func(s string, err error) string {
assert.NoError(t, err)
return s

View File

@@ -74,8 +74,6 @@ data:
if err != nil {
t.Fatalf("unexpected error %v", err)
}
output := rn.MustString()
expected := `apiVersion: v1
kind: ConfigMap
data:
@@ -84,7 +82,7 @@ metadata:
labels:
foo: 'bar'
`
if output != expected {
if output := rn.MustString(); output != expected {
t.Fatalf("expected \n%s\nbut got \n%s\n", expected, output)
}
}
@@ -102,7 +100,6 @@ data:
if err != nil {
t.Fatalf("unexpected error %v", err)
}
output := rn.MustString()
expected := `apiVersion: v1
kind: ConfigMap
@@ -114,7 +111,7 @@ data:
altGreeting: "Good Morning!"
enableRisky: "false"
`
if output != expected {
if output := rn.MustString(); output != expected {
t.Fatalf("expected \n%s\nbut got \n%s\n", expected, output)
}
}

View File

@@ -2180,8 +2180,7 @@ func TestRoundTripJSON(t *testing.T) {
if err != nil {
t.Fatalf("unexpected MarshalJSON err: %v", err)
}
actual := string(data)
if actual != deploymentLittleJson {
if actual := string(data); actual != deploymentLittleJson {
t.Fatalf("expected %s, got %s", deploymentLittleJson, actual)
}
}

View File

@@ -32,8 +32,7 @@ func TestCopyYNode(t *testing.T) {
Line: 7000,
Column: 8000,
}
ynAddr := &yn
if !reflect.DeepEqual(&yn, ynAddr) {
if ynAddr := &yn; !reflect.DeepEqual(&yn, ynAddr) {
t.Fatalf("truly %v should equal %v", &yn, ynAddr)
}
ynC := CopyYNode(&yn)