Skip to content

Commit

Permalink
Adding test Lint Presets (#3340)
Browse files Browse the repository at this point in the history
* chore: Hiding mocks tests

* fix: Removing terratest log parser

* fix: Moving mocks generation

* fix: Fixing mock tests again

* fix: Still need mockery for unit tests, it seems

* fix: Resolving weird conflict from merge

* chore: Adding `unused` and `test` presets to lints

* chore: Addressing `test` lint errors

* fix: Fixing style on contstants
  • Loading branch information
yhakbar authored Aug 14, 2024
1 parent 761223a commit 446f6df
Show file tree
Hide file tree
Showing 134 changed files with 2,944 additions and 2,541 deletions.
4 changes: 4 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,16 @@ linters:
- depguard
- gosec
- gocyclo
- exhaustruct
fast: false
mnd:
ignored-functions: strconv.Format*,os.*,strconv.Parse*,strings.SplitN,bytes.SplitN
presets:
- bugs
- performance
- unused
- test

issues:
exclude-dirs:
- docs
Expand Down
7 changes: 4 additions & 3 deletions aws_helper/config_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package aws_helper
package aws_helper_test

import (
"testing"

"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/gruntwork-io/terragrunt/aws_helper"
"github.com/gruntwork-io/terragrunt/options"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -13,7 +14,7 @@ import (
func TestTerragruntIsAddedInUserAgent(t *testing.T) {
t.Parallel()

sess, err := CreateAwsSession(nil, options.NewTerragruntOptions())
sess, err := aws_helper.CreateAwsSession(nil, options.NewTerragruntOptions())
require.NoError(t, err)

op := &request.Operation{
Expand All @@ -33,7 +34,7 @@ func TestTerragruntIsAddedInUserAgent(t *testing.T) {
func TestAwsSessionValidationFail(t *testing.T) {
t.Parallel()

err := ValidateAwsSession(&AwsSessionConfig{
err := aws_helper.ValidateAwsSession(&aws_helper.AwsSessionConfig{
Region: "not-existing-region",
CredsFilename: "/tmp/not-existing-file",
}, options.NewTerragruntOptions())
Expand Down
11 changes: 6 additions & 5 deletions aws_helper/policy_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package aws_helper
package aws_helper_test

import (
"testing"

"github.com/gruntwork-io/terragrunt/aws_helper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -53,7 +54,7 @@ const arraysPolicy = `
func TestUnmarshalStringActionResource(t *testing.T) {
t.Parallel()

bucketPolicy, err := UnmarshalPolicy(simplePolicy)
bucketPolicy, err := aws_helper.UnmarshalPolicy(simplePolicy)
require.NoError(t, err)
assert.NotNil(t, bucketPolicy)
assert.Len(t, bucketPolicy.Statement, 1)
Expand All @@ -74,14 +75,14 @@ func TestUnmarshalStringActionResource(t *testing.T) {
assert.Fail(t, "Expected string type for Resource")
}

out, err := MarshalPolicy(bucketPolicy)
out, err := aws_helper.MarshalPolicy(bucketPolicy)
require.NoError(t, err)
assert.NotContains(t, string(out), "null")
}

func TestUnmarshalActionResourceList(t *testing.T) {
t.Parallel()
bucketPolicy, err := UnmarshalPolicy(arraysPolicy)
bucketPolicy, err := aws_helper.UnmarshalPolicy(arraysPolicy)
require.NoError(t, err)
assert.NotNil(t, bucketPolicy)
assert.Len(t, bucketPolicy.Statement, 1)
Expand All @@ -104,7 +105,7 @@ func TestUnmarshalActionResourceList(t *testing.T) {
assert.Fail(t, "Expected []string type for Resource")
}

out, err := MarshalPolicy(bucketPolicy)
out, err := aws_helper.MarshalPolicy(bucketPolicy)
require.NoError(t, err)
assert.NotContains(t, string(out), "null")
}
14 changes: 7 additions & 7 deletions cli/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,11 @@ func NewApp(writer io.Writer, errWriter io.Writer) *App {
commands.NewGlobalFlags(opts),
commands.NewHelpVersionFlags(opts)...)
app.Commands = append(
deprecatedCommands(opts),
terragruntCommands(opts)...).WrapAction(wrapWithTelemetry(opts))
DeprecatedCommands(opts),
TerragruntCommands(opts)...).WrapAction(WrapWithTelemetry(opts))
app.Before = beforeAction(opts)
app.DefaultCommand = terraformCmd.NewCommand(opts).WrapAction(wrapWithTelemetry(opts)) // by default, if no terragrunt command is specified, run the Terraform command
app.OsExiter = osExiter
app.DefaultCommand = terraformCmd.NewCommand(opts).WrapAction(WrapWithTelemetry(opts)) // by default, if no terragrunt command is specified, run the Terraform command
app.OsExiter = OSExiter

return &App{app}
}
Expand Down Expand Up @@ -146,7 +146,7 @@ func (app *App) RunContext(ctx context.Context, args []string) error {
}

// This set of commands is also used in unit tests
func terragruntCommands(opts *options.TerragruntOptions) cli.Commands {
func TerragruntCommands(opts *options.TerragruntOptions) cli.Commands {
cmds := cli.Commands{
runall.NewCommand(opts), // runAction-all
terragruntinfo.NewCommand(opts), // terragrunt-info
Expand All @@ -171,7 +171,7 @@ func terragruntCommands(opts *options.TerragruntOptions) cli.Commands {
}

// Wrap CLI command execution with setting of telemetry context and labels, if telemetry is disabled, just runAction the command.
func wrapWithTelemetry(opts *options.TerragruntOptions) func(ctx *cli.Context, action cli.ActionFunc) error {
func WrapWithTelemetry(opts *options.TerragruntOptions) func(ctx *cli.Context, action cli.ActionFunc) error {
return func(ctx *cli.Context, action cli.ActionFunc) error {
return telemetry.Telemetry(ctx.Context, opts, fmt.Sprintf("%s %s", ctx.Command.Name, opts.TerraformCommand), map[string]interface{}{
"terraformCommand": opts.TerraformCommand,
Expand Down Expand Up @@ -391,7 +391,7 @@ func initialSetup(cliCtx *cli.Context, opts *options.TerragruntOptions) error {
return nil
}

func osExiter(exitCode int) {
func OSExiter(exitCode int) {
// Do nothing. We just need to override this function, as the default value calls os.Exit, which
// kills the app (or any automated test) dead in its tracks.
}
49 changes: 26 additions & 23 deletions cli/app_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cli
package cli_test

import (
"bytes"
Expand All @@ -9,6 +9,7 @@ import (
"testing"

"github.com/gruntwork-io/go-commons/errors"
"github.com/gruntwork-io/terragrunt/cli"
"github.com/gruntwork-io/terragrunt/cli/commands"
awsproviderpatch "github.com/gruntwork-io/terragrunt/cli/commands/aws-provider-patch"
"github.com/gruntwork-io/terragrunt/cli/commands/hclfmt"
Expand All @@ -17,7 +18,7 @@ import (
terraformcmd "github.com/gruntwork-io/terragrunt/cli/commands/terraform"
"github.com/gruntwork-io/terragrunt/config"
"github.com/gruntwork-io/terragrunt/options"
"github.com/gruntwork-io/terragrunt/pkg/cli"
cliPkg "github.com/gruntwork-io/terragrunt/pkg/cli"
"github.com/gruntwork-io/terragrunt/terraform"
"github.com/gruntwork-io/terragrunt/util"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -285,8 +286,8 @@ func TestFilterTerragruntArgs(t *testing.T) {
{[]string{"foo", doubleDashed(commands.TerragruntNonInteractiveFlagName)}, []string{"foo"}},
{[]string{"foo", doubleDashed(commands.TerragruntDebugFlagName)}, []string{"foo"}},
{[]string{"foo", doubleDashed(commands.TerragruntNonInteractiveFlagName), "-bar", doubleDashed(commands.TerragruntWorkingDirFlagName), "/some/path", "--baz", doubleDashed(commands.TerragruntConfigFlagName), "/some/path/" + config.DefaultTerragruntConfigPath}, []string{"foo", "-bar", "-baz"}},
{[]string{CommandNameApplyAll, "foo", "bar"}, []string{terraform.CommandNameApply, "foo", "bar"}},
{[]string{CommandNameDestroyAll, "foo", "-foo", "--bar"}, []string{terraform.CommandNameDestroy, "foo", "-foo", "-bar"}},
{[]string{cli.CommandNameApplyAll, "foo", "bar"}, []string{terraform.CommandNameApply, "foo", "bar"}},
{[]string{cli.CommandNameDestroyAll, "foo", "-foo", "--bar"}, []string{terraform.CommandNameDestroy, "foo", "-foo", "-bar"}},
}

for _, testCase := range testCases {
Expand All @@ -307,10 +308,10 @@ func TestParseMultiStringArg(t *testing.T) {
expectedVals []string
expectedErr error
}{
{[]string{CommandNameApplyAll, flagName, "bar"}, []string{"default_bar"}, []string{"bar"}, nil},
{[]string{CommandNameApplyAll, "--test", "bar"}, []string{"default_bar"}, []string{"default_bar"}, nil},
{[]string{CommandNamePlanAll, "--test", flagName, "bar1", flagName, "bar2"}, []string{"default_bar"}, []string{"bar1", "bar2"}, nil},
{[]string{CommandNamePlanAll, "--test", "value", flagName, "bar1", flagName}, []string{"default_bar"}, nil, argMissingValueError(commands.TerragruntModulesThatIncludeFlagName)},
{[]string{cli.CommandNameApplyAll, flagName, "bar"}, []string{"default_bar"}, []string{"bar"}, nil},
{[]string{cli.CommandNameApplyAll, "--test", "bar"}, []string{"default_bar"}, []string{"default_bar"}, nil},
{[]string{cli.CommandNamePlanAll, "--test", flagName, "bar1", flagName, "bar2"}, []string{"default_bar"}, []string{"bar1", "bar2"}, nil},
{[]string{cli.CommandNamePlanAll, "--test", "value", flagName, "bar1", flagName}, []string{"default_bar"}, nil, argMissingValueError(commands.TerragruntModulesThatIncludeFlagName)},
}

for _, testCase := range testCases {
Expand Down Expand Up @@ -343,7 +344,7 @@ func TestParseMutliStringKeyValueArg(t *testing.T) {
{[]string{awsproviderpatch.CommandName, "--other", "arg"}, map[string]string{"default": "value"}, map[string]string{"default": "value"}, nil},
{[]string{awsproviderpatch.CommandName, flagName, "key=value"}, map[string]string{"default": "value"}, map[string]string{"key": "value"}, nil},
{[]string{awsproviderpatch.CommandName, flagName, "key1=value1", flagName, "key2=value2", flagName, "key3=value3"}, map[string]string{"default": "value"}, map[string]string{"key1": "value1", "key2": "value2", "key3": "value3"}, nil},
{[]string{awsproviderpatch.CommandName, flagName, "invalidvalue"}, map[string]string{"default": "value"}, nil, cli.NewInvalidKeyValueError(cli.MapFlagKeyValSep, "invalidvalue")},
{[]string{awsproviderpatch.CommandName, flagName, "invalidvalue"}, map[string]string{"default": "value"}, nil, cliPkg.NewInvalidKeyValueError(cliPkg.MapFlagKeyValSep, "invalidvalue")},
}

for _, testCase := range testCases {
Expand Down Expand Up @@ -375,7 +376,7 @@ func TestTerragruntVersion(t *testing.T) {

for _, testCase := range testCases {
output := &bytes.Buffer{}
app := NewApp(output, os.Stderr)
app := cli.NewApp(output, os.Stderr)
app.Version = version

err := app.Run(testCase.args)
Expand All @@ -388,7 +389,7 @@ func TestTerragruntVersion(t *testing.T) {
func TestTerragruntHelp(t *testing.T) {
t.Parallel()

app := NewApp(os.Stdout, os.Stderr)
app := cli.NewApp(os.Stdout, os.Stderr)

testCases := []struct {
args []string
Expand All @@ -399,12 +400,12 @@ func TestTerragruntHelp(t *testing.T) {
{[]string{"terragrunt", "-help"}, app.UsageText, awsproviderpatch.FlagNameTerragruntOverrideAttr},
{[]string{"terragrunt", "-h"}, app.UsageText, awsproviderpatch.FlagNameTerragruntOverrideAttr},
{[]string{"terragrunt", awsproviderpatch.CommandName, "-h"}, commands.TerragruntConfigFlagName, hclfmt.CommandName},
{[]string{"terragrunt", CommandNamePlanAll, "--help"}, runall.CommandName, ""},
{[]string{"terragrunt", cli.CommandNamePlanAll, "--help"}, runall.CommandName, ""},
}

for _, testCase := range testCases {
output := &bytes.Buffer{}
app := NewApp(output, os.Stderr)
app := cli.NewApp(output, os.Stderr)
err := app.Run(testCase.args)
require.NoError(t, err, testCase)

Expand All @@ -431,7 +432,7 @@ func TestTerraformHelp(t *testing.T) {

for _, testCase := range testCases {
output := &bytes.Buffer{}
app := NewApp(output, os.Stderr)
app := cli.NewApp(output, os.Stderr)
err := app.Run(testCase.args)
require.NoError(t, err)

Expand All @@ -445,7 +446,7 @@ func TestTerraformHelp(t *testing.T) {
func TestTerraformHelp_wrongHelpFlag(t *testing.T) {
t.Parallel()

app := NewApp(os.Stdout, os.Stderr)
app := cli.NewApp(os.Stdout, os.Stderr)

output := &bytes.Buffer{}
app.Writer = output
Expand All @@ -455,9 +456,9 @@ func TestTerraformHelp_wrongHelpFlag(t *testing.T) {
}

func runAppTest(args []string, opts *options.TerragruntOptions) (*options.TerragruntOptions, error) {
emptyAction := func(ctx *cli.Context) error { return nil }
emptyAction := func(ctx *cliPkg.Context) error { return nil }

terragruntCommands := terragruntCommands(opts)
terragruntCommands := cli.TerragruntCommands(opts)
for _, command := range terragruntCommands {
command.Action = emptyAction
for _, cmd := range command.Subcommands {
Expand All @@ -468,17 +469,17 @@ func runAppTest(args []string, opts *options.TerragruntOptions) (*options.Terrag
defaultCommand := terraformcmd.NewCommand(opts)
defaultCommand.Action = emptyAction

app := cli.NewApp()
app := cliPkg.NewApp()
app.Writer = &bytes.Buffer{}
app.ErrWriter = &bytes.Buffer{}
app.Flags = append(
commands.NewGlobalFlags(opts),
commands.NewHelpVersionFlags(opts)...)
app.Commands = append(
deprecatedCommands(opts),
terragruntCommands...).WrapAction(wrapWithTelemetry(opts))
app.DefaultCommand = defaultCommand.WrapAction(wrapWithTelemetry(opts))
app.OsExiter = osExiter
cli.DeprecatedCommands(opts),
terragruntCommands...).WrapAction(cli.WrapWithTelemetry(opts))
app.DefaultCommand = defaultCommand.WrapAction(cli.WrapWithTelemetry(opts))
app.OsExiter = cli.OSExiter

err := app.Run(append([]string{"--"}, args...))
return opts, err
Expand All @@ -495,6 +496,8 @@ func (err argMissingValueError) Error() string {
}

func TestAutocomplete(t *testing.T) {
t.Parallel()

defer os.Unsetenv("COMP_LINE")

testCases := []struct {
Expand Down Expand Up @@ -523,7 +526,7 @@ func TestAutocomplete(t *testing.T) {
os.Setenv("COMP_LINE", "terragrunt "+testCase.compLine)

output := &bytes.Buffer{}
app := NewApp(output, os.Stderr)
app := cli.NewApp(output, os.Stderr)
app.Commands = app.Commands.Filter([]string{"aws-provider-patch", "graph-dependencies", "hclfmt", "output-module-groups", "render-json", "run-all", "terragrunt-info", "validate-inputs"})

err := app.Run([]string{"terragrunt"})
Expand Down
6 changes: 3 additions & 3 deletions cli/commands/aws-provider-patch/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func runAwsProviderPatch(ctx context.Context, opts *options.TerragruntOptions, c
return err
}

updatedTerraformFileContents, codeWasUpdated, err := patchAwsProviderInTerraformCode(originalTerraformFileContents, terraformFile, opts.AwsProviderPatchOverrides)
updatedTerraformFileContents, codeWasUpdated, err := PatchAwsProviderInTerraformCode(originalTerraformFileContents, terraformFile, opts.AwsProviderPatchOverrides)
if err != nil {
return err
}
Expand Down Expand Up @@ -153,7 +153,7 @@ func findAllTerraformFilesInModules(opts *options.TerragruntOptions) ([]string,
return terraformFiles, nil
}

// patchAwsProviderInTerraformCode looks for provider "aws" { ... } blocks in the given Terraform code and overwrites
// PatchAwsProviderInTerraformCode looks for provider "aws" { ... } blocks in the given Terraform code and overwrites
// the attributes in those provider blocks with the given attributes. It returns the new Terraform code and a boolean
// true if that code was updated.
//
Expand All @@ -172,7 +172,7 @@ func findAllTerraformFilesInModules(opts *options.TerragruntOptions) ([]string,
// This is a temporary workaround for a Terraform bug (https://github.com/hashicorp/terraform/issues/13018) where
// any dynamic values in nested provider blocks are not handled correctly when you call 'terraform import', so by
// temporarily hard-coding them, we can allow 'import' to work.
func patchAwsProviderInTerraformCode(terraformCode string, terraformFilePath string, attributesToOverride map[string]string) (string, bool, error) {
func PatchAwsProviderInTerraformCode(terraformCode string, terraformFilePath string, attributesToOverride map[string]string) (string, bool, error) {
if len(attributesToOverride) == 0 {
return terraformCode, false, nil
}
Expand Down
5 changes: 3 additions & 2 deletions cli/commands/aws-provider-patch/action_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package awsproviderpatch
package awsproviderpatch_test

import (
"testing"

awsproviderpatch "github.com/gruntwork-io/terragrunt/cli/commands/aws-provider-patch"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -318,7 +319,7 @@ func TestPatchAwsProviderInTerraformCodeHappyPath(t *testing.T) {
testCase := testCase
t.Run(testCase.testName, func(t *testing.T) {
t.Parallel()
actualTerraformCode, actualCodeWasUpdated, err := patchAwsProviderInTerraformCode(testCase.originalTerraformCode, "test.tf", testCase.attributesToOverride)
actualTerraformCode, actualCodeWasUpdated, err := awsproviderpatch.PatchAwsProviderInTerraformCode(testCase.originalTerraformCode, "test.tf", testCase.attributesToOverride)
require.NoError(t, err)
assert.Equal(t, testCase.expectedCodeWasUpdated, actualCodeWasUpdated)

Expand Down
4 changes: 2 additions & 2 deletions cli/commands/catalog/module/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ type Doc struct {
frontmatterReg *regexp.Regexp
}

func newDoc(rawContent, fileExt string) *Doc {
func NewDoc(rawContent, fileExt string) *Doc {
doc := &Doc{
rawContent: rawContent,
fileExt: fileExt,
Expand Down Expand Up @@ -169,7 +169,7 @@ func FindDoc(dir string) (*Doc, error) {
}
rawContent := string(contentByte)

return newDoc(rawContent, fileExt), nil
return NewDoc(rawContent, fileExt), nil
}

func (doc *Doc) Title() string {
Expand Down
7 changes: 4 additions & 3 deletions cli/commands/catalog/module/doc_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package module
package module_test

import (
"fmt"
"testing"

"github.com/gruntwork-io/terragrunt/cli/commands/catalog/module"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -68,7 +69,7 @@ func TestFrontmatter(t *testing.T) {
t.Run(fmt.Sprintf("testCase-%d", i), func(t *testing.T) {
t.Parallel()

doc := newDoc(testCase.content, "")
doc := module.NewDoc(testCase.content, "")

assert.Equal(t, testCase.expectedName, doc.Title(), "Frontmatter Name")
assert.Equal(t, testCase.expectedDesc, doc.Description(0), "Frontmatter Description")
Expand Down Expand Up @@ -223,7 +224,7 @@ func TestElement(t *testing.T) {
t.Run(fmt.Sprintf("testCase-%d", i), func(t *testing.T) {
t.Parallel()

doc := newDoc(testCase.content, testCase.fileExt)
doc := module.NewDoc(testCase.content, testCase.fileExt)

assert.Equal(t, testCase.expectedTitle, doc.Title(), "Title")
assert.Equal(t, testCase.expectedDescription, doc.Description(testCase.maxDescriptionLength), "Description")
Expand Down
Loading

0 comments on commit 446f6df

Please sign in to comment.