From cb786034244979f9ad07a3b8f06179e1995d6dc6 Mon Sep 17 00:00:00 2001 From: Yousif Akbar <11247449+yhakbar@users.noreply.github.com> Date: Mon, 12 Aug 2024 13:52:46 -0400 Subject: [PATCH] chore: Adding `bugs` Lint Preset (#3334) * 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 * chore: Bumping `golangci-lint` to `v1.59.1` * chore: Addressing lint errors * fix: Fixing lint configs * fix: Fixing magic numbers for file permissions * fix: Resolving remaining lints * chore: Adding `bugs` preset to lints * feat: Addressing `bugs` preset lint findings --- .golangci.yml | 3 +- aws_helper/config.go | 3 +- aws_helper/config_test.go | 3 +- aws_helper/policy_test.go | 17 +- cli/app.go | 5 +- cli/app_test.go | 6 +- cli/commands/aws-provider-patch/action.go | 8 +- .../aws-provider-patch/action_test.go | 3 +- cli/commands/catalog/module/repo_test.go | 3 +- cli/commands/catalog/tui/tui.go | 3 +- cli/commands/flags.go | 5 +- cli/commands/run-all/action_test.go | 3 +- cli/commands/scaffold/action_test.go | 2 +- .../terraform/download_source_test.go | 47 +- cli/commands/terraform/hook.go | 7 +- cli/commands/terraform/version_check.go | 3 +- cli/commands/terraform/version_check_test.go | 7 +- cli/commands/terragrunt-info/action.go | 12 +- cli/registry_urls.go | 3 +- codegen/generate.go | 6 +- codegen/generate_test.go | 6 +- config/cache_test.go | 18 +- config/catalog.go | 8 +- config/config.go | 21 +- config/config_helpers_test.go | 191 ++- config/config_partial.go | 4 +- config/config_partial_test.go | 145 +- config/config_test.go | 184 +-- config/cty_helpers.go | 4 +- config/dependency.go | 4 +- config/dependency_test.go | 29 +- config/hclparse/attributes.go | 3 +- config/include.go | 6 +- config/include_test.go | 72 +- config/locals_test.go | 23 +- config/variable.go | 4 +- config/variable_test.go | 74 +- configstack/module.go | 3 +- configstack/module_test.go | 253 ++-- configstack/running_module.go | 4 +- configstack/running_module_test.go | 2 +- configstack/stack.go | 4 +- configstack/stack_test.go | 64 +- configstack/test_helpers.go | 17 +- dynamodb/dynamo_lock_table.go | 9 +- dynamodb/dynamo_lock_table_test.go | 7 +- dynamodb/dynamo_lock_test_utils.go | 10 +- engine/engine.go | 23 +- engine/engine_test.go | 7 +- internal/cache/cache_test.go | 40 +- internal/view/diagnostic/servity.go | 3 +- internal/view/human_render.go | 3 +- main.go | 7 +- pkg/cli/errors.go | 4 +- remote/remote_state.go | 10 +- remote/remote_state_gcs.go | 21 +- remote/remote_state_gcs_test.go | 7 +- remote/remote_state_s3.go | 35 +- remote/remote_state_s3_test.go | 32 +- remote/remote_state_test.go | 12 +- remote/terraform_state_file.go | 18 +- remote/terraform_state_file_test.go | 39 +- shell/error_explainer.go | 10 +- shell/run_shell_cmd_output_test.go | 9 +- shell/run_shell_cmd_test.go | 33 +- shell/run_shell_cmd_unix_test.go | 40 +- telemetry/metrics.go | 4 +- telemetry/metrics_test.go | 12 +- telemetry/traces.go | 13 +- telemetry/traces_test.go | 14 +- terraform/cliconfig/config_test.go | 12 +- terraform/cliconfig/provider_installation.go | 31 +- .../getproviders/package_authentication.go | 5 +- terraform/getter.go | 9 +- terraform/getter_test.go | 23 +- test/integration_catalog_test.go | 45 +- test/integration_debug_test.go | 34 +- test/integration_download_test.go | 34 +- test/integration_include_test.go | 49 +- test/integration_local_dev_test.go | 5 +- test/integration_s3_encryption_test.go | 8 +- test/integration_scaffold_test.go | 6 +- test/integration_serial_test.go | 125 +- test/integration_test.go | 1282 +++++++++-------- tflint/tflint_test.go | 6 +- util/collections_test.go | 20 +- util/datetime.go | 3 +- util/datetime_test.go | 8 +- util/file.go | 5 +- util/file_test.go | 18 +- util/jsons_test.go | 6 +- util/prefix-writer_test.go | 12 +- util/reflect.go | 2 +- util/retry.go | 4 +- util/shell.go | 12 +- 95 files changed, 1789 insertions(+), 1689 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 72ba71e37..cafce95f9 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -73,7 +73,8 @@ linters: fast: false mnd: ignored-functions: strconv.Format*,os.*,strconv.Parse*,strings.SplitN,bytes.SplitN - + presets: + - bugs issues: exclude-dirs: - docs diff --git a/aws_helper/config.go b/aws_helper/config.go index ae4f4d298..1cfeb85a5 100644 --- a/aws_helper/config.go +++ b/aws_helper/config.go @@ -123,7 +123,8 @@ type tokenFetcher string func (f tokenFetcher) FetchToken(ctx credentials.Context) ([]byte, error) { // Check if token is a raw value if _, err := os.Stat(string(f)); err != nil { - return []byte(f), nil + // TODO: See if this lint error should be ignored + return []byte(f), nil //nolint: nilerr } token, err := os.ReadFile(string(f)) if err != nil { diff --git a/aws_helper/config_test.go b/aws_helper/config_test.go index 80a44dd67..86d4a4025 100644 --- a/aws_helper/config_test.go +++ b/aws_helper/config_test.go @@ -7,13 +7,14 @@ import ( "github.com/aws/aws-sdk-go/service/sts" "github.com/gruntwork-io/terragrunt/options" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTerragruntIsAddedInUserAgent(t *testing.T) { t.Parallel() sess, err := CreateAwsSession(nil, options.NewTerragruntOptions()) - assert.NoError(t, err) + require.NoError(t, err) op := &request.Operation{ Name: "", diff --git a/aws_helper/policy_test.go b/aws_helper/policy_test.go index 27b4fccca..7338a52f9 100644 --- a/aws_helper/policy_test.go +++ b/aws_helper/policy_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const simplePolicy = ` @@ -53,9 +54,9 @@ func TestUnmarshalStringActionResource(t *testing.T) { t.Parallel() bucketPolicy, err := UnmarshalPolicy(simplePolicy) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, bucketPolicy) - assert.Equal(t, 1, len(bucketPolicy.Statement)) + assert.Len(t, bucketPolicy.Statement, 1) assert.NotNil(t, bucketPolicy.Statement[0].Action) assert.NotNil(t, bucketPolicy.Statement[0].Resource) @@ -74,22 +75,22 @@ func TestUnmarshalStringActionResource(t *testing.T) { } out, err := MarshalPolicy(bucketPolicy) - assert.NoError(t, err) + require.NoError(t, err) assert.NotContains(t, string(out), "null") } func TestUnmarshalActionResourceList(t *testing.T) { t.Parallel() bucketPolicy, err := UnmarshalPolicy(arraysPolicy) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, bucketPolicy) - assert.Equal(t, 1, len(bucketPolicy.Statement)) + require.Len(t, bucketPolicy.Statement, 1) assert.NotNil(t, bucketPolicy.Statement[0].Action) assert.NotNil(t, bucketPolicy.Statement[0].Resource) switch actions := bucketPolicy.Statement[0].Action.(type) { case []interface{}: - assert.Equal(t, 11, len(actions)) + require.Len(t, actions, 11) assert.Contains(t, actions, "s3:ListJobs") default: assert.Fail(t, "Expected []string type for Action") @@ -97,13 +98,13 @@ func TestUnmarshalActionResourceList(t *testing.T) { switch resource := bucketPolicy.Statement[0].Resource.(type) { case []interface{}: - assert.Equal(t, 2, len(resource)) + require.Len(t, resource, 2) assert.Contains(t, resource, "arn:aws:s3:*:666:job/*") default: assert.Fail(t, "Expected []string type for Resource") } out, err := MarshalPolicy(bucketPolicy) - assert.NoError(t, err) + require.NoError(t, err) assert.NotContains(t, string(out), "null") } diff --git a/cli/app.go b/cli/app.go index 92dc2118a..f3b77ff75 100644 --- a/cli/app.go +++ b/cli/app.go @@ -183,12 +183,13 @@ func wrapWithTelemetry(opts *options.TerragruntOptions) func(ctx *cli.Context, a return err } - return runAction(ctx, opts, action) + // TODO: See if this lint should be ignored + return runAction(ctx, opts, action) //nolint:contextcheck }) } } -func beforeAction(opts *options.TerragruntOptions) cli.ActionFunc { +func beforeAction(_ *options.TerragruntOptions) cli.ActionFunc { return func(ctx *cli.Context) error { // setting current context to the options // show help if the args are not specified. diff --git a/cli/app_test.go b/cli/app_test.go index 2c814a3fb..1cfb494ee 100644 --- a/cli/app_test.go +++ b/cli/app_test.go @@ -193,7 +193,7 @@ func TestParseTerragruntOptionsFromArgs(t *testing.T) { if testCase.expectedErr != nil { assert.EqualError(t, actualErr, testCase.expectedErr.Error()) } else { - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr) assertOptionsEqual(t, *testCase.expectedOptions, *actualOptions, "For args %v", testCase.args) } } @@ -322,7 +322,7 @@ func TestParseMultiStringArg(t *testing.T) { if testCase.expectedErr != nil { assert.EqualError(t, actualErr, testCase.expectedErr.Error()) } else { - assert.Nil(t, actualErr, "Unexpected error: %q", actualErr) + require.NoError(t, actualErr) assert.Equal(t, testCase.expectedVals, actualOptions.ModulesThatInclude, "For args %q", testCase.args) } } @@ -355,7 +355,7 @@ func TestParseMutliStringKeyValueArg(t *testing.T) { if testCase.expectedErr != nil { assert.ErrorContains(t, actualErr, testCase.expectedErr.Error()) } else { - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr) assert.Equal(t, testCase.expectedVals, actualOptions.AwsProviderPatchOverrides, "For args %v", testCase.args) } } diff --git a/cli/commands/aws-provider-patch/action.go b/cli/commands/aws-provider-patch/action.go index 9a3040138..1318a9274 100644 --- a/cli/commands/aws-provider-patch/action.go +++ b/cli/commands/aws-provider-patch/action.go @@ -91,13 +91,13 @@ func runAwsProviderPatch(ctx context.Context, opts *options.TerragruntOptions, c // The format we expect in the .terraform/modules/modules.json file type TerraformModulesJson struct { - Modules []TerraformModule + Modules []TerraformModule `json:"Modules"` } type TerraformModule struct { - Key string - Source string - Dir string + Key string `json:"Key"` + Source string `json:"Source"` + Dir string `json:"Dir"` } // findAllTerraformFiles returns all Terraform source files within the modules being used by this Terragrunt diff --git a/cli/commands/aws-provider-patch/action_test.go b/cli/commands/aws-provider-patch/action_test.go index c8886f82c..ed5e7a643 100644 --- a/cli/commands/aws-provider-patch/action_test.go +++ b/cli/commands/aws-provider-patch/action_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const terraformCodeExampleOutputOnly = ` @@ -318,7 +319,7 @@ func TestPatchAwsProviderInTerraformCodeHappyPath(t *testing.T) { t.Run(testCase.testName, func(t *testing.T) { t.Parallel() actualTerraformCode, actualCodeWasUpdated, err := patchAwsProviderInTerraformCode(testCase.originalTerraformCode, "test.tf", testCase.attributesToOverride) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, testCase.expectedCodeWasUpdated, actualCodeWasUpdated) // We check an array of possible expected code here due to possible ordering differences. That is, the diff --git a/cli/commands/catalog/module/repo_test.go b/cli/commands/catalog/module/repo_test.go index e3b3e7ad2..1e9609e9a 100644 --- a/cli/commands/catalog/module/repo_test.go +++ b/cli/commands/catalog/module/repo_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFindModules(t *testing.T) { @@ -61,7 +62,7 @@ func TestFindModules(t *testing.T) { ctx := context.Background() repo, err := NewRepo(ctx, testCase.repoPath, "") - assert.NoError(t, err) + require.NoError(t, err) modules, err := repo.FindModules(ctx) assert.Equal(t, testCase.expectedErr, err) diff --git a/cli/commands/catalog/tui/tui.go b/cli/commands/catalog/tui/tui.go index 85c2e4a77..fb57b54e4 100644 --- a/cli/commands/catalog/tui/tui.go +++ b/cli/commands/catalog/tui/tui.go @@ -2,6 +2,7 @@ package tui import ( "context" + "errors" tea "github.com/charmbracelet/bubbletea" @@ -11,7 +12,7 @@ import ( func Run(ctx context.Context, modules module.Modules, opts *options.TerragruntOptions) error { if _, err := tea.NewProgram(newModel(modules, opts), tea.WithAltScreen(), tea.WithContext(ctx)).Run(); err != nil { - if err := context.Cause(ctx); err == context.Canceled { + if err := context.Cause(ctx); errors.Is(err, context.Canceled) { return nil } else if err != nil { return err diff --git a/cli/commands/flags.go b/cli/commands/flags.go index 11ec4fbb0..6d07055dc 100644 --- a/cli/commands/flags.go +++ b/cli/commands/flags.go @@ -1,6 +1,8 @@ package commands import ( + "errors" + "github.com/gruntwork-io/terragrunt/options" "github.com/gruntwork-io/terragrunt/pkg/cli" "github.com/gruntwork-io/terragrunt/shell" @@ -362,7 +364,8 @@ func NewHelpFlag(opts *options.TerragruntOptions) cli.Flag { err := cli.ShowCommandHelp(ctx, cmdName) // If the command name is not found, it is most likely a terraform command, show Terraform help. - if _, ok := err.(cli.InvalidCommandNameError); ok { + var invalidCommandNameError cli.InvalidCommandNameError + if ok := errors.As(err, &invalidCommandNameError); ok { terraformHelpCmd := append([]string{cmdName, "-help"}, ctx.Args().Tail()...) return shell.RunTerraformCommand(ctx, opts, terraformHelpCmd...) } diff --git a/cli/commands/run-all/action_test.go b/cli/commands/run-all/action_test.go index 5918c2227..d1819a177 100644 --- a/cli/commands/run-all/action_test.go +++ b/cli/commands/run-all/action_test.go @@ -22,7 +22,8 @@ func TestMissingRunAllArguments(t *testing.T) { err = Run(context.Background(), tgOptions) require.Error(t, err) - _, ok := errors.Unwrap(err).(MissingCommand) + var missingCommand MissingCommand + ok := errors.As(err, &missingCommand) fmt.Println(err, errors.Unwrap(err)) assert.True(t, ok) } diff --git a/cli/commands/scaffold/action_test.go b/cli/commands/scaffold/action_test.go index 8d7304cc3..2f930a168 100644 --- a/cli/commands/scaffold/action_test.go +++ b/cli/commands/scaffold/action_test.go @@ -85,7 +85,7 @@ func TestDefaultTemplateVariables(t *testing.T) { cfg, err := config.ReadTerragruntConfig(context.Background(), opts, config.DefaultParserOptions(opts)) require.NoError(t, err) require.NotEmpty(t, cfg.Inputs) - require.Equal(t, 1, len(cfg.Inputs)) + require.Len(t, cfg.Inputs, 1) _, found := cfg.Inputs["required_var_1"] require.True(t, found) require.Equal(t, "git::https://github.com/gruntwork-io/terragrunt.git//test/fixture-inputs?ref=v0.53.8", *cfg.Terraform.Source) diff --git a/cli/commands/terraform/download_source_test.go b/cli/commands/terraform/download_source_test.go index be5625363..bad98f3ad 100644 --- a/cli/commands/terraform/download_source_test.go +++ b/cli/commands/terraform/download_source_test.go @@ -2,6 +2,7 @@ package terraform import ( "context" + "errors" "fmt" "io" "net/url" @@ -12,7 +13,6 @@ import ( "testing" "github.com/gruntwork-io/go-commons/env" - "github.com/gruntwork-io/go-commons/errors" "github.com/gruntwork-io/terragrunt/terraform" "github.com/sirupsen/logrus" @@ -250,12 +250,13 @@ func TestDownloadTerraformSourceIfNecessaryInvalidTerraformSource(t *testing.T) terraformSource, terragruntOptions, terragruntConfig, err := createConfig(t, canonicalUrl, downloadDir, false) - assert.NoError(t, err) + require.NoError(t, err) err = downloadTerraformSourceIfNecessary(context.Background(), terraformSource, terragruntOptions, terragruntConfig) - assert.Error(t, err) - _, ok := errors.Unwrap(err).(DownloadingTerraformSourceErr) - assert.True(t, ok) + require.Error(t, err) + var downloadingTerraformSourceErr DownloadingTerraformSourceErr + ok := errors.As(err, &downloadingTerraformSourceErr) + require.True(t, ok) } func TestInvalidModulePath(t *testing.T) { @@ -268,13 +269,14 @@ func TestInvalidModulePath(t *testing.T) { copyFolder(t, "../../../test/fixture-download-source/hello-world-version-remote", downloadDir) terraformSource, _, _, err := createConfig(t, canonicalUrl, downloadDir, false) - assert.NoError(t, err) + require.NoError(t, err) terraformSource.WorkingDir += "/not-existing-path" err = validateWorkingDir(terraformSource) - assert.Error(t, err) - _, ok := errors.Unwrap(err).(WorkingDirNotFound) - assert.True(t, ok) + require.Error(t, err) + var workingDirNotFound WorkingDirNotFound + ok := errors.As(err, &workingDirNotFound) + require.True(t, ok) } func TestDownloadInvalidPathToFilePath(t *testing.T) { @@ -287,13 +289,14 @@ func TestDownloadInvalidPathToFilePath(t *testing.T) { copyFolder(t, "../../../test/fixture-download-source/hello-world-version-remote", downloadDir) terraformSource, _, _, err := createConfig(t, canonicalUrl, downloadDir, false) - assert.NoError(t, err) + require.NoError(t, err) terraformSource.WorkingDir += "/main.tf" err = validateWorkingDir(terraformSource) - assert.Error(t, err) - _, ok := errors.Unwrap(err).(WorkingDirNotDir) - assert.True(t, ok) + require.Error(t, err) + var workingDirNotDir WorkingDirNotDir + ok := errors.As(err, &workingDirNotDir) + require.True(t, ok) } func TestDownloadTerraformSourceFromLocalFolderWithManifest(t *testing.T) { @@ -363,7 +366,7 @@ func TestDownloadTerraformSourceFromLocalFolderWithManifest(t *testing.T) { func testDownloadTerraformSourceIfNecessary(t *testing.T, canonicalUrl string, downloadDir string, sourceUpdate bool, expectedFileContents string, requireInitFile bool) { terraformSource, terragruntOptions, terragruntConfig, err := createConfig(t, canonicalUrl, downloadDir, sourceUpdate) - assert.NoError(t, err) + require.NoError(t, err) err = downloadTerraformSourceIfNecessary(context.Background(), terraformSource, terragruntOptions, terragruntConfig) require.NoError(t, err, "For terraform source %v: %v", terraformSource, err) @@ -371,12 +374,12 @@ func testDownloadTerraformSourceIfNecessary(t *testing.T, canonicalUrl string, d expectedFilePath := util.JoinPath(downloadDir, "main.tf") if assert.True(t, util.FileExists(expectedFilePath), "For terraform source %v", terraformSource) { actualFileContents := readFile(t, expectedFilePath) - assert.Equal(t, expectedFileContents, actualFileContents, "For terraform source %v", terraformSource) + require.Equal(t, expectedFileContents, actualFileContents, "For terraform source %v", terraformSource) } if requireInitFile { existsInitFile := util.FileExists(util.JoinPath(terraformSource.WorkingDir, moduleInitRequiredFile)) - assert.True(t, existsInitFile) + require.True(t, existsInitFile) } } @@ -392,7 +395,7 @@ func createConfig(t *testing.T, canonicalUrl string, downloadDir string, sourceU } terragruntOptions, err := options.NewTerragruntOptionsForTest("./should-not-be-used") - assert.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err) terragruntOptions.SourceUpdate = sourceUpdate terragruntOptions.Env = env.Parse(os.Environ()) @@ -405,7 +408,7 @@ func createConfig(t *testing.T, canonicalUrl string, downloadDir string, sourceU } err = PopulateTerraformVersion(context.Background(), terragruntOptions) - assert.Nil(t, err, "For terraform source %v: %v", terraformSource, err) + require.NoError(t, err) return terraformSource, terragruntOptions, terragruntConfig, err } @@ -421,11 +424,11 @@ func testAlreadyHaveLatestCode(t *testing.T, canonicalUrl string, downloadDir st } opts, err := options.NewTerragruntOptionsForTest("./should-not-be-used") - assert.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err) actual, err := alreadyHaveLatestCode(terraformSource, opts) - assert.Nil(t, err, "Unexpected error for terraform source %v: %v", terraformSource, err) - assert.Equal(t, expected, actual, "For terraform source %v", terraformSource) + require.NoError(t, err) + require.Equal(t, expected, actual, "For terraform source %v", terraformSource) } func tmpDir(t *testing.T) string { @@ -465,5 +468,5 @@ func readFile(t *testing.T, path string) string { func copyFolder(t *testing.T, src string, dest string) { err := util.CopyFolderContents(filepath.FromSlash(src), filepath.FromSlash(dest), ".terragrunt-test", nil) - require.Nil(t, err) + require.NoError(t, err) } diff --git a/cli/commands/terraform/hook.go b/cli/commands/terraform/hook.go index 34cb19185..2524ffe20 100644 --- a/cli/commands/terraform/hook.go +++ b/cli/commands/terraform/hook.go @@ -41,9 +41,10 @@ func processErrorHooks(ctx context.Context, hooks []config.ErrorHook, terragrunt // https://github.com/gruntwork-io/terragrunt/issues/2045 originalError := errors.Unwrap(e) if originalError != nil { - processError, cast := originalError.(util.ProcessExecutionError) - if cast { - errorMessage = fmt.Sprintf("%s\n%s", processError.StdOut, processError.Stderr) + var processExecutionError util.ProcessExecutionError + ok := errors.As(originalError, &processExecutionError) + if ok { + errorMessage = fmt.Sprintf("%s\n%s", processExecutionError.StdOut, processExecutionError.Stderr) } } result = fmt.Sprintf("%s\n%s", result, errorMessage) diff --git a/cli/commands/terraform/version_check.go b/cli/commands/terraform/version_check.go index eb5b91e50..767bef51c 100644 --- a/cli/commands/terraform/version_check.go +++ b/cli/commands/terraform/version_check.go @@ -36,7 +36,8 @@ const versionParts = 3 func checkVersionConstraints(ctx context.Context, terragruntOptions *options.TerragruntOptions) error { configContext := config.NewParsingContext(ctx, terragruntOptions).WithDecodeList(config.TerragruntVersionConstraints) - partialTerragruntConfig, err := config.PartialParseConfigFile( + // TODO: See if we should be ignore this lint error + partialTerragruntConfig, err := config.PartialParseConfigFile( //nolint: contextcheck configContext, terragruntOptions.TerragruntConfigPath, nil, diff --git a/cli/commands/terraform/version_check_test.go b/cli/commands/terraform/version_check_test.go index 7d4988b60..1cd0baae0 100644 --- a/cli/commands/terraform/version_check_test.go +++ b/cli/commands/terraform/version_check_test.go @@ -7,6 +7,7 @@ import ( "github.com/gruntwork-io/go-commons/errors" "github.com/hashicorp/go-version" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Terraform Version Checking @@ -93,9 +94,9 @@ func testCheckTerraformVersionMeetsConstraint(t *testing.T, currentVersion strin err = checkTerraformVersionMeetsConstraint(current, versionConstraint) if versionMeetsConstraint && err != nil { - assert.Nil(t, err, "Expected Terraform version %s to meet constraint %s, but got error: %v", currentVersion, versionConstraint, err) + require.NoError(t, err, "Expected Terraform version %s to meet constraint %s, but got error: %v", currentVersion, versionConstraint, err) } else if !versionMeetsConstraint && err == nil { - assert.NotNil(t, err, "Expected Terraform version %s to NOT meet constraint %s, but got back a nil error", currentVersion, versionConstraint) + require.Error(t, err, "Expected Terraform version %s to NOT meet constraint %s, but got back a nil error", currentVersion, versionConstraint) } } @@ -107,7 +108,7 @@ func testParseTerraformVersion(t *testing.T, versionString string, expectedVersi t.Fatalf("Invalid expected version specified in test: %v", err) } - assert.Nil(t, actualErr) + require.NoError(t, actualErr) assert.Equal(t, expected, actualVersion) } else { assert.True(t, errors.IsError(actualErr, expectedErr)) diff --git a/cli/commands/terragrunt-info/action.go b/cli/commands/terragrunt-info/action.go index a03342bd3..06fb87075 100644 --- a/cli/commands/terragrunt-info/action.go +++ b/cli/commands/terragrunt-info/action.go @@ -20,12 +20,12 @@ func Run(ctx context.Context, opts *options.TerragruntOptions) error { // Struct is output as JSON by 'terragrunt-info': type TerragruntInfoGroup struct { - ConfigPath string - DownloadDir string - IamRole string - TerraformBinary string - TerraformCommand string - WorkingDir string + ConfigPath string `json:"ConfigPath"` + DownloadDir string `json:"DownloadDir"` + IamRole string `json:"IamRole"` + TerraformBinary string `json:"TerraformBinary"` + TerraformCommand string `json:"TerraformCommand"` + WorkingDir string `json:"WorkingDir"` } func printTerragruntInfo(opts *options.TerragruntOptions) error { diff --git a/cli/registry_urls.go b/cli/registry_urls.go index 98b565139..db3590749 100644 --- a/cli/registry_urls.go +++ b/cli/registry_urls.go @@ -28,7 +28,8 @@ type RegistryURLs struct { } func (urls *RegistryURLs) String() string { - b, _ := json.Marshal(urls) //nolint:errcheck + // TODO: handle error + b, _ := json.Marshal(urls) //nolint:errcheck,errchkjson return string(b) } diff --git a/codegen/generate.go b/codegen/generate.go index 96b7713e0..c50dae2b3 100644 --- a/codegen/generate.go +++ b/codegen/generate.go @@ -132,7 +132,8 @@ func WriteToFile(terragruntOptions *options.TerragruntOptions, basePath string, // Whether or not file generation should continue if the file path already exists. The answer depends on the // ifExists configuration. func shouldContinueWithFileExists(terragruntOptions *options.TerragruntOptions, path string, ifExists GenerateConfigExists) (bool, error) { - switch ifExists { + // TODO: Make exhaustive + switch ifExists { //nolint:exhaustive case ExistsError: return false, errors.WithStackTrace(GenerateFileExistsError{path: path}) case ExistsSkip: @@ -166,7 +167,8 @@ func shouldContinueWithFileExists(terragruntOptions *options.TerragruntOptions, // shouldRemoveWithFileExists returns true if the already existing file should be removed. func shouldRemoveWithFileExists(terragruntOptions *options.TerragruntOptions, path string, ifDisable GenerateConfigDisabled) (bool, error) { - switch ifDisable { + // TODO: Make exhaustive + switch ifDisable { //nolint:exhaustive case DisabledSkip: // Do nothing since skip was configured. terragruntOptions.Logger.Debugf("The file path %s already exists and if_disabled for code generation set to \"skip\", will not remove file.", path) diff --git a/codegen/generate_test.go b/codegen/generate_test.go index 04e170eaa..25723915c 100644 --- a/codegen/generate_test.go +++ b/codegen/generate_test.go @@ -55,7 +55,7 @@ func TestRemoteStateConfigToTerraformCode(t *testing.T) { // validates the first output. require.True(t, bytes.Contains(output, []byte(testCase.backend))) require.Equal(t, testCase.expected, output) - require.Nil(t, err) + require.NoError(t, err) // runs the function a few of times again. All the outputs must be // equal to the first output. @@ -105,11 +105,11 @@ func TestGenerateDisabling(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("mock-path-for-test.hcl") - require.Nil(t, err) + require.NoError(t, err) require.NotNil(t, opts) err = WriteToFile(opts, "", config) - require.Nil(t, err) + require.NoError(t, err) if testCase.disabled { require.True(t, util.FileNotExists(testCase.path)) diff --git a/config/cache_test.go b/config/cache_test.go index c567173e4..60f2eadac 100644 --- a/config/cache_test.go +++ b/config/cache_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/gruntwork-io/terragrunt/internal/cache" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const testCacheName = "TerragruntConfig" @@ -15,10 +15,10 @@ func TestTerragruntConfigCacheCreation(t *testing.T) { cache := cache.NewCache[TerragruntConfig](testCacheName) - assert.NotNil(t, cache.Mutex) - assert.NotNil(t, cache.Cache) + require.NotNil(t, cache.Mutex) + require.NotNil(t, cache.Cache) - assert.Equal(t, 0, len(cache.Cache)) + require.Empty(t, cache.Cache) } func TestTerragruntConfigCacheOperation(t *testing.T) { @@ -31,8 +31,8 @@ func TestTerragruntConfigCacheOperation(t *testing.T) { actualResult, found := cache.Get(ctx, testCacheKey) - assert.False(t, found) - assert.Empty(t, actualResult) + require.False(t, found) + require.Empty(t, actualResult) stubTerragruntConfig := TerragruntConfig{ IsPartial: true, // Any random property will be sufficient @@ -41,7 +41,7 @@ func TestTerragruntConfigCacheOperation(t *testing.T) { cache.Put(ctx, testCacheKey, stubTerragruntConfig) actualResult, found = cache.Get(ctx, testCacheKey) - assert.True(t, found) - assert.NotEmpty(t, actualResult) - assert.Equal(t, stubTerragruntConfig, actualResult) + require.True(t, found) + require.NotEmpty(t, actualResult) + require.Equal(t, stubTerragruntConfig, actualResult) } diff --git a/config/catalog.go b/config/catalog.go index 6eb854db3..de897aa58 100644 --- a/config/catalog.go +++ b/config/catalog.go @@ -2,11 +2,11 @@ package config import ( "context" + "errors" "fmt" "path/filepath" "regexp" - "github.com/gruntwork-io/go-commons/errors" "github.com/gruntwork-io/go-commons/files" "github.com/gruntwork-io/terragrunt/config/hclparse" "github.com/gruntwork-io/terragrunt/options" @@ -71,7 +71,8 @@ func ReadCatalogConfig(parentCtx context.Context, opts *options.TerragruntOption ctx.ParserOptions = append(ctx.ParserOptions, hclparse.WithHaltOnErrorOnlyForBlocks([]string{MetadataCatalog})) ctx.ConvertToTerragruntConfigFunc = convertToTerragruntCatalogConfig - config, err := ParseConfigString(ctx, configPath, configString, nil) + // TODO: Resolve lint error + config, err := ParseConfigString(ctx, configPath, configString, nil) //nolint:contextcheck if err != nil { return nil, err } @@ -103,7 +104,8 @@ func findCatalogConfig(ctx context.Context, opts *options.TerragruntOptions) (st newConfigPath, err := findInParentFolders(NewParsingContext(ctx, opts), []string{configName}) if err != nil { - if _, ok := errors.Unwrap(err).(ParentFileNotFoundError); ok { + var parentFileNotFoundError ParentFileNotFoundError + if ok := errors.As(err, &parentFileNotFoundError); ok { break } return "", "", err diff --git a/config/config.go b/config/config.go index d6a999b1d..5c769c20c 100644 --- a/config/config.go +++ b/config/config.go @@ -2,6 +2,7 @@ package config import ( "context" + goErrors "errors" "fmt" "net/url" "os" @@ -275,7 +276,7 @@ type remoteStateConfigGenerate struct { // Struct used to parse generate blocks. This will later be converted to GenerateConfig structs so that we can go // through the codegen routine. type terragruntGenerateBlock struct { - Name string `hcl:",label"` + Name string `hcl:",label" mapstructure:",omitempty"` Path string `hcl:"path,attr" mapstructure:"path"` IfExists string `hcl:"if_exists,attr" mapstructure:"if_exists"` IfDisabled *string `hcl:"if_disabled,attr" mapstructure:"if_disabled"` @@ -691,7 +692,9 @@ func ReadTerragruntConfig(ctx context.Context, terragruntOptions *options.Terrag ctx = shell.ContextWithTerraformCommandHook(ctx, nil) parcingCtx := NewParsingContext(ctx, terragruntOptions).WithParseOption(parserOptions) - return ParseConfigFile(parcingCtx, terragruntOptions.TerragruntConfigPath, nil) + + // TODO: Remove lint ignore + return ParseConfigFile(parcingCtx, terragruntOptions.TerragruntConfigPath, nil) //nolint:contextcheck } // Parse the Terragrunt config file at the given path. If the include parameter is not nil, then treat this as a config @@ -722,7 +725,8 @@ func ParseConfigFile(ctx *ParsingContext, configPath string, includeFromChild *I } var file *hclparse.File var cacheKey = fmt.Sprintf("parse-config-%v-%v-%v-%v-%v-%v", configPath, childKey, decodeListKey, ctx.TerragruntOptions.WorkingDir, dir, fileInfo.ModTime().UnixMicro()) - if cacheConfig, found := hclCache.Get(ctx, cacheKey); found { + // TODO: Remove lint ignore + if cacheConfig, found := hclCache.Get(ctx, cacheKey); found { //nolint:contextcheck file = cacheConfig } else { // Parse the HCL file into an AST body that can be decoded multiple times later without having to re-parse @@ -730,9 +734,12 @@ func ParseConfigFile(ctx *ParsingContext, configPath string, includeFromChild *I if err != nil { return err } - hclCache.Put(ctx, cacheKey, file) + // TODO: Remove lint ignore + hclCache.Put(ctx, cacheKey, file) //nolint:contextcheck } - config, err = ParseConfig(ctx, file, includeFromChild) + + // TODO: Remove lint ignore + config, err = ParseConfig(ctx, file, includeFromChild) //nolint:contextcheck if err != nil { return err } @@ -886,7 +893,9 @@ func decodeAsTerragruntConfigFile(ctx *ParsingContext, file *hclparse.File, eval terragruntConfig := terragruntConfigFile{} if err := file.Decode(&terragruntConfig, evalContext); err != nil { - diagErr, ok := errors.Unwrap(err).(hcl.Diagnostics) + var diagErr hcl.Diagnostics + // diagErr, ok := errors.Unwrap(err).(hcl.Diagnostics) + ok := goErrors.As(err, &diagErr) // in case of render-json command and inputs reference error, we update the inputs with default value if !ok || !isRenderJsonCommand(ctx) || !isAttributeAccessError(diagErr) { diff --git a/config/config_helpers_test.go b/config/config_helpers_test.go index 063a9e61d..a85d09328 100644 --- a/config/config_helpers_test.go +++ b/config/config_helpers_test.go @@ -31,45 +31,45 @@ func TestPathRelativeToInclude(t *testing.T) { ".", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/"+DefaultTerragruntConfigPath), "child", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/"+DefaultTerragruntConfigPath), "child", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../../../" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../../../" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/sub-sub-child/"+DefaultTerragruntConfigPath), "child/sub-child/sub-sub-child", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/sub-sub-child/"+DefaultTerragruntConfigPath), "child/sub-child/sub-sub-child", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../../other-child/" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../../other-child/" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/"+DefaultTerragruntConfigPath), "../child/sub-child", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../../" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../../" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, "../child/sub-child/"+DefaultTerragruntConfigPath), "child/sub-child", }, { map[string]IncludeConfig{ - "root": IncludeConfig{Path: "../../" + DefaultTerragruntConfigPath}, - "child": IncludeConfig{Path: "../../other-child/" + DefaultTerragruntConfigPath}, + "root": {Path: "../../" + DefaultTerragruntConfigPath}, + "child": {Path: "../../other-child/" + DefaultTerragruntConfigPath}, }, []string{"child"}, terragruntOptionsForTest(t, "../child/sub-child/"+DefaultTerragruntConfigPath), @@ -81,8 +81,8 @@ func TestPathRelativeToInclude(t *testing.T) { trackInclude := getTrackIncludeFromTestData(testCase.include, testCase.params) ctx := NewParsingContext(context.Background(), testCase.terragruntOptions).WithTrackInclude(trackInclude) actualPath, actualErr := pathRelativeToInclude(ctx, testCase.params) - assert.Nil(t, actualErr, "For include %v and options %v, unexpected error: %v", testCase.include, testCase.terragruntOptions, actualErr) - assert.Equal(t, testCase.expectedPath, actualPath, "For include %v and options %v", testCase.include, testCase.terragruntOptions) + require.NoError(t, actualErr, "For include %v and options %v, unexpected error: %v", testCase.include, testCase.terragruntOptions, actualErr) + require.Equal(t, testCase.expectedPath, actualPath, "For include %v and options %v", testCase.include, testCase.terragruntOptions) } } @@ -102,45 +102,45 @@ func TestPathRelativeFromInclude(t *testing.T) { ".", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/"+DefaultTerragruntConfigPath), "..", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/"+DefaultTerragruntConfigPath), "..", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../../../" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../../../" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/sub-sub-child/"+DefaultTerragruntConfigPath), "../../..", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/sub-sub-child/"+DefaultTerragruntConfigPath), "../../..", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../../other-child/" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../../other-child/" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/"+DefaultTerragruntConfigPath), "../../other-child", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../../" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../../" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, "../child/sub-child/"+DefaultTerragruntConfigPath), "../..", }, { map[string]IncludeConfig{ - "root": IncludeConfig{Path: "../../" + DefaultTerragruntConfigPath}, - "child": IncludeConfig{Path: "../../other-child/" + DefaultTerragruntConfigPath}, + "root": {Path: "../../" + DefaultTerragruntConfigPath}, + "child": {Path: "../../other-child/" + DefaultTerragruntConfigPath}, }, []string{"child"}, terragruntOptionsForTest(t, "../child/sub-child/"+DefaultTerragruntConfigPath), @@ -152,8 +152,8 @@ func TestPathRelativeFromInclude(t *testing.T) { trackInclude := getTrackIncludeFromTestData(testCase.include, testCase.params) ctx := NewParsingContext(context.Background(), testCase.terragruntOptions).WithTrackInclude(trackInclude) actualPath, actualErr := pathRelativeFromInclude(ctx, testCase.params) - assert.Nil(t, actualErr, "For include %v and options %v, unexpected error: %v", testCase.include, testCase.terragruntOptions, actualErr) - assert.Equal(t, testCase.expectedPath, actualPath, "For include %v and options %v", testCase.include, testCase.terragruntOptions) + require.NoError(t, actualErr, "For include %v and options %v, unexpected error: %v", testCase.include, testCase.terragruntOptions, actualErr) + require.Equal(t, testCase.expectedPath, actualPath, "For include %v and options %v", testCase.include, testCase.terragruntOptions) } } @@ -225,8 +225,8 @@ func TestRunCommand(t *testing.T) { assert.IsType(t, testCase.expectedErr, errors.Unwrap(actualErr)) } } else { - assert.Nil(t, actualErr) - assert.Equal(t, testCase.expectedOutput, actualOutput) + require.NoError(t, actualErr) + require.Equal(t, testCase.expectedOutput, actualOutput) } }) } @@ -330,8 +330,8 @@ func TestFindInParentFolders(t *testing.T) { assert.IsType(t, testCase.expectedErr, errors.Unwrap(actualErr)) } } else { - assert.Nil(t, actualErr) - assert.Equal(t, testCase.expectedPath, actualPath) + require.NoError(t, actualErr) + require.Equal(t, testCase.expectedPath, actualPath) } }) } @@ -615,14 +615,14 @@ func toStringSlice(t *testing.T, value interface{}) []string { func TestGetTerragruntDirAbsPath(t *testing.T) { t.Parallel() workingDir, err := os.Getwd() - assert.Nil(t, err, "Could not get current working dir: %v", err) + require.NoError(t, err, "Could not get current working dir: %v", err) testGetTerragruntDir(t, "/foo/bar/terragrunt.hcl", fmt.Sprintf("%s/foo/bar", filepath.VolumeName(workingDir))) } func TestGetTerragruntDirRelPath(t *testing.T) { t.Parallel() workingDir, err := os.Getwd() - assert.Nil(t, err, "Could not get current working dir: %v", err) + require.NoError(t, err, "Could not get current working dir: %v", err) workingDir = filepath.ToSlash(workingDir) testGetTerragruntDir(t, "foo/bar/terragrunt.hcl", fmt.Sprintf("%s/foo/bar", workingDir)) @@ -630,12 +630,12 @@ func TestGetTerragruntDirRelPath(t *testing.T) { func testGetTerragruntDir(t *testing.T, configPath string, expectedPath string) { terragruntOptions, err := options.NewTerragruntOptionsForTest(configPath) - assert.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) ctx := NewParsingContext(context.Background(), terragruntOptions) actualPath, err := getTerragruntDir(ctx) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) assert.Equal(t, expectedPath, actualPath) } @@ -663,7 +663,7 @@ func TestGetParentTerragruntDir(t *testing.T) { t.Parallel() currentDir, err := os.Getwd() - assert.Nil(t, err, "Could not get current working dir: %v", err) + require.NoError(t, err, "Could not get current working dir: %v", err) parentDir := filepath.ToSlash(filepath.Dir(currentDir)) testCases := []struct { @@ -679,45 +679,45 @@ func TestGetParentTerragruntDir(t *testing.T) { helpers.RootFolder + "child", }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/"+DefaultTerragruntConfigPath), helpers.RootFolder, }, { - map[string]IncludeConfig{"": IncludeConfig{Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/"+DefaultTerragruntConfigPath), helpers.RootFolder, }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../../../" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../../../" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/sub-sub-child/"+DefaultTerragruntConfigPath), helpers.RootFolder, }, { - map[string]IncludeConfig{"": IncludeConfig{Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: helpers.RootFolder + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/sub-sub-child/"+DefaultTerragruntConfigPath), helpers.RootFolder, }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../../other-child/" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../../other-child/" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/"+DefaultTerragruntConfigPath), fmt.Sprintf("%s/other-child", filepath.VolumeName(parentDir)), }, { - map[string]IncludeConfig{"": IncludeConfig{Path: "../../" + DefaultTerragruntConfigPath}}, + map[string]IncludeConfig{"": {Path: "../../" + DefaultTerragruntConfigPath}}, nil, terragruntOptionsForTest(t, "../child/sub-child/"+DefaultTerragruntConfigPath), parentDir, }, { map[string]IncludeConfig{ - "root": IncludeConfig{Path: "../../" + DefaultTerragruntConfigPath}, - "child": IncludeConfig{Path: "../../other-child/" + DefaultTerragruntConfigPath}, + "root": {Path: "../../" + DefaultTerragruntConfigPath}, + "child": {Path: "../../other-child/" + DefaultTerragruntConfigPath}, }, []string{"child"}, terragruntOptionsForTest(t, helpers.RootFolder+"child/sub-child/"+DefaultTerragruntConfigPath), @@ -729,8 +729,8 @@ func TestGetParentTerragruntDir(t *testing.T) { trackInclude := getTrackIncludeFromTestData(testCase.include, testCase.params) ctx := NewParsingContext(context.Background(), testCase.terragruntOptions).WithTrackInclude(trackInclude) actualPath, actualErr := getParentTerragruntDir(ctx, testCase.params) - assert.Nil(t, actualErr, "For include %v and options %v, unexpected error: %v", testCase.include, testCase.terragruntOptions, actualErr) - assert.Equal(t, testCase.expectedPath, actualPath, "For include %v and options %v", testCase.include, testCase.terragruntOptions) + require.NoError(t, actualErr, "For include %v and options %v, unexpected error: %v", testCase.include, testCase.terragruntOptions, actualErr) + require.Equal(t, testCase.expectedPath, actualPath, "For include %v and options %v", testCase.include, testCase.terragruntOptions) } } @@ -854,8 +854,8 @@ func TestTerraformOutputJsonToCtyValueMap(t *testing.T) { mockTargetConfig := DefaultTerragruntConfigPath for _, testCase := range testCases { converted, err := terraformOutputJsonToCtyValueMap(mockTargetConfig, []byte(testCase.input)) - assert.NoError(t, err) - assert.Equal(t, getKeys(converted), getKeys(testCase.expected)) + require.NoError(t, err) + require.Equal(t, getKeys(converted), getKeys(testCase.expected)) for k, v := range converted { assert.True(t, v.Equals(testCase.expected[k]).True()) } @@ -875,34 +875,29 @@ func TestReadTerragruntConfigInputs(t *testing.T) { require.NoError(t, err) inputsMap := tgConfigMap["inputs"].(map[string]interface{}) - assert.Equal(t, inputsMap["string"].(string), "string") - assert.Equal(t, inputsMap["number"].(float64), float64(42)) - assert.Equal(t, inputsMap["bool"].(bool), true) - assert.Equal(t, inputsMap["list_string"].([]interface{}), []interface{}{"a", "b", "c"}) - assert.Equal(t, inputsMap["list_number"].([]interface{}), []interface{}{float64(1), float64(2), float64(3)}) - assert.Equal(t, inputsMap["list_bool"].([]interface{}), []interface{}{true, false}) - assert.Equal(t, inputsMap["map_string"].(map[string]interface{}), map[string]interface{}{"foo": "bar"}) - assert.Equal( - t, - inputsMap["map_number"].(map[string]interface{}), - map[string]interface{}{"foo": float64(42), "bar": float64(12345)}, - ) - assert.Equal( - t, - inputsMap["map_bool"].(map[string]interface{}), - map[string]interface{}{"foo": true, "bar": false, "baz": true}, - ) - assert.Equal( + + require.Equal(t, "string", inputsMap["string"].(string)) + require.InEpsilon(t, float64(42), inputsMap["number"].(float64), 0.0000000001) + require.True(t, inputsMap["bool"].(bool)) + require.Equal(t, []interface{}{"a", "b", "c"}, inputsMap["list_string"].([]interface{})) + require.Equal(t, []interface{}{float64(1), float64(2), float64(3)}, inputsMap["list_number"].([]interface{})) + require.Equal(t, []interface{}{true, false}, inputsMap["list_bool"].([]interface{})) + require.Equal(t, map[string]interface{}{"foo": "bar"}, inputsMap["map_string"].(map[string]interface{})) + require.Equal(t, map[string]interface{}{"foo": float64(42), "bar": float64(12345)}, inputsMap["map_number"].(map[string]interface{})) + require.Equal(t, map[string]interface{}{"foo": true, "bar": false, "baz": true}, inputsMap["map_bool"].(map[string]interface{})) + + require.Equal( t, - inputsMap["object"].(map[string]interface{}), map[string]interface{}{ "str": "string", "num": float64(42), "list": []interface{}{float64(1), float64(2), float64(3)}, "map": map[string]interface{}{"foo": "bar"}, }, + inputsMap["object"].(map[string]interface{}), ) - assert.Equal(t, inputsMap["from_env"].(string), "default") + + require.Equal(t, "default", inputsMap["from_env"].(string)) } func TestReadTerragruntConfigRemoteState(t *testing.T) { @@ -917,24 +912,24 @@ func TestReadTerragruntConfigRemoteState(t *testing.T) { require.NoError(t, err) remoteStateMap := tgConfigMap["remote_state"].(map[string]interface{}) - assert.Equal(t, remoteStateMap["backend"].(string), "s3") + require.Equal(t, "s3", remoteStateMap["backend"].(string)) configMap := remoteStateMap["config"].(map[string]interface{}) - assert.Equal(t, configMap["encrypt"].(bool), true) - assert.Equal(t, configMap["key"].(string), "terraform.tfstate") - assert.Equal( + require.True(t, configMap["encrypt"].(bool)) + require.Equal(t, "terraform.tfstate", configMap["key"].(string)) + require.Equal( t, - configMap["s3_bucket_tags"].(map[string]interface{}), map[string]interface{}{"owner": "terragrunt integration test", "name": "Terraform state storage"}, + configMap["s3_bucket_tags"].(map[string]interface{}), ) - assert.Equal( + require.Equal( t, - configMap["dynamodb_table_tags"].(map[string]interface{}), map[string]interface{}{"owner": "terragrunt integration test", "name": "Terraform lock table"}, + configMap["dynamodb_table_tags"].(map[string]interface{}), ) - assert.Equal( + require.Equal( t, - configMap["accesslogging_bucket_tags"].(map[string]interface{}), map[string]interface{}{"owner": "terragrunt integration test", "name": "Terraform access log storage"}, + configMap["accesslogging_bucket_tags"].(map[string]interface{}), ) } @@ -951,33 +946,33 @@ func TestReadTerragruntConfigHooks(t *testing.T) { terraformMap := tgConfigMap["terraform"].(map[string]interface{}) beforeHooksMap := terraformMap["before_hook"].(map[string]interface{}) - assert.Equal( + require.Equal( t, - beforeHooksMap["before_hook_1"].(map[string]interface{})["execute"].([]interface{}), []interface{}{"touch", "before.out"}, + beforeHooksMap["before_hook_1"].(map[string]interface{})["execute"].([]interface{}), ) - assert.Equal( + require.Equal( t, - beforeHooksMap["before_hook_2"].(map[string]interface{})["execute"].([]interface{}), []interface{}{"echo", "BEFORE_TERRAGRUNT_READ_CONFIG"}, + beforeHooksMap["before_hook_2"].(map[string]interface{})["execute"].([]interface{}), ) afterHooksMap := terraformMap["after_hook"].(map[string]interface{}) - assert.Equal( + require.Equal( t, - afterHooksMap["after_hook_1"].(map[string]interface{})["execute"].([]interface{}), []interface{}{"touch", "after.out"}, + afterHooksMap["after_hook_1"].(map[string]interface{})["execute"].([]interface{}), ) - assert.Equal( + require.Equal( t, - afterHooksMap["after_hook_2"].(map[string]interface{})["execute"].([]interface{}), []interface{}{"echo", "AFTER_TERRAGRUNT_READ_CONFIG"}, + afterHooksMap["after_hook_2"].(map[string]interface{})["execute"].([]interface{}), ) errorHooksMap := terraformMap["error_hook"].(map[string]interface{}) - assert.Equal( + require.Equal( t, - errorHooksMap["error_hook_1"].(map[string]interface{})["execute"].([]interface{}), []interface{}{"echo", "ON_APPLY_ERROR"}, + errorHooksMap["error_hook_1"].(map[string]interface{})["execute"].([]interface{}), ) } @@ -993,9 +988,9 @@ func TestReadTerragruntConfigLocals(t *testing.T) { require.NoError(t, err) localsMap := tgConfigMap["locals"].(map[string]interface{}) - assert.Equal(t, localsMap["x"].(float64), float64(2)) - assert.Equal(t, localsMap["file_contents"].(string), "Hello world\n") - assert.Equal(t, localsMap["number_expression"].(float64), float64(42)) + require.InEpsilon(t, float64(2), localsMap["x"].(float64), 0.0000000001) + require.Equal(t, "Hello world\n", localsMap["file_contents"].(string)) + require.InEpsilon(t, float64(42), localsMap["number_expression"].(float64), 0.0000000001) } func TestGetTerragruntSourceForModuleHappyPath(t *testing.T) { @@ -1054,8 +1049,8 @@ func TestStartsWith(t *testing.T) { t.Run(fmt.Sprintf("%v %v", id, testCase.args), func(t *testing.T) { ctx := NewParsingContext(context.Background(), testCase.config) actual, err := startsWith(ctx, testCase.args) - assert.NoError(t, err) - assert.Equal(t, testCase.value, actual) + require.NoError(t, err) + require.Equal(t, testCase.value, actual) }) } } @@ -1084,8 +1079,8 @@ func TestEndsWith(t *testing.T) { t.Run(fmt.Sprintf("%v %v", id, testCase.args), func(t *testing.T) { ctx := NewParsingContext(context.Background(), testCase.config) actual, err := endsWith(ctx, testCase.args) - assert.NoError(t, err) - assert.Equal(t, testCase.value, actual) + require.NoError(t, err) + require.Equal(t, testCase.value, actual) }) } } @@ -1118,9 +1113,9 @@ func TestTimeCmp(t *testing.T) { ctx := NewParsingContext(context.Background(), testCase.config) actual, err := timeCmp(ctx, testCase.args) if testCase.err != "" { - assert.EqualError(t, err, testCase.err) + require.EqualError(t, err, testCase.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, testCase.value, actual) @@ -1155,9 +1150,9 @@ func TestStrContains(t *testing.T) { ctx := NewParsingContext(context.Background(), testCase.config) actual, err := strContains(ctx, testCase.args) if testCase.err != "" { - assert.EqualError(t, err, testCase.err) + require.EqualError(t, err, testCase.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, testCase.value, actual) @@ -1178,14 +1173,14 @@ func TestReadTFVarsFiles(t *testing.T) { locals := tgConfigMap["locals"].(map[string]interface{}) - assert.Equal(t, locals["string_var"].(string), "string") - assert.Equal(t, locals["number_var"].(float64), float64(42)) - assert.Equal(t, locals["bool_var"].(bool), true) - assert.Equal(t, locals["list_var"].([]interface{}), []interface{}{"hello", "world"}) + require.Equal(t, "string", locals["string_var"].(string)) + require.InEpsilon(t, float64(42), locals["number_var"].(float64), 0.0000000001) + require.True(t, locals["bool_var"].(bool)) + require.Equal(t, []interface{}{"hello", "world"}, locals["list_var"].([]interface{})) - assert.Equal(t, locals["json_number_var"].(float64), float64(24)) - assert.Equal(t, locals["json_string_var"].(string), "another string") - assert.Equal(t, locals["json_bool_var"].(bool), false) + require.InEpsilon(t, float64(24), locals["json_number_var"].(float64), 0.0000000001) + require.Equal(t, "another string", locals["json_string_var"].(string)) + require.False(t, locals["json_bool_var"].(bool)) } func mockConfigWithSource(sourceUrl string) *TerragruntConfig { diff --git a/config/config_partial.go b/config/config_partial.go index e6fa0528b..443cfc118 100644 --- a/config/config_partial.go +++ b/config/config_partial.go @@ -1,6 +1,7 @@ package config import ( + goErrors "errors" "fmt" "os" "path/filepath" @@ -327,7 +328,8 @@ func PartialParseConfig(ctx *ParsingContext, file *hclparse.File, includeFromChi } if err := file.Decode(&decoded, evalParsingContext); err != nil { - diagErr, ok := errors.Unwrap(err).(hcl.Diagnostics) + var diagErr hcl.Diagnostics + ok := goErrors.As(err, &diagErr) // in case of render-json command and inputs reference error, we update the inputs with default value if !ok || !isRenderJsonCommand(ctx) || !isAttributeAccessError(diagErr) { diff --git a/config/config_partial_test.go b/config/config_partial_test.go index 8e8cc863e..c63511335 100644 --- a/config/config_partial_test.go +++ b/config/config_partial_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/zclconf/go-cty/cty" ) @@ -25,18 +24,18 @@ dependencies { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(DependenciesBlock) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.Dependencies) - assert.Equal(t, len(terragruntConfig.Dependencies.Paths), 1) - assert.Equal(t, terragruntConfig.Dependencies.Paths[0], "../app1") - assert.Equal(t, map[string]interface{}{"app1": "../app1"}, terragruntConfig.Locals) + require.Len(t, terragruntConfig.Dependencies.Paths, 1) + require.Equal(t, "../app1", terragruntConfig.Dependencies.Paths[0]) + require.Equal(t, map[string]interface{}{"app1": "../app1"}, terragruntConfig.Locals) - assert.False(t, terragruntConfig.Skip) - assert.Nil(t, terragruntConfig.PreventDestroy) - assert.Nil(t, terragruntConfig.Terraform) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Inputs) + require.False(t, terragruntConfig.Skip) + require.Nil(t, terragruntConfig.PreventDestroy) + require.Nil(t, terragruntConfig.Terraform) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Inputs) } func TestPartialParseDoesNotResolveIgnoredBlock(t *testing.T) { @@ -53,10 +52,10 @@ prevent_destroy = false ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)) _, err := PartialParseConfigString(ctx.WithDecodeList(TerragruntFlags), DefaultTerragruntConfigPath, config, nil) - assert.NoError(t, err) + require.NoError(t, err) _, err = PartialParseConfigString(ctx.WithDecodeList(DependenciesBlock), DefaultTerragruntConfigPath, config, nil) - assert.Error(t, err) + require.Error(t, err) } func TestPartialParseMultipleItems(t *testing.T) { @@ -74,19 +73,19 @@ skip = true ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(DependenciesBlock, TerragruntFlags) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.Dependencies) - assert.Equal(t, len(terragruntConfig.Dependencies.Paths), 1) - assert.Equal(t, terragruntConfig.Dependencies.Paths[0], "../app1") + require.Len(t, terragruntConfig.Dependencies.Paths, 1) + require.Equal(t, "../app1", terragruntConfig.Dependencies.Paths[0]) - assert.True(t, terragruntConfig.Skip) - assert.True(t, *terragruntConfig.PreventDestroy) + require.True(t, terragruntConfig.Skip) + require.True(t, *terragruntConfig.PreventDestroy) - assert.Nil(t, terragruntConfig.Terraform) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Inputs) - assert.Nil(t, terragruntConfig.Locals) + require.Nil(t, terragruntConfig.Terraform) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Inputs) + require.Nil(t, terragruntConfig.Locals) } func TestPartialParseOmittedItems(t *testing.T) { @@ -96,14 +95,14 @@ func TestPartialParseOmittedItems(t *testing.T) { terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, "", nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) - assert.Nil(t, terragruntConfig.Dependencies) - assert.False(t, terragruntConfig.Skip) - assert.Nil(t, terragruntConfig.PreventDestroy) - assert.Nil(t, terragruntConfig.Terraform) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Inputs) - assert.Nil(t, terragruntConfig.Locals) + require.True(t, terragruntConfig.IsPartial) + require.Nil(t, terragruntConfig.Dependencies) + require.False(t, terragruntConfig.Skip) + require.Nil(t, terragruntConfig.PreventDestroy) + require.Nil(t, terragruntConfig.Terraform) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Inputs) + require.Nil(t, terragruntConfig.Locals) } func TestPartialParseDoesNotResolveIgnoredBlockEvenInParent(t *testing.T) { @@ -113,10 +112,10 @@ func TestPartialParseDoesNotResolveIgnoredBlockEvenInParent(t *testing.T) { ctx := NewParsingContext(context.Background(), opts) _, err := PartialParseConfigFile(ctx.WithDecodeList(TerragruntFlags), opts.TerragruntConfigPath, nil) - assert.NoError(t, err) + require.NoError(t, err) _, err = PartialParseConfigFile(ctx.WithDecodeList(DependenciesBlock), opts.TerragruntConfigPath, nil) - assert.Error(t, err) + require.Error(t, err) } func TestPartialParseOnlyInheritsSelectedBlocksFlags(t *testing.T) { @@ -128,14 +127,14 @@ func TestPartialParseOnlyInheritsSelectedBlocksFlags(t *testing.T) { terragruntConfig, err := PartialParseConfigFile(ctx, opts.TerragruntConfigPath, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) - assert.Nil(t, terragruntConfig.Dependencies) - assert.False(t, terragruntConfig.Skip) - assert.True(t, *terragruntConfig.PreventDestroy) - assert.Nil(t, terragruntConfig.Terraform) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Inputs) - assert.Nil(t, terragruntConfig.Locals) + require.True(t, terragruntConfig.IsPartial) + require.Nil(t, terragruntConfig.Dependencies) + require.False(t, terragruntConfig.Skip) + require.True(t, *terragruntConfig.PreventDestroy) + require.Nil(t, terragruntConfig.Terraform) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Inputs) + require.Nil(t, terragruntConfig.Locals) } func TestPartialParseOnlyInheritsSelectedBlocksDependencies(t *testing.T) { @@ -147,18 +146,18 @@ func TestPartialParseOnlyInheritsSelectedBlocksDependencies(t *testing.T) { terragruntConfig, err := PartialParseConfigFile(ctx, opts.TerragruntConfigPath, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.Dependencies) - assert.Equal(t, len(terragruntConfig.Dependencies.Paths), 1) - assert.Equal(t, terragruntConfig.Dependencies.Paths[0], "../app1") + require.Len(t, terragruntConfig.Dependencies.Paths, 1) + require.Equal(t, "../app1", terragruntConfig.Dependencies.Paths[0]) - assert.False(t, terragruntConfig.Skip) - assert.Nil(t, terragruntConfig.PreventDestroy) - assert.Nil(t, terragruntConfig.Terraform) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Inputs) - assert.Nil(t, terragruntConfig.Locals) + require.False(t, terragruntConfig.Skip) + require.Nil(t, terragruntConfig.PreventDestroy) + require.Nil(t, terragruntConfig.Terraform) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Inputs) + require.Nil(t, terragruntConfig.Locals) } func TestPartialParseDependencyBlockSetsTerragruntDependencies(t *testing.T) { @@ -173,12 +172,12 @@ dependency "vpc" { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(DependencyBlock) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.TerragruntDependencies) - assert.Equal(t, len(terragruntConfig.TerragruntDependencies), 1) - assert.Equal(t, terragruntConfig.TerragruntDependencies[0].Name, "vpc") - assert.Equal(t, terragruntConfig.TerragruntDependencies[0].ConfigPath, cty.StringVal("../app1")) + require.Len(t, terragruntConfig.TerragruntDependencies, 1) + require.Equal(t, "vpc", terragruntConfig.TerragruntDependencies[0].Name) + require.Equal(t, cty.StringVal("../app1"), terragruntConfig.TerragruntDependencies[0].ConfigPath) } func TestPartialParseMultipleDependencyBlockSetsTerragruntDependencies(t *testing.T) { @@ -197,14 +196,14 @@ dependency "sql" { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(DependencyBlock) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.TerragruntDependencies) - assert.Equal(t, len(terragruntConfig.TerragruntDependencies), 2) - assert.Equal(t, terragruntConfig.TerragruntDependencies[0].Name, "vpc") - assert.Equal(t, terragruntConfig.TerragruntDependencies[0].ConfigPath, cty.StringVal("../app1")) - assert.Equal(t, terragruntConfig.TerragruntDependencies[1].Name, "sql") - assert.Equal(t, terragruntConfig.TerragruntDependencies[1].ConfigPath, cty.StringVal("../db1")) + require.Len(t, terragruntConfig.TerragruntDependencies, 2) + require.Equal(t, "vpc", terragruntConfig.TerragruntDependencies[0].Name) + require.Equal(t, cty.StringVal("../app1"), terragruntConfig.TerragruntDependencies[0].ConfigPath) + require.Equal(t, "sql", terragruntConfig.TerragruntDependencies[1].Name) + require.Equal(t, cty.StringVal("../db1"), terragruntConfig.TerragruntDependencies[1].ConfigPath) } func TestPartialParseDependencyBlockSetsDependencies(t *testing.T) { @@ -223,11 +222,11 @@ dependency "sql" { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(DependencyBlock) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.Dependencies) - assert.Equal(t, len(terragruntConfig.Dependencies.Paths), 2) - assert.Equal(t, terragruntConfig.Dependencies.Paths, []string{"../app1", "../db1"}) + require.Len(t, terragruntConfig.Dependencies.Paths, 2) + require.Equal(t, []string{"../app1", "../db1"}, terragruntConfig.Dependencies.Paths) } func TestPartialParseDependencyBlockMergesDependencies(t *testing.T) { @@ -250,11 +249,11 @@ dependency "sql" { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(DependenciesBlock, DependencyBlock) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.Dependencies) - assert.Equal(t, len(terragruntConfig.Dependencies.Paths), 3) - assert.Equal(t, terragruntConfig.Dependencies.Paths, []string{"../vpc", "../app1", "../db1"}) + require.Len(t, terragruntConfig.Dependencies.Paths, 3) + require.Equal(t, []string{"../vpc", "../app1", "../db1"}, terragruntConfig.Dependencies.Paths) } func TestPartialParseDependencyBlockMergesDependenciesOrdering(t *testing.T) { @@ -277,11 +276,11 @@ dependency "sql" { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(DependencyBlock, DependenciesBlock) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.Dependencies) - assert.Equal(t, len(terragruntConfig.Dependencies.Paths), 3) - assert.Equal(t, terragruntConfig.Dependencies.Paths, []string{"../app1", "../db1", "../vpc"}) + require.Len(t, terragruntConfig.Dependencies.Paths, 3) + require.Equal(t, []string{"../app1", "../db1", "../vpc"}, terragruntConfig.Dependencies.Paths) } func TestPartialParseDependencyBlockMergesDependenciesDedup(t *testing.T) { @@ -304,11 +303,11 @@ dependency "sql" { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(DependencyBlock, DependenciesBlock) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.Dependencies) - assert.Equal(t, len(terragruntConfig.Dependencies.Paths), 2) - assert.Equal(t, terragruntConfig.Dependencies.Paths, []string{"../app1", "../db1"}) + require.Len(t, terragruntConfig.Dependencies.Paths, 2) + require.Equal(t, []string{"../app1", "../db1"}, terragruntConfig.Dependencies.Paths) } func TestPartialParseOnlyParsesTerraformSource(t *testing.T) { @@ -331,11 +330,11 @@ terraform { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(TerraformSource) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.True(t, terragruntConfig.IsPartial) + require.True(t, terragruntConfig.IsPartial) require.NotNil(t, terragruntConfig.Terraform) require.NotNil(t, terragruntConfig.Terraform.Source) - assert.Equal(t, *terragruntConfig.Terraform.Source, "../../modules/app") + require.Equal(t, "../../modules/app", *terragruntConfig.Terraform.Source) } func TestOptionalDependenciesAreSkipped(t *testing.T) { @@ -354,5 +353,5 @@ dependency "ec2" { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)).WithDecodeList(DependencyBlock) terragruntConfig, err := PartialParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) require.NoError(t, err) - assert.Len(t, terragruntConfig.Dependencies.Paths, 1) + require.Len(t, terragruntConfig.Dependencies.Paths, 1) } diff --git a/config/config_test.go b/config/config_test.go index e46f883ad..8554f74e4 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -218,8 +218,8 @@ func TestParseTerragruntJsonConfigRetryConfiguration(t *testing.T) { assert.Nil(t, terragruntConfig.Terraform) assert.Empty(t, terragruntConfig.IamRole) - assert.Equal(t, *terragruntConfig.RetryMaxAttempts, 10) - assert.Equal(t, *terragruntConfig.RetrySleepIntervalSec, 60) + require.Equal(t, 10, *terragruntConfig.RetryMaxAttempts) + require.Equal(t, 60, *terragruntConfig.RetrySleepIntervalSec) if assert.NotNil(t, terragruntConfig.RetryableErrors) { assert.Equal(t, []string{"My own little error"}, terragruntConfig.RetryableErrors) @@ -469,16 +469,16 @@ include { ctx := NewParsingContext(context.Background(), opts) terragruntConfig, err := ParseConfigString(ctx, opts.TerragruntConfigPath, config, nil) - if assert.Nil(t, err, "Unexpected error: %v", errors.PrintErrorWithStackTrace(err)) { - assert.Nil(t, terragruntConfig.Terraform) + if assert.NoError(t, err, "Unexpected error: %v", errors.PrintErrorWithStackTrace(err)) { + require.Nil(t, terragruntConfig.Terraform) if assert.NotNil(t, terragruntConfig.RemoteState) { - assert.Equal(t, "s3", terragruntConfig.RemoteState.Backend) - assert.NotEmpty(t, terragruntConfig.RemoteState.Config) - assert.Equal(t, true, terragruntConfig.RemoteState.Config["encrypt"]) - assert.Equal(t, "my-bucket", terragruntConfig.RemoteState.Config["bucket"]) - assert.Equal(t, "child/sub-child/sub-sub-child/terraform.tfstate", terragruntConfig.RemoteState.Config["key"]) - assert.Equal(t, "us-east-1", terragruntConfig.RemoteState.Config["region"]) + require.Equal(t, "s3", terragruntConfig.RemoteState.Backend) + require.NotEmpty(t, terragruntConfig.RemoteState.Config) + require.Equal(t, true, terragruntConfig.RemoteState.Config["encrypt"]) + require.Equal(t, "my-bucket", terragruntConfig.RemoteState.Config["bucket"]) + require.Equal(t, "child/sub-child/sub-sub-child/terraform.tfstate", terragruntConfig.RemoteState.Config["key"]) + require.Equal(t, "us-east-1", terragruntConfig.RemoteState.Config["region"]) } } @@ -497,16 +497,16 @@ include { ctx := NewParsingContext(context.Background(), opts) terragruntConfig, err := ParseConfigString(ctx, opts.TerragruntConfigPath, config, nil) - if assert.Nil(t, err, "Unexpected error: %v", errors.PrintErrorWithStackTrace(err)) { - assert.Nil(t, terragruntConfig.Terraform) + if assert.NoError(t, err, "Unexpected error: %v", errors.PrintErrorWithStackTrace(err)) { + require.Nil(t, terragruntConfig.Terraform) if assert.NotNil(t, terragruntConfig.RemoteState) { - assert.Equal(t, "s3", terragruntConfig.RemoteState.Backend) - assert.NotEmpty(t, terragruntConfig.RemoteState.Config) - assert.Equal(t, true, terragruntConfig.RemoteState.Config["encrypt"]) - assert.Equal(t, "my-bucket", terragruntConfig.RemoteState.Config["bucket"]) - assert.Equal(t, "child/sub-child/sub-sub-child/terraform.tfstate", terragruntConfig.RemoteState.Config["key"]) - assert.Equal(t, "us-east-1", terragruntConfig.RemoteState.Config["region"]) + require.Equal(t, "s3", terragruntConfig.RemoteState.Backend) + require.NotEmpty(t, terragruntConfig.RemoteState.Config) + require.Equal(t, true, terragruntConfig.RemoteState.Config["encrypt"]) + require.Equal(t, "my-bucket", terragruntConfig.RemoteState.Config["bucket"]) + require.Equal(t, "child/sub-child/sub-sub-child/terraform.tfstate", terragruntConfig.RemoteState.Config["key"]) + require.Equal(t, "us-east-1", terragruntConfig.RemoteState.Config["region"]) } } @@ -537,16 +537,16 @@ remote_state { ctx := NewParsingContext(context.Background(), opts) terragruntConfig, err := ParseConfigString(ctx, opts.TerragruntConfigPath, config, nil) - if assert.Nil(t, err, "Unexpected error: %v", errors.PrintErrorWithStackTrace(err)) { - assert.Nil(t, terragruntConfig.Terraform) + if assert.NoError(t, err, "Unexpected error: %v", errors.PrintErrorWithStackTrace(err)) { + require.Nil(t, terragruntConfig.Terraform) if assert.NotNil(t, terragruntConfig.RemoteState) { - assert.Equal(t, "s3", terragruntConfig.RemoteState.Backend) - assert.NotEmpty(t, terragruntConfig.RemoteState.Config) - assert.Equal(t, false, terragruntConfig.RemoteState.Config["encrypt"]) - assert.Equal(t, "override", terragruntConfig.RemoteState.Config["bucket"]) - assert.Equal(t, "override", terragruntConfig.RemoteState.Config["key"]) - assert.Equal(t, "override", terragruntConfig.RemoteState.Config["region"]) + require.Equal(t, "s3", terragruntConfig.RemoteState.Backend) + require.NotEmpty(t, terragruntConfig.RemoteState.Config) + require.Equal(t, false, terragruntConfig.RemoteState.Config["encrypt"]) + require.Equal(t, "override", terragruntConfig.RemoteState.Config["bucket"]) + require.Equal(t, "override", terragruntConfig.RemoteState.Config["key"]) + require.Equal(t, "override", terragruntConfig.RemoteState.Config["region"]) } } @@ -703,18 +703,18 @@ func TestParseTerragruntConfigEmptyConfig(t *testing.T) { ctx := NewParsingContext(context.Background(), mockOptionsForTest(t)) cfg, err := ParseConfigString(ctx, DefaultTerragruntConfigPath, config, nil) - assert.NoError(t, err) + require.NoError(t, err) - assert.Nil(t, cfg.Terraform) - assert.Nil(t, cfg.RemoteState) - assert.Nil(t, cfg.Dependencies) - assert.Nil(t, cfg.PreventDestroy) - assert.False(t, cfg.Skip) - assert.Empty(t, cfg.IamRole) - assert.Empty(t, cfg.IamWebIdentityToken) - assert.Nil(t, cfg.RetryMaxAttempts) - assert.Nil(t, cfg.RetrySleepIntervalSec) - assert.Nil(t, cfg.RetryableErrors) + require.Nil(t, cfg.Terraform) + require.Nil(t, cfg.RemoteState) + require.Nil(t, cfg.Dependencies) + require.Nil(t, cfg.PreventDestroy) + require.False(t, cfg.Skip) + require.Empty(t, cfg.IamRole) + require.Empty(t, cfg.IamWebIdentityToken) + require.Nil(t, cfg.RetryMaxAttempts) + require.Nil(t, cfg.RetrySleepIntervalSec) + require.Nil(t, cfg.RetryableErrors) } func TestParseTerragruntConfigEmptyConfigOldConfig(t *testing.T) { @@ -913,22 +913,22 @@ func TestParseTerragruntJsonConfigTerraformWithMultipleExtraArguments(t *testing terragruntConfig, err := ParseConfigString(ctx, DefaultTerragruntJsonConfigPath, config, nil) require.NoError(t, err) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Dependencies) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Dependencies) if assert.NotNil(t, terragruntConfig.Terraform) { - assert.Equal(t, "json_output", terragruntConfig.Terraform.ExtraArgs[0].Name) - assert.Equal(t, &[]string{"-json"}, terragruntConfig.Terraform.ExtraArgs[0].Arguments) - assert.Equal(t, []string{"output"}, terragruntConfig.Terraform.ExtraArgs[0].Commands) - assert.Equal(t, "fmt_diff", terragruntConfig.Terraform.ExtraArgs[1].Name) - assert.Equal(t, &[]string{"-diff=true"}, terragruntConfig.Terraform.ExtraArgs[1].Arguments) - assert.Equal(t, []string{"fmt"}, terragruntConfig.Terraform.ExtraArgs[1].Commands) - assert.Equal(t, "required_tfvars", terragruntConfig.Terraform.ExtraArgs[2].Name) - assert.Equal(t, &[]string{"file1.tfvars", "file2.tfvars"}, terragruntConfig.Terraform.ExtraArgs[2].RequiredVarFiles) - assert.Equal(t, TERRAFORM_COMMANDS_NEED_VARS, terragruntConfig.Terraform.ExtraArgs[2].Commands) - assert.Equal(t, "optional_tfvars", terragruntConfig.Terraform.ExtraArgs[3].Name) - assert.Equal(t, &[]string{"opt1.tfvars", "opt2.tfvars"}, terragruntConfig.Terraform.ExtraArgs[3].OptionalVarFiles) - assert.Equal(t, TERRAFORM_COMMANDS_NEED_VARS, terragruntConfig.Terraform.ExtraArgs[3].Commands) + require.Equal(t, "json_output", terragruntConfig.Terraform.ExtraArgs[0].Name) + require.Equal(t, &[]string{"-json"}, terragruntConfig.Terraform.ExtraArgs[0].Arguments) + require.Equal(t, []string{"output"}, terragruntConfig.Terraform.ExtraArgs[0].Commands) + require.Equal(t, "fmt_diff", terragruntConfig.Terraform.ExtraArgs[1].Name) + require.Equal(t, &[]string{"-diff=true"}, terragruntConfig.Terraform.ExtraArgs[1].Arguments) + require.Equal(t, []string{"fmt"}, terragruntConfig.Terraform.ExtraArgs[1].Commands) + require.Equal(t, "required_tfvars", terragruntConfig.Terraform.ExtraArgs[2].Name) + require.Equal(t, &[]string{"file1.tfvars", "file2.tfvars"}, terragruntConfig.Terraform.ExtraArgs[2].RequiredVarFiles) + require.Equal(t, TERRAFORM_COMMANDS_NEED_VARS, terragruntConfig.Terraform.ExtraArgs[2].Commands) + require.Equal(t, "optional_tfvars", terragruntConfig.Terraform.ExtraArgs[3].Name) + require.Equal(t, &[]string{"opt1.tfvars", "opt2.tfvars"}, terragruntConfig.Terraform.ExtraArgs[3].OptionalVarFiles) + require.Equal(t, TERRAFORM_COMMANDS_NEED_VARS, terragruntConfig.Terraform.ExtraArgs[3].Commands) } } @@ -941,8 +941,8 @@ func TestFindConfigFilesInPathNone(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/none", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.Equal(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.Equal(t, expected, actual) } func TestFindConfigFilesInPathOneConfig(t *testing.T) { @@ -954,8 +954,8 @@ func TestFindConfigFilesInPathOneConfig(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/one-config", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.Equal(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.Equal(t, expected, actual) } func TestFindConfigFilesInPathOneJsonConfig(t *testing.T) { @@ -967,8 +967,8 @@ func TestFindConfigFilesInPathOneJsonConfig(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/one-json-config", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.Equal(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.Equal(t, expected, actual) } func TestFindConfigFilesInPathMultipleConfigs(t *testing.T) { @@ -984,8 +984,8 @@ func TestFindConfigFilesInPathMultipleConfigs(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/multiple-configs", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.ElementsMatch(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.ElementsMatch(t, expected, actual) } func TestFindConfigFilesInPathMultipleJsonConfigs(t *testing.T) { @@ -1001,8 +1001,8 @@ func TestFindConfigFilesInPathMultipleJsonConfigs(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/multiple-json-configs", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.ElementsMatch(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.ElementsMatch(t, expected, actual) } func TestFindConfigFilesInPathMultipleMixedConfigs(t *testing.T) { @@ -1018,8 +1018,8 @@ func TestFindConfigFilesInPathMultipleMixedConfigs(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/multiple-mixed-configs", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.ElementsMatch(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.ElementsMatch(t, expected, actual) } func TestFindConfigFilesIgnoresTerragruntCache(t *testing.T) { @@ -1033,8 +1033,8 @@ func TestFindConfigFilesIgnoresTerragruntCache(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/ignore-cached-config", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.Equal(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.Equal(t, expected, actual) } func TestFindConfigFilesIgnoresTerraformDataDir(t *testing.T) { @@ -1051,8 +1051,8 @@ func TestFindConfigFilesIgnoresTerraformDataDir(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/ignore-terraform-data-dir", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.ElementsMatch(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.ElementsMatch(t, expected, actual) } func TestFindConfigFilesIgnoresTerraformDataDirEnv(t *testing.T) { @@ -1069,8 +1069,8 @@ func TestFindConfigFilesIgnoresTerraformDataDirEnv(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/ignore-terraform-data-dir", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.ElementsMatch(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.ElementsMatch(t, expected, actual) } func TestFindConfigFilesIgnoresTerraformDataDirEnvPath(t *testing.T) { @@ -1088,8 +1088,8 @@ func TestFindConfigFilesIgnoresTerraformDataDirEnvPath(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/ignore-terraform-data-dir", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.ElementsMatch(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.ElementsMatch(t, expected, actual) } func TestFindConfigFilesIgnoresTerraformDataDirEnvRoot(t *testing.T) { @@ -1111,8 +1111,8 @@ func TestFindConfigFilesIgnoresTerraformDataDirEnvRoot(t *testing.T) { actual, err := FindConfigFilesInPath(workingDir, terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.ElementsMatch(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.ElementsMatch(t, expected, actual) } func TestFindConfigFilesIgnoresDownloadDir(t *testing.T) { @@ -1128,8 +1128,8 @@ func TestFindConfigFilesIgnoresDownloadDir(t *testing.T) { actual, err := FindConfigFilesInPath("../test/fixture-config-files/multiple-configs", terragruntOptions) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.ElementsMatch(t, expected, actual) + require.NoError(t, err, "Unexpected error: %v", err) + require.ElementsMatch(t, expected, actual) } func mockOptionsForTestWithConfigPath(t *testing.T, configPath string) *options.TerragruntOptions { @@ -1157,10 +1157,10 @@ prevent_destroy = true t.Fatal(err) } - assert.Nil(t, terragruntConfig.Terraform) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Dependencies) - assert.Equal(t, true, *terragruntConfig.PreventDestroy) + require.Nil(t, terragruntConfig.Terraform) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Dependencies) + require.True(t, *terragruntConfig.PreventDestroy) } func TestParseTerragruntConfigPreventDestroyFalse(t *testing.T) { @@ -1176,10 +1176,10 @@ prevent_destroy = false t.Fatal(err) } - assert.Nil(t, terragruntConfig.Terraform) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Dependencies) - assert.Equal(t, false, *terragruntConfig.PreventDestroy) + require.Nil(t, terragruntConfig.Terraform) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Dependencies) + require.False(t, *terragruntConfig.PreventDestroy) } func TestParseTerragruntConfigSkipTrue(t *testing.T) { @@ -1195,10 +1195,10 @@ skip = true t.Fatal(err) } - assert.Nil(t, terragruntConfig.Terraform) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Dependencies) - assert.Equal(t, true, terragruntConfig.Skip) + require.Nil(t, terragruntConfig.Terraform) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Dependencies) + require.True(t, terragruntConfig.Skip) } func TestParseTerragruntConfigSkipFalse(t *testing.T) { @@ -1214,10 +1214,10 @@ skip = false t.Fatal(err) } - assert.Nil(t, terragruntConfig.Terraform) - assert.Nil(t, terragruntConfig.RemoteState) - assert.Nil(t, terragruntConfig.Dependencies) - assert.Equal(t, false, terragruntConfig.Skip) + require.Nil(t, terragruntConfig.Terraform) + require.Nil(t, terragruntConfig.RemoteState) + require.Nil(t, terragruntConfig.Dependencies) + require.False(t, terragruntConfig.Skip) } func TestIncludeFunctionsWorkInChildConfig(t *testing.T) { @@ -1312,7 +1312,7 @@ func TestModuleDependenciesMerge(t *testing.T) { } target.Merge(source) - assert.Equal(t, target.Paths, testCase.expected) + require.Equal(t, testCase.expected, target.Paths) }) } } diff --git a/config/cty_helpers.go b/config/cty_helpers.go index 09b26e5e0..e3301aa51 100644 --- a/config/cty_helpers.go +++ b/config/cty_helpers.go @@ -244,8 +244,8 @@ func parseCtyValueToMap(value cty.Value) (map[string]interface{}, error) { // a value field. This struct is used to capture that information so when we parse the JSON back into a Go struct, we // can pull out just the Value field we need. type CtyJsonOutput struct { - Value map[string]interface{} - Type interface{} + Value map[string]interface{} `json:"Value"` + Type interface{} `json:"Type"` } // convertValuesMapToCtyVal takes a map of name - cty.Value pairs and converts to a single cty.Value object. diff --git a/config/dependency.go b/config/dependency.go index fe931c096..76f2caef0 100644 --- a/config/dependency.go +++ b/config/dependency.go @@ -433,7 +433,9 @@ func getTerragruntOutputIfAppliedElseConfiguredDefault(ctx *ParsingContext, depe if !isEmpty && dependencyConfig.shouldMergeMockOutputsWithState(ctx) && dependencyConfig.MockOutputs != nil { mockMergeStrategy := dependencyConfig.getMockOutputsMergeStrategy() - switch mockMergeStrategy { + + // TODO: Make this exhaustive + switch mockMergeStrategy { // nolint:exhaustive case NoMerge: return outputVal, nil case ShallowMerge: diff --git a/config/dependency_test.go b/config/dependency_test.go index 37d4b264d..781602648 100644 --- a/config/dependency_test.go +++ b/config/dependency_test.go @@ -10,7 +10,6 @@ import ( "github.com/gruntwork-io/go-commons/env" "github.com/gruntwork-io/terragrunt/config/hclparse" "github.com/hashicorp/hcl/v2" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/gocty" @@ -35,11 +34,11 @@ dependency "sql" { decoded := terragruntDependency{} require.NoError(t, file.Decode(&decoded, &hcl.EvalContext{})) - assert.Equal(t, len(decoded.Dependencies), 2) - assert.Equal(t, decoded.Dependencies[0].Name, "vpc") - assert.Equal(t, decoded.Dependencies[0].ConfigPath, cty.StringVal("../vpc")) - assert.Equal(t, decoded.Dependencies[1].Name, "sql") - assert.Equal(t, decoded.Dependencies[1].ConfigPath, cty.StringVal("../sql")) + require.Len(t, decoded.Dependencies, 2) + require.Equal(t, "vpc", decoded.Dependencies[0].Name) + require.Equal(t, cty.StringVal("../vpc"), decoded.Dependencies[0].ConfigPath) + require.Equal(t, "sql", decoded.Dependencies[1].Name) + require.Equal(t, cty.StringVal("../sql"), decoded.Dependencies[1].ConfigPath) } func TestDecodeNoDependencyBlock(t *testing.T) { @@ -56,7 +55,7 @@ locals { decoded := terragruntDependency{} require.NoError(t, file.Decode(&decoded, &hcl.EvalContext{})) - assert.Equal(t, len(decoded.Dependencies), 0) + require.Empty(t, decoded.Dependencies) } func TestDecodeDependencyNoLabelIsError(t *testing.T) { @@ -94,10 +93,10 @@ dependency "hitchhiker" { decoded := terragruntDependency{} require.NoError(t, file.Decode(&decoded, &hcl.EvalContext{})) - assert.Equal(t, len(decoded.Dependencies), 1) + require.Len(t, decoded.Dependencies, 1) dependency := decoded.Dependencies[0] - assert.Equal(t, dependency.Name, "hitchhiker") - assert.Equal(t, dependency.ConfigPath, cty.StringVal("../answers")) + require.Equal(t, "hitchhiker", dependency.Name) + require.Equal(t, cty.StringVal("../answers"), dependency.ConfigPath) ctyValueDefault := dependency.MockOutputs require.NotNil(t, ctyValueDefault) @@ -106,11 +105,11 @@ dependency "hitchhiker" { TheAnswer int `cty:"the_answer"` } require.NoError(t, gocty.FromCtyValue(*ctyValueDefault, &actualDefault)) - assert.Equal(t, actualDefault.TheAnswer, 42) + require.Equal(t, 42, actualDefault.TheAnswer) defaultAllowedCommands := dependency.MockOutputsAllowedTerraformCommands require.NotNil(t, defaultAllowedCommands) - assert.Equal(t, *defaultAllowedCommands, []string{"validate", "apply"}) + require.Equal(t, []string{"validate", "apply"}, *defaultAllowedCommands) } func TestParseDependencyBlockMultiple(t *testing.T) { t.Parallel() @@ -125,8 +124,8 @@ func TestParseDependencyBlockMultiple(t *testing.T) { tfConfig, err := ParseConfigFile(ctx, filename, nil) require.NoError(t, err) require.Len(t, tfConfig.TerragruntDependencies, 2) - assert.Equal(t, tfConfig.TerragruntDependencies[0].Name, "dependency_1") - assert.Equal(t, tfConfig.TerragruntDependencies[1].Name, "dependency_2") + require.Equal(t, "dependency_1", tfConfig.TerragruntDependencies[0].Name) + require.Equal(t, "dependency_2", tfConfig.TerragruntDependencies[1].Name) } func TestDisabledDependency(t *testing.T) { @@ -147,5 +146,5 @@ dependency "vpc" { decoded := terragruntDependency{} require.NoError(t, file.Decode(&decoded, &hcl.EvalContext{})) - assert.Equal(t, len(decoded.Dependencies), 2) + require.Len(t, decoded.Dependencies, 2) } diff --git a/config/hclparse/attributes.go b/config/hclparse/attributes.go index ae1e2aeb3..f23fd7572 100644 --- a/config/hclparse/attributes.go +++ b/config/hclparse/attributes.go @@ -25,7 +25,8 @@ func NewAttributes(file *File, hclAttrs hcl.Attributes) Attributes { func (attrs Attributes) ValidateIdentifier() error { for _, attr := range attrs { if err := attr.ValidateIdentifier(); err != nil { - return nil + // TODO: Remove lint suppression + return nil //nolint:nilerr } } diff --git a/config/include.go b/config/include.go index 0ca1552a2..5ea0af57a 100644 --- a/config/include.go +++ b/config/include.go @@ -127,7 +127,8 @@ func handleInclude(ctx *ParsingContext, config *TerragruntConfig, isPartial bool return nil, err } - switch mergeStrategy { + // TODO: Remove lint suppression + switch mergeStrategy { //nolint:exhaustive case NoMerge: ctx.TerragruntOptions.Logger.Debugf("%sIncluded config %s has strategy no merge: not merging config in.", logPrefix, includeConfig.Path) case ShallowMerge: @@ -173,7 +174,8 @@ func handleIncludeForDependency(ctx *ParsingContext, childDecodedDependency terr return nil, err } - switch mergeStrategy { + // TODO: Remove lint suppression + switch mergeStrategy { //nolint:exhaustive case NoMerge: ctx.TerragruntOptions.Logger.Debugf("Included config %s has strategy no merge: not merging config in for dependency.", includeConfig.Path) case ShallowMerge: diff --git a/config/include_test.go b/config/include_test.go index ae56a5ae5..c50a2d076 100644 --- a/config/include_test.go +++ b/config/include_test.go @@ -44,69 +44,69 @@ func TestMergeConfigIntoIncludedConfig(t *testing.T) { &TerragruntConfig{RemoteState: &remote.RemoteState{Backend: "bar"}, Terraform: &TerraformConfig{Source: ptr("foo")}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{TerraformExtraArguments{Name: "childArgs"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{{Name: "childArgs"}}}}, &TerragruntConfig{Terraform: &TerraformConfig{}}, - &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{TerraformExtraArguments{Name: "childArgs"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{{Name: "childArgs"}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{TerraformExtraArguments{Name: "childArgs"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{TerraformExtraArguments{Name: "parentArgs"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{TerraformExtraArguments{Name: "parentArgs"}, TerraformExtraArguments{Name: "childArgs"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{{Name: "childArgs"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{{Name: "parentArgs"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{{Name: "parentArgs"}, {Name: "childArgs"}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{TerraformExtraArguments{Name: "overrideArgs", Arguments: &[]string{"-child"}}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{TerraformExtraArguments{Name: "overrideArgs", Arguments: &[]string{"-parent"}}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{TerraformExtraArguments{Name: "overrideArgs", Arguments: &[]string{"-child"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{{Name: "overrideArgs", Arguments: &[]string{"-child"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{{Name: "overrideArgs", Arguments: &[]string{"-parent"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{ExtraArgs: []TerraformExtraArguments{{Name: "overrideArgs", Arguments: &[]string{"-child"}}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "childHooks"}}}}, &TerragruntConfig{Terraform: nil}, - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "childHooks"}}}}, }, { &TerragruntConfig{Terraform: nil}, - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "parentHooks"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "parentHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "parentHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "parentHooks"}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "childHooks"}}}}, &TerragruntConfig{Terraform: &TerraformConfig{}}, - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "childHooks"}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "childHooks"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "parentHooks"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "parentHooks"}, Hook{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "parentHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "parentHooks"}, {Name: "childHooks"}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "overrideHooks", Commands: []string{"child-apply"}}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "overrideHooks", Commands: []string{"parent-apply"}}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{Hook{Name: "overrideHooks", Commands: []string{"child-apply"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "overrideHooks", Commands: []string{"child-apply"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "overrideHooks", Commands: []string{"parent-apply"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{BeforeHooks: []Hook{{Name: "overrideHooks", Commands: []string{"child-apply"}}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "childHooks"}}}}, &TerragruntConfig{Terraform: &TerraformConfig{}}, - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "childHooks"}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "childHooks"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "parentHooks"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "parentHooks"}, Hook{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "parentHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "parentHooks"}, {Name: "childHooks"}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "overrideHooks", Commands: []string{"child-apply"}}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "overrideHooks", Commands: []string{"parent-apply"}}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "overrideHooks", Commands: []string{"child-apply"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "overrideHooks", Commands: []string{"child-apply"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "overrideHooks", Commands: []string{"parent-apply"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "overrideHooks", Commands: []string{"child-apply"}}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "overrideHooksPlusMore", Commands: []string{"child-apply"}}, Hook{Name: "childHooks"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "overrideHooksPlusMore", Commands: []string{"parent-apply"}}, Hook{Name: "parentHooks"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "overrideHooksPlusMore", Commands: []string{"child-apply"}}, Hook{Name: "parentHooks"}, Hook{Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "overrideHooksPlusMore", Commands: []string{"child-apply"}}, {Name: "childHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "overrideHooksPlusMore", Commands: []string{"parent-apply"}}, {Name: "parentHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "overrideHooksPlusMore", Commands: []string{"child-apply"}}, {Name: "parentHooks"}, {Name: "childHooks"}}}}, }, { - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "overrideWithEmptyHooks"}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "overrideWithEmptyHooks", Commands: []string{"parent-apply"}}}}}, - &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{Hook{Name: "overrideWithEmptyHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "overrideWithEmptyHooks"}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "overrideWithEmptyHooks", Commands: []string{"parent-apply"}}}}}, + &TerragruntConfig{Terraform: &TerraformConfig{AfterHooks: []Hook{{Name: "overrideWithEmptyHooks"}}}}, }, { &TerragruntConfig{}, @@ -152,8 +152,8 @@ func TestMergeConfigIntoIncludedConfig(t *testing.T) { } err := testCase.includedConfig.Merge(testCase.config, mockOptionsForTest(t)) - assert.NoError(t, err) - assert.Equal(t, testCase.expected, testCase.includedConfig) + require.NoError(t, err) + require.Equal(t, testCase.expected, testCase.includedConfig) } } diff --git a/config/locals_test.go b/config/locals_test.go index ef18a9086..a1a311f7c 100644 --- a/config/locals_test.go +++ b/config/locals_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/zclconf/go-cty/cty/gocty" @@ -28,34 +27,34 @@ func TestEvaluateLocalsBlock(t *testing.T) { var actualRegion string require.NoError(t, gocty.FromCtyValue(evaluatedLocals["region"], &actualRegion)) - assert.Equal(t, actualRegion, "us-east-1") + require.Equal(t, "us-east-1", actualRegion) var actualS3Url string require.NoError(t, gocty.FromCtyValue(evaluatedLocals["s3_url"], &actualS3Url)) - assert.Equal(t, actualS3Url, "com.amazonaws.us-east-1.s3") + require.Equal(t, "com.amazonaws.us-east-1.s3", actualS3Url) var actualX float64 require.NoError(t, gocty.FromCtyValue(evaluatedLocals["x"], &actualX)) - assert.Equal(t, actualX, float64(1)) + require.InEpsilon(t, float64(1), actualX, 0.0000001) var actualY float64 require.NoError(t, gocty.FromCtyValue(evaluatedLocals["y"], &actualY)) - assert.Equal(t, actualY, float64(2)) + require.InEpsilon(t, float64(2), actualY, 0.0000001) var actualZ float64 require.NoError(t, gocty.FromCtyValue(evaluatedLocals["z"], &actualZ)) - assert.Equal(t, actualZ, float64(3)) + require.InEpsilon(t, float64(3), actualZ, 0.0000001) var actualFoo struct{ First Foo } require.NoError(t, gocty.FromCtyValue(evaluatedLocals["foo"], &actualFoo)) - assert.Equal(t, actualFoo.First, Foo{ + require.Equal(t, Foo{ Region: "us-east-1", Foo: "bar", - }) + }, actualFoo.First) var actualBar string require.NoError(t, gocty.FromCtyValue(evaluatedLocals["bar"], &actualBar)) - assert.Equal(t, actualBar, "us-east-1") + require.Equal(t, "us-east-1", actualBar) } func TestEvaluateLocalsBlockMultiDeepReference(t *testing.T) { @@ -75,7 +74,7 @@ func TestEvaluateLocalsBlockMultiDeepReference(t *testing.T) { var actualA string require.NoError(t, gocty.FromCtyValue(evaluatedLocals["a"], &actualA)) - assert.Equal(t, actualA, expected) + require.Equal(t, expected, actualA) testCases := []string{ "b", @@ -93,7 +92,7 @@ func TestEvaluateLocalsBlockMultiDeepReference(t *testing.T) { var actual string require.NoError(t, gocty.FromCtyValue(evaluatedLocals[testCase], &actual)) - assert.Equal(t, actual, expected) + require.Equal(t, expected, actual) } } @@ -110,7 +109,7 @@ func TestEvaluateLocalsBlockImpossibleWillFail(t *testing.T) { _, err = evaluateLocalsBlock(ctx, file) require.Error(t, err) - switch errors.Unwrap(err).(type) { + switch errors.Unwrap(err).(type) { //nolint:errorlint case CouldNotEvaluateAllLocalsError: default: t.Fatalf("Did not get expected error: %s", err) diff --git a/config/variable.go b/config/variable.go index 37fa6d588..341242c08 100644 --- a/config/variable.go +++ b/config/variable.go @@ -135,8 +135,8 @@ func generateDefaultValue(variableType string) string { } type ctyJsonValue struct { - Value interface{} - Type interface{} + Value interface{} `json:"Value"` + Type interface{} `json:"Type"` } // readBlockAttribute - hcl block attribute. diff --git a/config/variable_test.go b/config/variable_test.go index 6139a3c16..75632eba8 100644 --- a/config/variable_test.go +++ b/config/variable_test.go @@ -3,7 +3,7 @@ package config import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestScanVariables(t *testing.T) { @@ -12,31 +12,31 @@ func TestScanVariables(t *testing.T) { opts := terragruntOptionsForTest(t, "") inputs, err := ParseVariables(opts, "../test/fixture-inputs") - assert.NoError(t, err) - assert.Len(t, inputs, 11) + require.NoError(t, err) + require.Len(t, inputs, 11) varByName := map[string]*ParsedVariable{} for _, input := range inputs { varByName[input.Name] = input } - assert.Equal(t, "string", varByName["string"].Type) - assert.Equal(t, "\"\"", varByName["string"].DefaultValuePlaceholder) + require.Equal(t, "string", varByName["string"].Type) + require.Equal(t, "\"\"", varByName["string"].DefaultValuePlaceholder) - assert.Equal(t, "bool", varByName["bool"].Type) - assert.Equal(t, "false", varByName["bool"].DefaultValuePlaceholder) + require.Equal(t, "bool", varByName["bool"].Type) + require.Equal(t, "false", varByName["bool"].DefaultValuePlaceholder) - assert.Equal(t, "number", varByName["number"].Type) - assert.Equal(t, "0", varByName["number"].DefaultValuePlaceholder) + require.Equal(t, "number", varByName["number"].Type) + require.Equal(t, "0", varByName["number"].DefaultValuePlaceholder) - assert.Equal(t, "object", varByName["object"].Type) - assert.Equal(t, "{}", varByName["object"].DefaultValuePlaceholder) + require.Equal(t, "object", varByName["object"].Type) + require.Equal(t, "{}", varByName["object"].DefaultValuePlaceholder) - assert.Equal(t, "map", varByName["map_bool"].Type) - assert.Equal(t, "{}", varByName["map_bool"].DefaultValuePlaceholder) + require.Equal(t, "map", varByName["map_bool"].Type) + require.Equal(t, "{}", varByName["map_bool"].DefaultValuePlaceholder) - assert.Equal(t, "list", varByName["list_bool"].Type) - assert.Equal(t, "[]", varByName["list_bool"].DefaultValuePlaceholder) + require.Equal(t, "list", varByName["list_bool"].Type) + require.Equal(t, "[]", varByName["list_bool"].DefaultValuePlaceholder) } func TestScanDefaultVariables(t *testing.T) { @@ -44,38 +44,38 @@ func TestScanDefaultVariables(t *testing.T) { opts := terragruntOptionsForTest(t, "") inputs, err := ParseVariables(opts, "../test/fixture-inputs-defaults") - assert.NoError(t, err) - assert.Len(t, inputs, 11) + require.NoError(t, err) + require.Len(t, inputs, 11) varByName := map[string]*ParsedVariable{} for _, input := range inputs { varByName[input.Name] = input } - assert.Equal(t, "string", varByName["project_name"].Type) - assert.Equal(t, "Project name", varByName["project_name"].Description) - assert.Equal(t, "\"\"", varByName["project_name"].DefaultValuePlaceholder) + require.Equal(t, "string", varByName["project_name"].Type) + require.Equal(t, "Project name", varByName["project_name"].Description) + require.Equal(t, "\"\"", varByName["project_name"].DefaultValuePlaceholder) - assert.Equal(t, "(variable no_type_value_var does not define a type)", varByName["no_type_value_var"].Type) - assert.Equal(t, "(variable no_type_value_var did not define a description)", varByName["no_type_value_var"].Description) - assert.Equal(t, "\"\"", varByName["no_type_value_var"].DefaultValuePlaceholder) + require.Equal(t, "(variable no_type_value_var does not define a type)", varByName["no_type_value_var"].Type) + require.Equal(t, "(variable no_type_value_var did not define a description)", varByName["no_type_value_var"].Description) + require.Equal(t, "\"\"", varByName["no_type_value_var"].DefaultValuePlaceholder) - assert.Equal(t, "number", varByName["number_default"].Type) - assert.Equal(t, "number variable with default", varByName["number_default"].Description) - assert.Equal(t, "42", varByName["number_default"].DefaultValue) - assert.Equal(t, "0", varByName["number_default"].DefaultValuePlaceholder) + require.Equal(t, "number", varByName["number_default"].Type) + require.Equal(t, "number variable with default", varByName["number_default"].Description) + require.Equal(t, "42", varByName["number_default"].DefaultValue) + require.Equal(t, "0", varByName["number_default"].DefaultValuePlaceholder) - assert.Equal(t, "object", varByName["object_var"].Type) - assert.Equal(t, "{\"num\":42,\"str\":\"default\"}", varByName["object_var"].DefaultValue) + require.Equal(t, "object", varByName["object_var"].Type) + require.Equal(t, "{\"num\":42,\"str\":\"default\"}", varByName["object_var"].DefaultValue) - assert.Equal(t, "map", varByName["map_var"].Type) - assert.Equal(t, "{\"key\":\"value42\"}", varByName["map_var"].DefaultValue) + require.Equal(t, "map", varByName["map_var"].Type) + require.Equal(t, "{\"key\":\"value42\"}", varByName["map_var"].DefaultValue) - assert.Equal(t, "bool", varByName["enabled"].Type) - assert.Equal(t, "true", varByName["enabled"].DefaultValue) - assert.Equal(t, "Enable or disable the module", varByName["enabled"].Description) + require.Equal(t, "bool", varByName["enabled"].Type) + require.Equal(t, "true", varByName["enabled"].DefaultValue) + require.Equal(t, "Enable or disable the module", varByName["enabled"].Description) - assert.Equal(t, "string", varByName["vpc"].Type) - assert.Equal(t, "\"default-vpc\"", varByName["vpc"].DefaultValue) - assert.Equal(t, "VPC to be used", varByName["vpc"].Description) + require.Equal(t, "string", varByName["vpc"].Type) + require.Equal(t, "\"default-vpc\"", varByName["vpc"].DefaultValue) + require.Equal(t, "VPC to be used", varByName["vpc"].Description) } diff --git a/configstack/module.go b/configstack/module.go index 16d78ea02..9acef8c56 100644 --- a/configstack/module.go +++ b/configstack/module.go @@ -167,7 +167,8 @@ func (module *TerraformModule) getDependenciesForModule(modulesMap TerraformModu for _, dependencyPath := range module.Config.Dependencies.Paths { dependencyModulePath, err := util.CanonicalPath(dependencyPath, module.Path) if err != nil { - return dependencies, nil + // TODO: Remove lint suppression + return dependencies, nil //nolint:nilerr } if files.FileExists(dependencyModulePath) && !files.IsDir(dependencyModulePath) { diff --git a/configstack/module_test.go b/configstack/module_test.go index 415838b51..e277fd4ff 100644 --- a/configstack/module_test.go +++ b/configstack/module_test.go @@ -3,14 +3,15 @@ package configstack import ( "bytes" "context" + "errors" "fmt" "strings" "testing" - "github.com/gruntwork-io/go-commons/errors" "github.com/gruntwork-io/terragrunt/config" "github.com/gruntwork-io/terragrunt/options" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGraph(t *testing.T) { @@ -47,7 +48,7 @@ digraph { "h" -> "c"; } `) - assert.True(t, strings.Contains(stdout.String(), expected)) + require.True(t, strings.Contains(stdout.String(), expected)) } func TestGraphTrimPrefix(t *testing.T) { @@ -84,7 +85,7 @@ digraph { "alpha/beta/h" -> "c"; } `) - assert.True(t, strings.Contains(stdout.String(), expected)) + require.True(t, strings.Contains(stdout.String(), expected)) } func TestGraphFlagExcluded(t *testing.T) { @@ -121,7 +122,7 @@ digraph { "h" -> "c"; } `) - assert.True(t, strings.Contains(stdout.String(), expected)) + require.True(t, strings.Contains(stdout.String(), expected)) } func TestCheckForCycles(t *testing.T) { @@ -195,10 +196,12 @@ func TestCheckForCycles(t *testing.T) { for _, testCase := range testCases { actual := testCase.modules.CheckForCycles() if testCase.expected == nil { - assert.Nil(t, actual) - } else if assert.NotNil(t, actual, "For modules %v", testCase.modules) { - actualErr := errors.Unwrap(actual).(DependencyCycleError) - assert.Equal(t, []string(testCase.expected), []string(actualErr), "For modules %v", testCase.modules) + require.NoError(t, actual) + } else if assert.Error(t, actual, "For modules %v", testCase.modules) { + var actualErr DependencyCycleError + // actualErr := errors.Unwrap(actual).(DependencyCycleError) + errors.As(actual, &actualErr) + require.Equal(t, []string(testCase.expected), []string(actualErr), "For modules %v", testCase.modules) } } } @@ -207,11 +210,11 @@ func TestRunModulesNoModules(t *testing.T) { t.Parallel() opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) } func TestRunModulesOneModuleSuccess(t *testing.T) { @@ -226,12 +229,12 @@ func TestRunModulesOneModuleSuccess(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) + require.NoError(t, err, "Unexpected error: %v", err) + require.True(t, aRan) } func TestRunModulesOneModuleAssumeAlreadyRan(t *testing.T) { @@ -247,12 +250,12 @@ func TestRunModulesOneModuleAssumeAlreadyRan(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.False(t, aRan) + require.NoError(t, err, "Unexpected error: %v", err) + require.False(t, aRan) } func TestRunModulesReverseOrderOneModuleSuccess(t *testing.T) { @@ -267,12 +270,12 @@ func TestRunModulesReverseOrderOneModuleSuccess(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA} err = modules.RunModulesReverseOrder(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) + require.NoError(t, err, "Unexpected error: %v", err) + require.True(t, aRan) } func TestRunModulesIgnoreOrderOneModuleSuccess(t *testing.T) { @@ -287,12 +290,12 @@ func TestRunModulesIgnoreOrderOneModuleSuccess(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA} err = modules.RunModulesIgnoreOrder(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) + require.NoError(t, err, "Unexpected error: %v", err) + require.True(t, aRan) } func TestRunModulesOneModuleError(t *testing.T) { @@ -308,12 +311,12 @@ func TestRunModulesOneModuleError(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrA) - assert.True(t, aRan) + require.True(t, aRan) } func TestRunModulesReverseOrderOneModuleError(t *testing.T) { @@ -329,12 +332,12 @@ func TestRunModulesReverseOrderOneModuleError(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA} err = modules.RunModulesReverseOrder(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrA) - assert.True(t, aRan) + require.True(t, aRan) } func TestRunModulesIgnoreOrderOneModuleError(t *testing.T) { @@ -350,12 +353,12 @@ func TestRunModulesIgnoreOrderOneModuleError(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA} err = modules.RunModulesIgnoreOrder(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrA) - assert.True(t, aRan) + require.True(t, aRan) } func TestRunModulesMultipleModulesNoDependenciesSuccess(t *testing.T) { @@ -386,15 +389,15 @@ func TestRunModulesMultipleModulesNoDependenciesSuccess(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesMultipleModulesNoDependenciesSuccessNoParallelism(t *testing.T) { @@ -425,15 +428,15 @@ func TestRunModulesMultipleModulesNoDependenciesSuccessNoParallelism(t *testing. } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModules(context.Background(), opts, 1) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesReverseOrderMultipleModulesNoDependenciesSuccess(t *testing.T) { @@ -464,15 +467,15 @@ func TestRunModulesReverseOrderMultipleModulesNoDependenciesSuccess(t *testing.T } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModulesReverseOrder(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesIgnoreOrderMultipleModulesNoDependenciesSuccess(t *testing.T) { @@ -503,15 +506,15 @@ func TestRunModulesIgnoreOrderMultipleModulesNoDependenciesSuccess(t *testing.T) } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModulesIgnoreOrder(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesMultipleModulesNoDependenciesOneFailure(t *testing.T) { @@ -543,15 +546,15 @@ func TestRunModulesMultipleModulesNoDependenciesOneFailure(t *testing.T) { } opts, optsErr := options.NewTerragruntOptionsForTest("") - assert.NoError(t, optsErr) + require.NoError(t, optsErr) modules := TerraformModules{moduleA, moduleB, moduleC} err := modules.RunModules(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrB) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesMultipleModulesNoDependenciesMultipleFailures(t *testing.T) { @@ -585,15 +588,15 @@ func TestRunModulesMultipleModulesNoDependenciesMultipleFailures(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrA, expectedErrB, expectedErrC) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesMultipleModulesWithDependenciesSuccess(t *testing.T) { @@ -624,15 +627,15 @@ func TestRunModulesMultipleModulesWithDependenciesSuccess(t *testing.T) { } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesMultipleModulesWithDependenciesWithAssumeAlreadyRanSuccess(t *testing.T) { @@ -672,16 +675,16 @@ func TestRunModulesMultipleModulesWithDependenciesWithAssumeAlreadyRanSuccess(t } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC, moduleD} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) - assert.True(t, bRan) - assert.False(t, cRan) - assert.True(t, dRan) + require.True(t, aRan) + require.True(t, bRan) + require.False(t, cRan) + require.True(t, dRan) } func TestRunModulesReverseOrderMultipleModulesWithDependenciesSuccess(t *testing.T) { @@ -712,15 +715,15 @@ func TestRunModulesReverseOrderMultipleModulesWithDependenciesSuccess(t *testing } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModulesReverseOrder(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesIgnoreOrderMultipleModulesWithDependenciesSuccess(t *testing.T) { @@ -751,15 +754,15 @@ func TestRunModulesIgnoreOrderMultipleModulesWithDependenciesSuccess(t *testing. } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModulesIgnoreOrder(context.Background(), opts, options.DefaultParallelism) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesMultipleModulesWithDependenciesOneFailure(t *testing.T) { @@ -793,15 +796,15 @@ func TestRunModulesMultipleModulesWithDependenciesOneFailure(t *testing.T) { expectedErrC := ProcessingModuleDependencyError{moduleC, moduleB, expectedErrB} opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrB, expectedErrC) - assert.True(t, aRan) - assert.True(t, bRan) - assert.False(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.False(t, cRan) } func TestRunModulesMultipleModulesWithDependenciesOneFailureIgnoreDependencyErrors(t *testing.T) { @@ -839,15 +842,15 @@ func TestRunModulesMultipleModulesWithDependenciesOneFailureIgnoreDependencyErro } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrB) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesReverseOrderMultipleModulesWithDependenciesOneFailure(t *testing.T) { @@ -881,15 +884,15 @@ func TestRunModulesReverseOrderMultipleModulesWithDependenciesOneFailure(t *test expectedErrA := ProcessingModuleDependencyError{moduleA, moduleB, expectedErrB} opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModulesReverseOrder(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrB, expectedErrA) - assert.False(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.False(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesIgnoreOrderMultipleModulesWithDependenciesOneFailure(t *testing.T) { @@ -921,15 +924,15 @@ func TestRunModulesIgnoreOrderMultipleModulesWithDependenciesOneFailure(t *testi } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModulesIgnoreOrder(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrB) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesMultipleModulesWithDependenciesMultipleFailures(t *testing.T) { @@ -964,15 +967,15 @@ func TestRunModulesMultipleModulesWithDependenciesMultipleFailures(t *testing.T) expectedErrC := ProcessingModuleDependencyError{moduleC, moduleB, expectedErrB} opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrA, expectedErrB, expectedErrC) - assert.True(t, aRan) - assert.False(t, bRan) - assert.False(t, cRan) + require.True(t, aRan) + require.False(t, bRan) + require.False(t, cRan) } func TestRunModulesIgnoreOrderMultipleModulesWithDependenciesMultipleFailures(t *testing.T) { @@ -1004,15 +1007,15 @@ func TestRunModulesIgnoreOrderMultipleModulesWithDependenciesMultipleFailures(t } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC} err = modules.RunModulesIgnoreOrder(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrA) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) } func TestRunModulesMultipleModulesWithDependenciesLargeGraphAllSuccess(t *testing.T) { @@ -1067,18 +1070,18 @@ func TestRunModulesMultipleModulesWithDependenciesLargeGraphAllSuccess(t *testin } opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC, moduleD, moduleE, moduleF} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) - assert.NoError(t, err) - - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) - assert.True(t, dRan) - assert.True(t, eRan) - assert.True(t, fRan) + require.NoError(t, err) + + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) + require.True(t, dRan) + require.True(t, eRan) + require.True(t, fRan) } func TestRunModulesMultipleModulesWithDependenciesLargeGraphPartialFailure(t *testing.T) { @@ -1146,19 +1149,19 @@ func TestRunModulesMultipleModulesWithDependenciesLargeGraphPartialFailure(t *te expectedErrF := ProcessingModuleDependencyError{moduleF, moduleD, expectedErrD} opts, err := options.NewTerragruntOptionsForTest("") - assert.NoError(t, err) + require.NoError(t, err) modules := TerraformModules{moduleA, moduleB, moduleC, moduleD, moduleE, moduleF, moduleG} err = modules.RunModules(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrC, expectedErrD, expectedErrF) - assert.True(t, aRan) - assert.True(t, bRan) - assert.True(t, cRan) - assert.False(t, dRan) - assert.False(t, eRan) - assert.False(t, fRan) - assert.True(t, gRan) + require.True(t, aRan) + require.True(t, bRan) + require.True(t, cRan) + require.False(t, dRan) + require.False(t, eRan) + require.False(t, fRan) + require.True(t, gRan) } func TestRunModulesReverseOrderMultipleModulesWithDependenciesLargeGraphPartialFailure(t *testing.T) { @@ -1217,16 +1220,16 @@ func TestRunModulesReverseOrderMultipleModulesWithDependenciesLargeGraphPartialF expectedErrA := ProcessingModuleDependencyError{moduleA, moduleB, expectedErrB} opts, optsErr := options.NewTerragruntOptionsForTest("") - assert.NoError(t, optsErr) + require.NoError(t, optsErr) modules := TerraformModules{moduleA, moduleB, moduleC, moduleD, moduleE, moduleF} err := modules.RunModulesReverseOrder(context.Background(), opts, options.DefaultParallelism) assertMultiErrorContains(t, err, expectedErrC, expectedErrB, expectedErrA) - assert.False(t, aRan) - assert.False(t, bRan) - assert.True(t, cRan) - assert.True(t, dRan) - assert.True(t, eRan) - assert.True(t, fRan) + require.False(t, aRan) + require.False(t, bRan) + require.True(t, cRan) + require.True(t, dRan) + require.True(t, eRan) + require.True(t, fRan) } diff --git a/configstack/running_module.go b/configstack/running_module.go index 5559250be..6d9ebe9c7 100644 --- a/configstack/running_module.go +++ b/configstack/running_module.go @@ -236,7 +236,9 @@ func (modules runningModules) crossLinkDependencies(dependencyOrder DependencyOr if !hasDependency { return modules, errors.WithStackTrace(DependencyNotFoundWhileCrossLinkingError{module, dependency}) } - switch dependencyOrder { + + // TODO: Remove lint suppression + switch dependencyOrder { //nolint:exhaustive case NormalOrder: module.Dependencies[runningDependency.Module.Path] = runningDependency runningDependency.NotifyWhenDone = append(runningDependency.NotifyWhenDone, module) diff --git a/configstack/running_module_test.go b/configstack/running_module_test.go index f9429b5af..b9ac4d100 100644 --- a/configstack/running_module_test.go +++ b/configstack/running_module_test.go @@ -487,7 +487,7 @@ func TestToRunningModulesMultipleModulesWithAndWithoutDependenciesIgnoreOrder(t func testToRunningModules(t *testing.T, modules TerraformModules, order DependencyOrder, expected runningModules) { actual, err := modules.toRunningModules(order) - if assert.Nil(t, err, "For modules %v and order %v", modules, order) { + if assert.NoError(t, err, "For modules %v and order %v", modules, order) { assertRunningModuleMapsEqual(t, expected, actual, true, "For modules %v and order %v", modules, order) } } diff --git a/configstack/stack.go b/configstack/stack.go index ab2a81e08..10533b026 100644 --- a/configstack/stack.go +++ b/configstack/stack.go @@ -507,7 +507,9 @@ func (stack *Stack) resolveTerraformModule(ctx context.Context, terragruntConfig // We only partially parse the config, only using the pieces that we need in this section. This config will be fully // parsed at a later stage right before the action is run. This is to delay interpolation of functions until right // before we call out to terraform. - terragruntConfig, err := config.PartialParseConfigFile( + + // TODO: Remove lint suppression + terragruntConfig, err := config.PartialParseConfigFile( //nolint:contextcheck parseCtx, terragruntConfigPath, includeConfig, diff --git a/configstack/stack_test.go b/configstack/stack_test.go index 29a2a19ca..9f80cb535 100644 --- a/configstack/stack_test.go +++ b/configstack/stack_test.go @@ -2,6 +2,7 @@ package configstack import ( "context" + goErrors "errors" "os" "path/filepath" "reflect" @@ -14,7 +15,6 @@ import ( "github.com/gruntwork-io/terragrunt/options" "github.com/gruntwork-io/terragrunt/terraform" "github.com/gruntwork-io/terragrunt/util" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -54,7 +54,7 @@ func TestFindStackInSubfolders(t *testing.T) { for _, filePath := range filePaths { filePathFound := util.ListContainsElement(modulePaths, filePath) - assert.True(t, filePathFound, "The filePath %s was not found by Terragrunt.\n", filePath) + require.True(t, filePathFound, "The filePath %s was not found by Terragrunt.\n", filePath) } } @@ -65,7 +65,7 @@ func TestGetModuleRunGraphApplyOrder(t *testing.T) { runGraph, err := stack.getModuleRunGraph(terraform.CommandNameApply) require.NoError(t, err) - assert.Equal( + require.Equal( t, []TerraformModules{ { @@ -90,7 +90,7 @@ func TestGetModuleRunGraphDestroyOrder(t *testing.T) { runGraph, err := stack.getModuleRunGraph(terraform.CommandNameDestroy) require.NoError(t, err) - assert.Equal( + require.Equal( t, []TerraformModules{ { @@ -198,7 +198,7 @@ func TestResolveTerraformModulesNoPaths(t *testing.T) { expected := TerraformModules{} stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -221,7 +221,7 @@ func TestResolveTerraformModulesOneModuleNoDependencies(t *testing.T) { stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -244,7 +244,7 @@ func TestResolveTerraformModulesOneJsonModuleNoDependencies(t *testing.T) { stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -270,7 +270,7 @@ func TestResolveTerraformModulesOneModuleWithIncludesNoDependencies(t *testing.T stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -292,11 +292,11 @@ func TestResolveTerraformModulesReadConfigFromParentConfig(t *testing.T) { for name, configPath := range localsConfigPaths { opts, err := options.NewTerragruntOptionsWithConfigPath(configPath) - assert.NoError(t, err) + require.NoError(t, err) ctx := config.NewParsingContext(context.Background(), opts) cfg, err := config.PartialParseConfigFile(ctx, configPath, nil) - assert.NoError(t, err) + require.NoError(t, err) localsConfigs[name] = map[string]interface{}{ "dependencies": interface{}(nil), @@ -356,7 +356,7 @@ func TestResolveTerraformModulesReadConfigFromParentConfig(t *testing.T) { stack := NewStack(mockOptions, WithChildTerragruntConfig(childTerragruntConfig)) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -382,7 +382,7 @@ func TestResolveTerraformModulesOneJsonModuleWithIncludesNoDependencies(t *testi stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -408,7 +408,7 @@ func TestResolveTerraformModulesOneHclModuleWithIncludesNoDependencies(t *testin stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -443,7 +443,7 @@ func TestResolveTerraformModulesTwoModulesWithDependencies(t *testing.T) { stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -478,7 +478,7 @@ func TestResolveTerraformModulesJsonModulesWithHclDependencies(t *testing.T) { stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -513,7 +513,7 @@ func TestResolveTerraformModulesHclModulesWithJsonDependencies(t *testing.T) { stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -550,7 +550,7 @@ func TestResolveTerraformModulesTwoModulesWithDependenciesExcludedDirsWithDepend moduleA.FlagExcluded = true expected := TerraformModules{moduleA, moduleC} - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -599,7 +599,7 @@ func TestResolveTerraformModulesTwoModulesWithDependenciesExcludedDirsWithDepend moduleA.FlagExcluded = true expected := TerraformModules{moduleA, moduleC, moduleAbba} - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -642,7 +642,7 @@ func TestResolveTerraformModulesTwoModulesWithDependenciesExcludedDirsWithDepend moduleAbba.FlagExcluded = true expected := TerraformModules{moduleA, moduleC, moduleAbba} - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -677,7 +677,7 @@ func TestResolveTerraformModulesTwoModulesWithDependenciesExcludedDirsWithNoDepe moduleC.FlagExcluded = true expected := TerraformModules{moduleA, moduleC} - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -719,7 +719,7 @@ func TestResolveTerraformModulesTwoModulesWithDependenciesIncludedDirsWithDepend moduleA.FlagExcluded = false expected := TerraformModules{moduleA, moduleC} - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -762,7 +762,7 @@ func TestResolveTerraformModulesTwoModulesWithDependenciesIncludedDirsWithNoDepe moduleC.FlagExcluded = true expected := TerraformModules{moduleA, moduleC} - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -812,7 +812,7 @@ func TestResolveTerraformModulesTwoModulesWithDependenciesIncludedDirsWithDepend moduleF.FlagExcluded = true expected := TerraformModules{moduleA, moduleC, moduleF} - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -872,7 +872,7 @@ func TestResolveTerraformModulesMultipleModulesWithDependencies(t *testing.T) { stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -932,7 +932,7 @@ func TestResolveTerraformModulesMultipleModulesWithMixedDependencies(t *testing. stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -984,7 +984,7 @@ func TestResolveTerraformModulesMultipleModulesWithDependenciesWithIncludes(t *t stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -1019,7 +1019,7 @@ func TestResolveTerraformModulesMultipleModulesWithExternalDependencies(t *testi stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } @@ -1091,11 +1091,13 @@ func TestResolveTerraformModulesInvalidPaths(t *testing.T) { _, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) require.Error(t, actualErr) - underlying, ok := errors.Unwrap(actualErr).(ProcessingModuleError) + var processingModuleError ProcessingModuleError + // underlying, ok := errors.Unwrap(actualErr).(ProcessingModuleError) + ok := goErrors.As(actualErr, &processingModuleError) require.True(t, ok) - unwrapped := errors.Unwrap(underlying.UnderlyingError) - assert.True(t, os.IsNotExist(unwrapped), "Expected a file not exists error but got %v", underlying.UnderlyingError) + unwrapped := errors.Unwrap(processingModuleError.UnderlyingError) + require.True(t, os.IsNotExist(unwrapped), "Expected a file not exists error but got %v", processingModuleError.UnderlyingError) } func TestResolveTerraformModuleNoTerraformConfig(t *testing.T) { @@ -1106,7 +1108,7 @@ func TestResolveTerraformModuleNoTerraformConfig(t *testing.T) { stack := NewStack(mockOptions) actualModules, actualErr := stack.ResolveTerraformModules(context.Background(), configPaths) - assert.Nil(t, actualErr, "Unexpected error: %v", actualErr) + require.NoError(t, actualErr, "Unexpected error: %v", actualErr) assertModuleListsEqual(t, expected, actualModules) } diff --git a/configstack/test_helpers.go b/configstack/test_helpers.go index b7354ec68..3a32e62a1 100644 --- a/configstack/test_helpers.go +++ b/configstack/test_helpers.go @@ -2,6 +2,7 @@ package configstack import ( "context" + goErrors "errors" "sort" "testing" @@ -125,10 +126,13 @@ func assertRunningModulesEqual(t *testing.T, expected *runningModule, actual *ru // configstack.UnrecognizedDependencyError" panic. Therefore, we have to compare that error more manually. func assertErrorsEqual(t *testing.T, expected error, actual error, messageAndArgs ...interface{}) { actual = errors.Unwrap(actual) - if expectedUnrecognized, isUnrecognizedDependencyError := expected.(UnrecognizedDependencyError); isUnrecognizedDependencyError { - actualUnrecognized, isUnrecognizedDependencyError := actual.(UnrecognizedDependencyError) - if assert.True(t, isUnrecognizedDependencyError, messageAndArgs...) { - assert.Equal(t, expectedUnrecognized, actualUnrecognized, messageAndArgs...) + + var unrecognizedDependencyError UnrecognizedDependencyError + if ok := goErrors.As(expected, &unrecognizedDependencyError); ok { + var actualUnrecognized UnrecognizedDependencyError + ok = goErrors.As(actual, &actualUnrecognized) + if assert.True(t, ok, messageAndArgs...) { + assert.Equal(t, unrecognizedDependencyError, actualUnrecognized, messageAndArgs...) } } else { assert.True(t, errors.IsError(actual, expected), messageAndArgs...) @@ -180,13 +184,14 @@ func optionsWithMockTerragruntCommand(t *testing.T, terragruntConfigPath string, func assertMultiErrorContains(t *testing.T, actualError error, expectedErrors ...error) { actualError = errors.Unwrap(actualError) - multiError, isMultiError := actualError.(*multierror.Error) + var multiError *multierror.Error + isMultiError := goErrors.As(actualError, &multiError) if assert.True(t, isMultiError, "Expected a MutliError, but got: %v", actualError) { assert.Equal(t, len(expectedErrors), len(multiError.Errors)) for _, expectedErr := range expectedErrors { found := false for _, actualErr := range multiError.Errors { - if expectedErr == actualErr { + if goErrors.Is(expectedErr, actualErr) { found = true break } diff --git a/dynamodb/dynamo_lock_table.go b/dynamodb/dynamo_lock_table.go index 7151558f9..76e8948ea 100644 --- a/dynamodb/dynamo_lock_table.go +++ b/dynamodb/dynamo_lock_table.go @@ -1,6 +1,7 @@ package dynamodb import ( + goErrors "errors" "fmt" "net/http" "time" @@ -63,7 +64,8 @@ func CreateLockTableIfNecessary(tableName string, tags map[string]string, client func LockTableExistsAndIsActive(tableName string, client *dynamodb.DynamoDB) (bool, error) { output, err := client.DescribeTable(&dynamodb.DescribeTableInput{TableName: aws.String(tableName)}) if err != nil { - if awsErr, isAwsErr := err.(awserr.Error); isAwsErr && awsErr.Code() == "ResourceNotFoundException" { + var awsErr awserr.Error + if ok := goErrors.As(err, &awsErr); ok && awsErr.Code() == "ResourceNotFoundException" { return false, nil } else { return false, errors.WithStackTrace(err) @@ -192,8 +194,9 @@ func (retryer DeleteTableRetryer) ShouldRetry(req *request.Request) bool { // Return true if the given error is the error message returned by AWS when the resource already exists and is being // updated by someone else func isTableAlreadyBeingCreatedOrUpdatedError(err error) bool { - awsErr, isAwsErr := err.(awserr.Error) - return isAwsErr && awsErr.Code() == "ResourceInUseException" + var awsErr awserr.Error + ok := goErrors.As(err, &awsErr) + return ok && awsErr.Code() == "ResourceInUseException" } // Wait for the given DynamoDB table to be in the "active" state. If it's not in "active" state, sleep for the diff --git a/dynamodb/dynamo_lock_table_test.go b/dynamodb/dynamo_lock_table_test.go index 8204c0f02..1045ce6c4 100644 --- a/dynamodb/dynamo_lock_table_test.go +++ b/dynamodb/dynamo_lock_table_test.go @@ -11,6 +11,7 @@ import ( "github.com/gruntwork-io/go-commons/errors" "github.com/gruntwork-io/terragrunt/options" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateLockTableIfNecessaryTableDoesntAlreadyExist(t *testing.T) { @@ -45,7 +46,7 @@ func TestCreateLockTableConcurrency(t *testing.T) { go func() { defer waitGroup.Done() err := CreateLockTableIfNecessary(tableName, nil, client, mockOptions) - assert.Nil(t, err, "Unexpected error: %v", err) + assert.NoError(t, err, "Unexpected error: %v", err) }() } @@ -83,7 +84,7 @@ func TestCreateLockTableIfNecessaryTableAlreadyExists(t *testing.T) { // Try to create the table the second time and make sure you get no errors err = CreateLockTableIfNecessary(tableName, nil, client, mockOptions) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) }) } @@ -105,7 +106,7 @@ func TestTableTagging(t *testing.T) { // Try to create the table the second time and make sure you get no errors err = CreateLockTableIfNecessary(tableName, nil, client, mockOptions) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) }) } diff --git a/dynamodb/dynamo_lock_test_utils.go b/dynamodb/dynamo_lock_test_utils.go index feed80f87..7af6f55ae 100644 --- a/dynamodb/dynamo_lock_test_utils.go +++ b/dynamodb/dynamo_lock_test_utils.go @@ -9,7 +9,7 @@ import ( "github.com/gruntwork-io/terragrunt/aws_helper" "github.com/gruntwork-io/terragrunt/options" "github.com/gruntwork-io/terragrunt/util" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // For simplicity, do all testing in the us-east-1 region @@ -39,7 +39,7 @@ func uniqueTableNameForTest() string { func cleanupTableForTest(t *testing.T, tableName string, client *dynamodb.DynamoDB) { err := DeleteTable(tableName, client) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) } func assertCanWriteToTable(t *testing.T, tableName string, client *dynamodb.DynamoDB) { @@ -50,7 +50,7 @@ func assertCanWriteToTable(t *testing.T, tableName string, client *dynamodb.Dyna Item: item, }) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) } func withLockTable(t *testing.T, action func(tableName string, client *dynamodb.DynamoDB)) { @@ -67,7 +67,7 @@ func withLockTableTagged(t *testing.T, tags map[string]string, action func(table } err = CreateLockTableIfNecessary(tableName, tags, client, mockOptions) - assert.Nil(t, err, "Unexpected error: %v", err) + require.NoError(t, err, "Unexpected error: %v", err) defer cleanupTableForTest(t, tableName, client) action(tableName, client) @@ -75,6 +75,6 @@ func withLockTableTagged(t *testing.T, tags map[string]string, action func(table func createKeyFromItemId(itemId string) map[string]*dynamodb.AttributeValue { return map[string]*dynamodb.AttributeValue{ - ATTR_LOCK_ID: &dynamodb.AttributeValue{S: aws.String(itemId)}, + ATTR_LOCK_ID: {S: aws.String(itemId)}, } } diff --git a/engine/engine.go b/engine/engine.go index f0281d550..3552000af 100644 --- a/engine/engine.go +++ b/engine/engine.go @@ -465,19 +465,19 @@ func invoke(ctx context.Context, runOptions *ExecutionOptions, client *proto.Eng if runResp == nil { break } - if runResp.Stdout != "" { - _, err := stdout.Write([]byte(runResp.Stdout)) + if runResp.GetStdout() != "" { + _, err := stdout.Write([]byte(runResp.GetStdout())) if err != nil { return nil, errors.WithStackTrace(err) } } - if runResp.Stderr != "" { - _, err := stderr.Write([]byte(runResp.Stderr)) + if runResp.GetStderr() != "" { + _, err := stderr.Write([]byte(runResp.GetStderr())) if err != nil { return nil, errors.WithStackTrace(err) } } - resultCode = int(runResp.ResultCode) + resultCode = int(runResp.GetResultCode()) } terragruntOptions.Logger.Debugf("Engine execution done in %v", terragruntOptions.WorkingDir) @@ -526,8 +526,8 @@ func initialize(ctx context.Context, runOptions *ExecutionOptions, client *proto return nil, nil } return &outputLine{ - Stderr: output.Stderr, - Stdout: output.Stdout, + Stderr: output.GetStderr(), + Stdout: output.GetStdout(), }, nil }) } @@ -559,8 +559,8 @@ func shutdown(ctx context.Context, runOptions *ExecutionOptions, terragruntEngin return nil, nil } return &outputLine{ - Stdout: output.Stdout, - Stderr: output.Stderr, + Stdout: output.GetStdout(), + Stderr: output.GetStderr(), }, nil }) @@ -597,7 +597,8 @@ func readEngineOutput(runOptions *ExecutionOptions, output outputFn) error { } } } - return nil + // TODO: Why does this lint need to be ignored? + return nil //nolint:nilerr } // convert metadata map to protobuf map @@ -609,7 +610,7 @@ func convertMetaToProtobuf(meta map[string]interface{}) (map[string]*anypb.Any, for key, value := range meta { jsonData, err := json.Marshal(value) if err != nil { - return nil, fmt.Errorf("error marshaling value to JSON: %v", err) + return nil, fmt.Errorf("error marshaling value to JSON: %w", err) } jsonStructValue, err := structpb.NewValue(string(jsonData)) if err != nil { diff --git a/engine/engine_test.go b/engine/engine_test.go index 7f08e8a26..d05e630a7 100644 --- a/engine/engine_test.go +++ b/engine/engine_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIsEngineEnabled(t *testing.T) { @@ -27,9 +28,9 @@ func TestConvertMetaToProtobuf(t *testing.T) { } protoMeta, err := convertMetaToProtobuf(meta) - assert.NoError(t, err) - assert.NotNil(t, protoMeta) - assert.Equal(t, 2, len(protoMeta)) + require.NoError(t, err) + require.NotNil(t, protoMeta) + require.Len(t, protoMeta, 2) } func TestReadEngineOutput(t *testing.T) { diff --git a/internal/cache/cache_test.go b/internal/cache/cache_test.go index 542fab1b4..d3a51b035 100644 --- a/internal/cache/cache_test.go +++ b/internal/cache/cache_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCacheCreation(t *testing.T) { @@ -13,10 +13,10 @@ func TestCacheCreation(t *testing.T) { cache := NewCache[string]("test") - assert.NotNil(t, cache.Mutex) - assert.NotNil(t, cache.Cache) + require.NotNil(t, cache.Mutex) + require.NotNil(t, cache.Cache) - assert.Equal(t, 0, len(cache.Cache)) + require.Empty(t, cache.Cache) } func TestStringCacheOperation(t *testing.T) { @@ -27,15 +27,15 @@ func TestStringCacheOperation(t *testing.T) { value, found := cache.Get(ctx, "potato") - assert.False(t, found) - assert.Empty(t, value) + require.False(t, found) + require.Empty(t, value) cache.Put(ctx, "potato", "carrot") value, found = cache.Get(ctx, "potato") - assert.True(t, found) - assert.NotEmpty(t, value) - assert.Equal(t, "carrot", value) + require.True(t, found) + require.NotEmpty(t, value) + require.Equal(t, "carrot", value) } func TestExpiringCacheCreation(t *testing.T) { @@ -43,10 +43,10 @@ func TestExpiringCacheCreation(t *testing.T) { cache := NewExpiringCache[string]("test") - assert.NotNil(t, cache.Mutex) - assert.NotNil(t, cache.Cache) + require.NotNil(t, cache.Mutex) + require.NotNil(t, cache.Cache) - assert.Equal(t, 0, len(cache.Cache)) + require.Empty(t, cache.Cache) } func TestExpiringCacheOperation(t *testing.T) { @@ -57,15 +57,15 @@ func TestExpiringCacheOperation(t *testing.T) { value, found := cache.Get(ctx, "potato") - assert.False(t, found) - assert.Empty(t, value) + require.False(t, found) + require.Empty(t, value) cache.Put(ctx, "potato", "carrot", time.Now().Add(1*time.Second)) value, found = cache.Get(ctx, "potato") - assert.True(t, found) - assert.NotEmpty(t, value) - assert.Equal(t, "carrot", value) + require.True(t, found) + require.NotEmpty(t, value) + require.Equal(t, "carrot", value) } func TestExpiringCacheExpiration(t *testing.T) { @@ -77,7 +77,7 @@ func TestExpiringCacheExpiration(t *testing.T) { cache.Put(ctx, "potato", "carrot", time.Now().Add(-1*time.Second)) value, found := cache.Get(ctx, "potato") - assert.False(t, found) - assert.NotEmpty(t, value) - assert.Equal(t, "carrot", value) + require.False(t, found) + require.NotEmpty(t, value) + require.Equal(t, "carrot", value) } diff --git a/internal/view/diagnostic/servity.go b/internal/view/diagnostic/servity.go index 089618f08..a17eac03e 100644 --- a/internal/view/diagnostic/servity.go +++ b/internal/view/diagnostic/servity.go @@ -16,7 +16,8 @@ const ( type DiagnosticSeverity hcl.DiagnosticSeverity func (severity DiagnosticSeverity) String() string { - switch hcl.DiagnosticSeverity(severity) { + // TODO: Remove lint suppression + switch hcl.DiagnosticSeverity(severity) { //nolint:exhaustive case hcl.DiagError: return DiagnosticSeverityError case hcl.DiagWarning: diff --git a/internal/view/human_render.go b/internal/view/human_render.go index 146417bb0..21a24d524 100644 --- a/internal/view/human_render.go +++ b/internal/view/human_render.go @@ -84,7 +84,8 @@ func (render *HumanRender) Diagnostic(diag *diagnostic.Diagnostic) (string, erro var leftRuleLine, leftRuleStart, leftRuleEnd string var leftRuleWidth int // in visual character cells - switch hcl.DiagnosticSeverity(diag.Severity) { + // TODO: Remove lint suppression + switch hcl.DiagnosticSeverity(diag.Severity) { //nolint:exhaustive case hcl.DiagError: buf.WriteString(render.colorize.Color("[bold][red]Error: [reset]")) leftRuleLine = render.colorize.Color("[red]│[reset] ") diff --git a/main.go b/main.go index 7dee04505..4da3ae318 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + goErrors "errors" "os" "strings" @@ -43,9 +44,11 @@ func checkForErrorsAndExit(err error) { } func printErrorWithStackTrace(err error) string { - if err, ok := err.(*multierror.Error); ok { + var multierror *multierror.Error + // if err, ok := err.(*multierror.Error); ok { + if goErrors.As(err, &multierror) { var errsStr []string - for _, err := range err.Errors { + for _, err := range multierror.Errors { errsStr = append(errsStr, errors.PrintErrorWithStackTrace(err)) } return strings.Join(errsStr, "\n") diff --git a/pkg/cli/errors.go b/pkg/cli/errors.go index a57d1cab2..01e1642c0 100644 --- a/pkg/cli/errors.go +++ b/pkg/cli/errors.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "fmt" "github.com/urfave/cli/v2" @@ -73,7 +74,8 @@ func handleExitCoder(err error, osExiter func(code int)) error { return nil } - if exitErr, ok := err.(cli.ExitCoder); ok { + var exitErr cli.ExitCoder + if ok := errors.As(err, &exitErr); ok { if err.Error() != "" { _, _ = fmt.Fprintln(cli.ErrWriter, err) } diff --git a/remote/remote_state.go b/remote/remote_state.go index f3ffb7007..2d549234f 100644 --- a/remote/remote_state.go +++ b/remote/remote_state.go @@ -18,11 +18,11 @@ const initializedRemoteStateCacheName = "initializedRemoteStateCache" // Configuration for Terraform remote state // NOTE: If any attributes are added here, be sure to add it to remoteStateAsCty in config/config_as_cty.go type RemoteState struct { - Backend string - DisableInit bool - DisableDependencyOptimization bool - Generate *RemoteStateGenerate - Config map[string]interface{} + Backend string `mapstructure:"backend" json:"Backend"` + DisableInit bool `mapstructure:"disable_init" json:"DisableInit"` + DisableDependencyOptimization bool `mapstructure:"disable_dependency_optimization" json:"DisableDependencyOptimization"` + Generate *RemoteStateGenerate `mapstructure:"generate" json:"Generate"` + Config map[string]interface{} `mapstructure:"config" json:"Config"` } // map to store mutexes for each state bucket action diff --git a/remote/remote_state_gcs.go b/remote/remote_state_gcs.go index a3cec2c15..8dba025a6 100644 --- a/remote/remote_state_gcs.go +++ b/remote/remote_state_gcs.go @@ -3,6 +3,7 @@ package remote import ( "context" "encoding/json" + goErrors "errors" "fmt" "os" "reflect" @@ -193,7 +194,8 @@ func (gcsInitializer GCSInitializer) Initialize(ctx context.Context, remoteState return nil } - gcsClient, err := CreateGCSClient(gcsConfig) + // TODO: Remove lint suppression + gcsClient, err := CreateGCSClient(gcsConfig) //nolint:contextcheck if err != nil { return err } @@ -206,7 +208,8 @@ func (gcsInitializer GCSInitializer) Initialize(ctx context.Context, remoteState } // If bucket is specified and skip_bucket_versioning is false then warn user if versioning is disabled on bucket if !gcsConfigExtended.SkipBucketVersioning && gcsConfig.Bucket != "" { - if err := checkIfGCSVersioningEnabled(gcsClient, &gcsConfig, terragruntOptions); err != nil { + // TODO: Remove lint suppression + if err := checkIfGCSVersioningEnabled(gcsClient, &gcsConfig, terragruntOptions); err != nil { //nolint:contextcheck return err } } @@ -273,7 +276,8 @@ func validateGCSConfig(extendedConfig *ExtendedRemoteStateConfigGCS) error { // If the bucket specified in the given config doesn't already exist, prompt the user to create it, and if the user // confirms, create the bucket and enable versioning for it. func createGCSBucketIfNecessary(ctx context.Context, gcsClient *storage.Client, config *ExtendedRemoteStateConfigGCS, terragruntOptions *options.TerragruntOptions) error { - if !DoesGCSBucketExist(gcsClient, &config.remoteStateConfigGCS) { + // TODO: Remove lint suppression + if !DoesGCSBucketExist(gcsClient, &config.remoteStateConfigGCS) { //nolint:contextcheck terragruntOptions.Logger.Debugf("Remote state GCS bucket %s does not exist. Attempting to create it", config.remoteStateConfigGCS.Bucket) // A project must be specified in order for terragrunt to automatically create a storage bucket. @@ -301,7 +305,8 @@ func createGCSBucketIfNecessary(ctx context.Context, gcsClient *storage.Client, description := fmt.Sprintf("Create GCS bucket %s", config.remoteStateConfigGCS.Bucket) return util.DoWithRetry(ctx, description, gcpMaxRetries, gcpSleepBetweenRetries, logrus.DebugLevel, func(ctx context.Context) error { - return CreateGCSBucketWithVersioning(gcsClient, config, terragruntOptions) + // TODO: Remove lint suppression + return CreateGCSBucketWithVersioning(gcsClient, config, terragruntOptions) //nolint:contextcheck }) } } @@ -443,7 +448,7 @@ func DoesGCSBucketExist(gcsClient *storage.Client, config *RemoteStateConfigGCS) } it := bucket.Objects(ctx, nil) - if _, err := it.Next(); err == storage.ErrBucketNotExist { + if _, err := it.Next(); goErrors.Is(err, storage.ErrBucketNotExist) { return false } @@ -473,15 +478,15 @@ func CreateGCSClient(gcsConfigRemote RemoteStateConfigGCS) (*storage.Client, err creds := os.Getenv("GOOGLE_CREDENTIALS") contents, err := util.FileOrData(creds) if err != nil { - return nil, fmt.Errorf("Error loading credentials: %s", err) + return nil, fmt.Errorf("Error loading credentials: %w", err) } if err := json.Unmarshal([]byte(contents), &account); err != nil { - return nil, fmt.Errorf("Error parsing credentials '%s': %s", contents, err) + return nil, fmt.Errorf("Error parsing credentials '%s': %w", contents, err) } if err := json.Unmarshal([]byte(contents), &account); err != nil { - return nil, fmt.Errorf("Error parsing credentials '%s': %s", contents, err) + return nil, fmt.Errorf("Error parsing credentials '%s': %w", contents, err) } conf := jwt.Config{ diff --git a/remote/remote_state_gcs_test.go b/remote/remote_state_gcs_test.go index 2f984d210..bf1131ce4 100644 --- a/remote/remote_state_gcs_test.go +++ b/remote/remote_state_gcs_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/gruntwork-io/terragrunt/options" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -12,7 +11,7 @@ func TestGCSConfigValuesEqual(t *testing.T) { t.Parallel() terragruntOptions, err := options.NewTerragruntOptionsForTest("remote_state_test") - require.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) testCases := []struct { name string @@ -120,10 +119,10 @@ func TestGCSConfigValuesEqual(t *testing.T) { } actual := gcsConfigValuesEqual(config, testCase.backend, terragruntOptions) - assert.Equal(t, testCase.shouldBeEqual, actual) + require.Equal(t, testCase.shouldBeEqual, actual) // Ensure the config remains unchanged by the comparison - assert.Equal(t, testCase.config, config) + require.Equal(t, testCase.config, config) }) } } diff --git a/remote/remote_state_s3.go b/remote/remote_state_s3.go index 45ce6d17a..1c3d5edba 100644 --- a/remote/remote_state_s3.go +++ b/remote/remote_state_s3.go @@ -2,6 +2,7 @@ package remote import ( "context" + goErrors "errors" "fmt" "reflect" "strconv" @@ -593,7 +594,8 @@ func updateS3BucketIfNecessary(s3Client *s3.S3, config *ExtendedRemoteStateConfi } else { if config.AccessLoggingBucketName != "" { if err := configureAccessLogBucket(terragruntOptions, s3Client, config); err != nil { - return nil + // TODO: Remove lint suppression + return nil //nolint:nilerr } } else { terragruntOptions.Logger.Debugf("Access Logging is disabled for the remote state AWS S3 bucket %s", config.remoteStateConfigS3.Bucket) @@ -828,7 +830,8 @@ func CreateS3BucketWithVersioningSSEncryptionAndAccessLogging(s3Client *s3.S3, c if config.AccessLoggingBucketName != "" { if err := configureAccessLogBucket(terragruntOptions, s3Client, config); err != nil { - return nil + // TODO: Remove lint suppression + return nil //nolint:nilerr } } else { terragruntOptions.Logger.Debugf("Access Logging is disabled for the remote state AWS S3 bucket %s", config.remoteStateConfigS3.Bucket) @@ -962,14 +965,16 @@ func CreateS3Bucket(s3Client *s3.S3, bucket *string, terragruntOptions *options. // Determine if this is an error that implies you've already made a request to create the S3 bucket and it succeeded // or is in progress. This usually happens when running many tests in parallel or xxx-all commands. func isBucketAlreadyOwnedByYouError(err error) bool { - awsErr, isAwsErr := errors.Unwrap(err).(awserr.Error) - return isAwsErr && (awsErr.Code() == "BucketAlreadyOwnedByYou" || awsErr.Code() == "OperationAborted") + var awsErr awserr.Error + ok := goErrors.As(err, &awsErr) + return ok && (awsErr.Code() == "BucketAlreadyOwnedByYou" || awsErr.Code() == "OperationAborted") } // isBucketCreationErrorRetriable returns true if the error is temporary and bucket creation can be retried. func isBucketCreationErrorRetriable(err error) bool { - awsErr, isAwsErr := errors.Unwrap(err).(awserr.Error) - if !isAwsErr { + var awsErr awserr.Error + ok := goErrors.As(err, &awsErr) + if !ok { return true } return awsErr.Code() == "InternalError" || awsErr.Code() == "OperationAborted" || awsErr.Code() == "InvalidParameter" @@ -1062,7 +1067,8 @@ func checkIfBucketRootAccess(s3Client *s3.S3, config *RemoteStateConfigS3, terra }) if err != nil { // NoSuchBucketPolicy error is considered as no policy. - if awsErr, ok := err.(awserr.Error); ok { + var awsErr awserr.Error + if ok := goErrors.As(err, &awsErr); ok { if awsErr.Code() == "NoSuchBucketPolicy" { return false, nil } @@ -1175,9 +1181,10 @@ func checkIfBucketEnforcedTLS(s3Client *s3.S3, config *RemoteStateConfigS3, terr if err != nil { // S3 API error codes: // http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html - if aerr, ok := err.(awserr.Error); ok { + var awsErr awserr.Error + if ok := goErrors.As(err, &awsErr); ok { // Enforced TLS policy if is not found bucket policy - if aerr.Code() == "NoSuchBucketPolicy" { + if awsErr.Code() == "NoSuchBucketPolicy" { terragruntOptions.Logger.Debugf("Could not get policy for bucket %s", config.Bucket) return false, nil } @@ -1377,9 +1384,10 @@ func checkIfS3PublicAccessBlockingEnabled(s3Client *s3.S3, config *RemoteStateCo Bucket: aws.String(config.Bucket), }) if err != nil { - if aerr, ok := err.(awserr.Error); ok { + var awsErr awserr.Error + if ok := goErrors.As(err, &awsErr); ok { // Enforced block public access if is not found bucket policy - if aerr.Code() == "NoSuchPublicAccessBlockConfiguration" { + if awsErr.Code() == "NoSuchPublicAccessBlockConfiguration" { terragruntOptions.Logger.Debugf("Could not get public access block for bucket %s", config.Bucket) return false, nil } @@ -1482,8 +1490,9 @@ func checkBucketAccess(s3Client *s3.S3, bucket *string, key *string) error { if err == nil { return nil } - awsErr, isAwsErr := errors.Unwrap(err).(awserr.Error) - if !isAwsErr { + var awsErr awserr.Error + ok := goErrors.As(err, &awsErr) + if !ok { return err } // filter permissions errors diff --git a/remote/remote_state_s3_test.go b/remote/remote_state_s3_test.go index b39b2a8d3..b1a900e3a 100644 --- a/remote/remote_state_s3_test.go +++ b/remote/remote_state_s3_test.go @@ -122,7 +122,7 @@ func TestConfigValuesEqual(t *testing.T) { t.Parallel() terragruntOptions, err := options.NewTerragruntOptionsForTest("remote_state_test") - require.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) testCases := []struct { name string @@ -237,7 +237,7 @@ func TestConfigValuesEqual(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() actual := configValuesEqual(testCase.config, testCase.backend, terragruntOptions) - assert.Equal(t, testCase.shouldBeEqual, actual) + require.Equal(t, testCase.shouldBeEqual, actual) }) } } @@ -246,7 +246,7 @@ func TestForcePathStyleClientSession(t *testing.T) { t.Parallel() terragruntOptions, err := options.NewTerragruntOptionsForTest("s3_client_test") - require.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) testCases := []struct { name string @@ -279,13 +279,13 @@ func TestForcePathStyleClientSession(t *testing.T) { t.Parallel() s3ConfigExtended, err := ParseExtendedS3Config(testCase.config) - require.Nil(t, err, "Unexpected error parsing config for test: %v", err) + require.NoError(t, err, "Unexpected error parsing config for test: %v", err) s3Client, err := CreateS3Client(s3ConfigExtended.GetAwsSessionConfig(), terragruntOptions) - require.Nil(t, err, "Unexpected error creating client for test: %v", err) + require.NoError(t, err, "Unexpected error creating client for test: %v", err) actual := aws.BoolValue(s3Client.Config.S3ForcePathStyle) - assert.Equal(t, testCase.expected, actual) + require.Equal(t, testCase.expected, actual) }) } } @@ -320,7 +320,7 @@ func TestGetAwsSessionConfig(t *testing.T) { t.Parallel() s3ConfigExtended, err := ParseExtendedS3Config(testCase.config) - require.Nil(t, err, "Unexpected error parsing config for test: %v", err) + require.NoError(t, err, "Unexpected error parsing config for test: %v", err) expected := &aws_helper.AwsSessionConfig{ Region: s3ConfigExtended.remoteStateConfigS3.Region, @@ -334,7 +334,7 @@ func TestGetAwsSessionConfig(t *testing.T) { } actual := s3ConfigExtended.GetAwsSessionConfig() - assert.Equal(t, expected, actual) + require.Equal(t, expected, actual) }) } } @@ -362,7 +362,7 @@ func TestGetAwsSessionConfigWithAssumeRole(t *testing.T) { config := map[string]interface{}{"assume_role": testCase.config} s3ConfigExtended, err := ParseExtendedS3Config(config) - require.Nil(t, err, "Unexpected error parsing config for test: %v", err) + require.NoError(t, err, "Unexpected error parsing config for test: %v", err) expected := &aws_helper.AwsSessionConfig{ RoleArn: s3ConfigExtended.remoteStateConfigS3.AssumeRole.RoleArn, @@ -371,7 +371,7 @@ func TestGetAwsSessionConfigWithAssumeRole(t *testing.T) { } actual := s3ConfigExtended.GetAwsSessionConfig() - assert.Equal(t, expected, actual) + require.Equal(t, expected, actual) }) } } @@ -516,10 +516,10 @@ func TestGetTerraformInitArgs(t *testing.T) { actual := initializer.GetTerraformInitArgs(testCase.config) if !testCase.shouldBeEqual { - assert.NotEqual(t, testCase.expected, actual) + require.NotEqual(t, testCase.expected, actual) return } - assert.Equal(t, testCase.expected, actual) + require.Equal(t, testCase.expected, actual) }) } } @@ -567,8 +567,8 @@ func TestNegativePublicAccessResponse(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() response, err := validatePublicAccessBlock(testCase.response) - assert.NoError(t, err) - assert.False(t, response) + require.NoError(t, err) + require.False(t, response) }) } } @@ -616,9 +616,9 @@ func TestValidateS3Config(t *testing.T) { logger.SetOutput(buf) err := validateS3Config(testCase.extendedConfig) if err != nil { - assert.ErrorIs(t, err, testCase.expectedErr) + require.ErrorIs(t, err, testCase.expectedErr) } - assert.Contains(t, buf.String(), testCase.expectedOutput) + require.Contains(t, buf.String(), testCase.expectedOutput) }) } } diff --git a/remote/remote_state_test.go b/remote/remote_state_test.go index 88552858b..8fb4eda30 100644 --- a/remote/remote_state_test.go +++ b/remote/remote_state_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/gruntwork-io/terragrunt/options" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) /** @@ -121,7 +121,7 @@ func TestToTerraformInitArgsNoBackendConfigs(t *testing.T) { for _, state := range remoteStates { args := state.ToTerraformInitArgs() - assert.Empty(t, args) + require.Empty(t, args) } } @@ -129,7 +129,7 @@ func TestDiffersFrom(t *testing.T) { t.Parallel() terragruntOptions, err := options.NewTerragruntOptionsForTest("remote_state_test") - assert.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) testCases := []struct { name string @@ -286,16 +286,16 @@ func TestDiffersFrom(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { t.Parallel() shouldOverride := testCase.stateFromConfig.differsFrom(&testCase.existingBackend, terragruntOptions) - assert.Equal(t, testCase.shouldOverride, shouldOverride, "Expect differsFrom to return %t but got %t for existingRemoteState %v and remoteStateFromTerragruntConfig %v", testCase.shouldOverride, shouldOverride, testCase.existingBackend, testCase.stateFromConfig) + require.Equal(t, testCase.shouldOverride, shouldOverride, "Expect differsFrom to return %t but got %t for existingRemoteState %v and remoteStateFromTerragruntConfig %v", testCase.shouldOverride, shouldOverride, testCase.existingBackend, testCase.stateFromConfig) }) } } func assertTerraformInitArgsEqual(t *testing.T, actualArgs []string, expectedArgs string) { expected := strings.Split(expectedArgs, " ") - assert.Len(t, actualArgs, len(expected)) + require.Len(t, actualArgs, len(expected)) for _, expectedArg := range expected { - assert.Contains(t, actualArgs, expectedArg) + require.Contains(t, actualArgs, expectedArg) } } diff --git a/remote/terraform_state_file.go b/remote/terraform_state_file.go index 094e2271a..b5ca991a1 100644 --- a/remote/terraform_state_file.go +++ b/remote/terraform_state_file.go @@ -22,23 +22,23 @@ const DefaultPathToRemoteStateFile = "terraform.tfstate" // TerraformState - represents the structure of the Terraform .tfstate file. type TerraformState struct { - Version int - Serial int - Backend *TerraformBackend - Modules []TerraformStateModule + Version int `json:"Version"` + Serial int `json:"Serial"` + Backend *TerraformBackend `json:"Backend"` + Modules []TerraformStateModule `json:"Modules"` } // TerraformBackend represents the structure of the "backend" section in the Terraform .tfstate file. type TerraformBackend struct { - Type string - Config map[string]interface{} + Type string `json:"Type"` + Config map[string]interface{} `json:"Config"` } // TerraformStateModule represents the structure of a "module" section in the Terraform .tfstate file. type TerraformStateModule struct { - Path []string - Outputs map[string]interface{} - Resources map[string]interface{} + Path []string `json:"Path"` + Outputs map[string]interface{} `json:"Outputs"` + Resources map[string]interface{} `json:"Resources"` } // IsRemote returns true if this Terraform state is configured for remote state storage. diff --git a/remote/terraform_state_file_test.go b/remote/terraform_state_file_test.go index bcae0d9d8..2fbc580e7 100644 --- a/remote/terraform_state_file_test.go +++ b/remote/terraform_state_file_test.go @@ -4,8 +4,9 @@ import ( "encoding/json" "testing" - "github.com/gruntwork-io/go-commons/errors" - "github.com/stretchr/testify/assert" + "errors" + + "github.com/stretchr/testify/require" ) func TestParseTerraformStateLocal(t *testing.T) { @@ -43,9 +44,9 @@ func TestParseTerraformStateLocal(t *testing.T) { actualTerraformState, err := parseTerraformState([]byte(stateFile)) - assert.NoError(t, err) - assert.Equal(t, expectedTerraformState, actualTerraformState) - assert.False(t, actualTerraformState.IsRemote()) + require.NoError(t, err) + require.Equal(t, expectedTerraformState, actualTerraformState) + require.False(t, actualTerraformState.IsRemote()) } func TestParseTerraformStateRemote(t *testing.T) { @@ -100,9 +101,9 @@ func TestParseTerraformStateRemote(t *testing.T) { actualTerraformState, err := parseTerraformState([]byte(stateFile)) - assert.NoError(t, err) - assert.Equal(t, expectedTerraformState, actualTerraformState) - assert.True(t, actualTerraformState.IsRemote()) + require.NoError(t, err) + require.Equal(t, expectedTerraformState, actualTerraformState) + require.True(t, actualTerraformState.IsRemote()) } func TestParseTerraformStateRemoteFull(t *testing.T) { @@ -287,9 +288,9 @@ func TestParseTerraformStateRemoteFull(t *testing.T) { actualTerraformState, err := parseTerraformState([]byte(stateFile)) - assert.NoError(t, err) - assert.Equal(t, expectedTerraformState, actualTerraformState) - assert.True(t, actualTerraformState.IsRemote()) + require.NoError(t, err) + require.Equal(t, expectedTerraformState, actualTerraformState) + require.True(t, actualTerraformState.IsRemote()) } func TestParseTerraformStateEmpty(t *testing.T) { @@ -301,9 +302,9 @@ func TestParseTerraformStateEmpty(t *testing.T) { actualTerraformState, err := parseTerraformState([]byte(stateFile)) - assert.NoError(t, err) - assert.Equal(t, expectedTerraformState, actualTerraformState) - assert.False(t, actualTerraformState.IsRemote()) + require.NoError(t, err) + require.Equal(t, expectedTerraformState, actualTerraformState) + require.False(t, actualTerraformState.IsRemote()) } func TestParseTerraformStateInvalid(t *testing.T) { @@ -313,10 +314,10 @@ func TestParseTerraformStateInvalid(t *testing.T) { actualTerraformState, err := parseTerraformState([]byte(stateFile)) - assert.Nil(t, actualTerraformState) - assert.Error(t, err) + require.Nil(t, actualTerraformState) + require.Error(t, err) - underlyingErr := errors.Unwrap(err) - _, isSyntaxErr := underlyingErr.(*json.SyntaxError) - assert.True(t, isSyntaxErr) + var jsonSyntaxError *json.SyntaxError + ok := errors.As(err, &jsonSyntaxError) + require.True(t, ok) } diff --git a/shell/error_explainer.go b/shell/error_explainer.go index 486ae966c..34edd96d5 100644 --- a/shell/error_explainer.go +++ b/shell/error_explainer.go @@ -1,6 +1,7 @@ package shell import ( + goErrors "errors" "fmt" "regexp" "strings" @@ -33,8 +34,9 @@ var terraformErrorsMatcher = map[string]string{ // ExplainError will try to explain the error to the user, if we know how to do so. func ExplainError(err error) string { errorsToProcess := []error{err} - multiErrors, ok := err.(*multierror.Error) - if ok { + var multiErrors *multierror.Error + // multiErrors, ok := err.(*multierror.Error) + if ok := goErrors.As(err, &multiErrors); ok { errorsToProcess = multiErrors.Errors } explanations := map[string]string{} @@ -47,8 +49,8 @@ func ExplainError(err error) string { } message := originalError.Error() // extract process output, if it is the case - processError, ok := originalError.(util.ProcessExecutionError) - if ok { + var processError util.ProcessExecutionError + if ok := goErrors.As(originalError, &processError); ok { errorOutput := processError.Stderr stdOut := processError.StdOut message = fmt.Sprintf("%s\n%s", stdOut, errorOutput) diff --git a/shell/run_shell_cmd_output_test.go b/shell/run_shell_cmd_output_test.go index b6d414fae..f08248e53 100644 --- a/shell/run_shell_cmd_output_test.go +++ b/shell/run_shell_cmd_output_test.go @@ -15,7 +15,6 @@ import ( "github.com/stretchr/testify/require" "github.com/gruntwork-io/terragrunt/options" - "github.com/stretchr/testify/assert" ) func TestCommandOutputOrder(t *testing.T) { @@ -82,7 +81,7 @@ func testCommandOutput(t *testing.T, withOptions func(*options.TerragruntOptions out, err := RunShellCommandWithOutput(context.Background(), terragruntOptions, "", !allocateStdout, false, "../testdata/test_outputs.sh", "same") require.NotNil(t, out, "Should get output") - assert.Nil(t, err, "Should have no error") + require.NoError(t, err, "Should have no error") assertResults(allOutputBuffer.String(), out) } @@ -95,13 +94,13 @@ func assertOutputs( ) func(string, *util.CmdOutput) { return func(allOutput string, out *util.CmdOutput) { allOutputs := strings.Split(strings.TrimSpace(allOutput), "\n") - assert.Equal(t, expectedAllOutputs, allOutputs) + require.Equal(t, expectedAllOutputs, allOutputs) stdOutputs := strings.Split(strings.TrimSpace(out.Stdout), "\n") - assert.Equal(t, expectedStdOutputs, stdOutputs) + require.Equal(t, expectedStdOutputs, stdOutputs) stdErrs := strings.Split(strings.TrimSpace(out.Stderr), "\n") - assert.Equal(t, expectedStdErrs, stdErrs) + require.Equal(t, expectedStdErrs, stdErrs) } } diff --git a/shell/run_shell_cmd_test.go b/shell/run_shell_cmd_test.go index 29c37f701..5fee39b81 100644 --- a/shell/run_shell_cmd_test.go +++ b/shell/run_shell_cmd_test.go @@ -10,27 +10,26 @@ import ( "github.com/stretchr/testify/require" "github.com/gruntwork-io/terragrunt/options" - "github.com/stretchr/testify/assert" ) func TestRunShellCommand(t *testing.T) { t.Parallel() terragruntOptions, err := options.NewTerragruntOptionsForTest("") - assert.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) cmd := RunShellCommand(context.Background(), terragruntOptions, "terraform", "--version") - assert.Nil(t, cmd) + require.NoError(t, cmd) cmd = RunShellCommand(context.Background(), terragruntOptions, "terraform", "not-a-real-command") - assert.Error(t, cmd) + require.Error(t, cmd) } func TestRunShellOutputToStderrAndStdout(t *testing.T) { t.Parallel() terragruntOptions, err := options.NewTerragruntOptionsForTest("") - assert.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) stdout := new(bytes.Buffer) stderr := new(bytes.Buffer) @@ -39,10 +38,10 @@ func TestRunShellOutputToStderrAndStdout(t *testing.T) { terragruntOptions.ErrWriter = stderr cmd := RunShellCommand(context.Background(), terragruntOptions, "terraform", "--version") - assert.Nil(t, cmd) + require.NoError(t, cmd) - assert.True(t, strings.Contains(stdout.String(), "Terraform"), "Output directed to stdout") - assert.True(t, len(stderr.String()) == 0, "No output to stderr") + require.True(t, strings.Contains(stdout.String(), "Terraform"), "Output directed to stdout") + require.Empty(t, stderr.String(), "No output to stderr") stdout = new(bytes.Buffer) stderr = new(bytes.Buffer) @@ -52,10 +51,10 @@ func TestRunShellOutputToStderrAndStdout(t *testing.T) { terragruntOptions.ErrWriter = stderr cmd = RunShellCommand(context.Background(), terragruntOptions, "terraform", "--version") - assert.Nil(t, cmd) + require.NoError(t, cmd) - assert.True(t, strings.Contains(stderr.String(), "Terraform"), "Output directed to stderr") - assert.True(t, len(stdout.String()) == 0, "No output to stdout") + require.True(t, strings.Contains(stderr.String(), "Terraform"), "Output directed to stderr") + require.Empty(t, stdout.String(), "No output to stdout") } func TestLastReleaseTag(t *testing.T) { @@ -70,8 +69,8 @@ func TestLastReleaseTag(t *testing.T) { "refs/tags/v0.5.1", } lastTag := lastReleaseTag(tags) - assert.NotEmpty(t, lastTag) - assert.Equal(t, "v20.1.2", lastTag) + require.NotEmpty(t, lastTag) + require.Equal(t, "v20.1.2", lastTag) } func TestGitLevelTopDirCaching(t *testing.T) { @@ -79,8 +78,8 @@ func TestGitLevelTopDirCaching(t *testing.T) { ctx := context.Background() ctx = ContextWithTerraformCommandHook(ctx, nil) c := cache.ContextCache[string](ctx, RunCmdCacheContextKey) - assert.NotNil(t, c) - assert.Equal(t, 0, len(c.Cache)) + require.NotNil(t, c) + require.Empty(t, len(c.Cache)) terragruntOptions, err := options.NewTerragruntOptionsForTest("") require.NoError(t, err) path := "." @@ -88,6 +87,6 @@ func TestGitLevelTopDirCaching(t *testing.T) { require.NoError(t, err) path2, err := GitTopLevelDir(ctx, terragruntOptions, path) require.NoError(t, err) - assert.Equal(t, path1, path2) - assert.Equal(t, 1, len(c.Cache)) + require.Equal(t, path1, path2) + require.Len(t, c.Cache, 1) } diff --git a/shell/run_shell_cmd_unix_test.go b/shell/run_shell_cmd_unix_test.go index 150bd1a8a..4beda9b81 100644 --- a/shell/run_shell_cmd_unix_test.go +++ b/shell/run_shell_cmd_unix_test.go @@ -17,7 +17,7 @@ import ( "github.com/gruntwork-io/terragrunt/util" "github.com/gruntwork-io/terragrunt/options" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestExitCodeUnix(t *testing.T) { @@ -28,21 +28,21 @@ func TestExitCodeUnix(t *testing.T) { err := cmd.Run() if i == 0 { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.Error(t, err) + require.Error(t, err) } retCode, err := util.GetExitCode(err) - assert.NoError(t, err) - assert.Equal(t, i, retCode) + require.NoError(t, err) + require.Equal(t, i, retCode) } // assert a non exec.ExitError returns an error err := goerrors.New("This is an explicit error") retCode, retErr := util.GetExitCode(err) - assert.Error(t, retErr, "An error was expected") - assert.Equal(t, err, retErr) - assert.Equal(t, 0, retCode) + require.Error(t, retErr, "An error was expected") + require.Equal(t, err, retErr) + require.Equal(t, 0, retCode) } func TestNewSignalsForwarderWaitUnix(t *testing.T) { @@ -51,7 +51,7 @@ func TestNewSignalsForwarderWaitUnix(t *testing.T) { expectedWait := 5 terragruntOptions, err := options.NewTerragruntOptionsForTest("") - assert.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) cmd := exec.Command("../testdata/test_sigint_wait.sh", strconv.Itoa(expectedWait)) @@ -70,11 +70,11 @@ func TestNewSignalsForwarderWaitUnix(t *testing.T) { cmd.Process.Signal(os.Interrupt) err = <-runChannel cmdChannel <- err - assert.Error(t, err) + require.Error(t, err) retCode, err := util.GetExitCode(err) - assert.NoError(t, err) - assert.Equal(t, retCode, expectedWait) - assert.WithinDuration(t, time.Now(), start.Add(time.Duration(expectedWait)*time.Second), time.Second, + require.NoError(t, err) + require.Equal(t, expectedWait, retCode) + require.WithinDuration(t, time.Now(), start.Add(time.Duration(expectedWait)*time.Second), time.Second, "Expected to wait 5 (+/-1) seconds after SIGINT") } @@ -85,7 +85,7 @@ func TestNewSignalsForwarderMultipleUnix(t *testing.T) { expectedInterrupts := 10 terragruntOptions, err := options.NewTerragruntOptionsForTest("") - assert.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) cmd := exec.Command("../testdata/test_sigint_multiple.sh", strconv.Itoa(expectedInterrupts)) @@ -118,18 +118,18 @@ func TestNewSignalsForwarderMultipleUnix(t *testing.T) { interrupts, err := interruptAndWaitForProcess() cmdChannel <- err - assert.Error(t, err) + require.Error(t, err) retCode, err := util.GetExitCode(err) - assert.NoError(t, err) - assert.True(t, retCode <= interrupts, "Subprocess received wrong number of signals") - assert.Equal(t, retCode, expectedInterrupts, "Subprocess didn't receive multiple signals") + require.NoError(t, err) + require.LessOrEqual(t, retCode, interrupts, "Subprocess received wrong number of signals") + require.Equal(t, expectedInterrupts, retCode, "Subprocess didn't receive multiple signals") } func TestRunShellCommandWithOutputInterrupt(t *testing.T) { t.Parallel() terragruntOptions, err := options.NewTerragruntOptionsForTest("") - assert.Nil(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) + require.NoError(t, err, "Unexpected error creating NewTerragruntOptionsForTest: %v", err) errCh := make(chan error) expectedWait := 5 @@ -144,5 +144,5 @@ func TestRunShellCommandWithOutputInterrupt(t *testing.T) { }) expectedErr := fmt.Sprintf("[.] exit status %d", expectedWait) - assert.EqualError(t, <-errCh, expectedErr) + require.EqualError(t, <-errCh, expectedErr) } diff --git a/telemetry/metrics.go b/telemetry/metrics.go index 49b3c7bf5..29f098c92 100644 --- a/telemetry/metrics.go +++ b/telemetry/metrics.go @@ -98,7 +98,9 @@ func configureMetricsCollection(ctx context.Context, opts *TelemetryOptions) err func newMetricsExporter(ctx context.Context, opts *TelemetryOptions) (metric.Exporter, error) { exporterType := metricsExporterType(env.GetString(opts.Vars["TERRAGRUNT_TELEMETRY_METRIC_EXPORTER"], string(noneMetricsExporterType))) insecure := env.GetBool(opts.GetValue("TERRAGRUNT_TELEMETRY_METRIC_EXPORTER_INSECURE_ENDPOINT", "TERRAGRUNT_TELEMERTY_METRIC_EXPORTER_INSECURE_ENDPOINT"), false) - switch exporterType { + + // TODO: Remove this lint suppression + switch exporterType { //nolint:exhaustive case oltpHttpMetricsExporterType: var config []otlpmetrichttp.Option if insecure { diff --git a/telemetry/metrics_test.go b/telemetry/metrics_test.go index bf5140a86..ff1881790 100644 --- a/telemetry/metrics_test.go +++ b/telemetry/metrics_test.go @@ -8,7 +8,7 @@ import ( "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc" "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp" ) @@ -17,7 +17,7 @@ func TestNewMetricsExporter(t *testing.T) { ctx := context.Background() stdout, err := stdoutmetric.New() - assert.NoError(t, err) + require.NoError(t, err) tests := []struct { name string @@ -65,12 +65,12 @@ func TestNewMetricsExporter(t *testing.T) { } exporter, err := newMetricsExporter(ctx, opts) - assert.NoError(t, err) + require.NoError(t, err) if tt.expectNil { - assert.Nil(t, exporter) + require.Nil(t, exporter) } else { - assert.IsType(t, tt.expectedType, exporter) + require.IsType(t, tt.expectedType, exporter) } }) } @@ -124,7 +124,7 @@ func TestCleanMetricName(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() result := cleanMetricName(tc.input) - assert.Equal(t, tc.expected, result) + require.Equal(t, tc.expected, result) }) } } diff --git a/telemetry/traces.go b/telemetry/traces.go index 8031c766d..c85fc18f2 100644 --- a/telemetry/traces.go +++ b/telemetry/traces.go @@ -126,7 +126,9 @@ func newTraceProvider(opts *TelemetryOptions, exp sdktrace.SpanExporter) (*sdktr func newTraceExporter(ctx context.Context, opts *TelemetryOptions) (sdktrace.SpanExporter, error) { exporterType := traceExporterType(env.GetString(opts.Vars["TERRAGRUNT_TELEMETRY_TRACE_EXPORTER"], string(noneTraceExporterType))) insecure := env.GetBool(opts.GetValue("TERRAGRUNT_TELEMETRY_TRACE_EXPORTER_INSECURE_ENDPOINT", "TERRAGRUNT_TELEMERTY_TRACE_EXPORTER_INSECURE_ENDPOINT"), false) - switch exporterType { + + // TODO: Remove lint suppression + switch exporterType { //nolint:exhaustive case httpTraceExporterType: endpoint := env.GetString(opts.GetValue("TERRAGRUNT_TELEMETRY_TRACE_EXPORTER_HTTP_ENDPOINT", "TERRAGRUNT_TELEMERTY_TRACE_EXPORTER_HTTP_ENDPOINT"), "") if endpoint == "" { @@ -177,8 +179,13 @@ func openSpan(ctx context.Context, name string, attrs map[string]interface{}) (c ctx = trace.ContextWithSpanContext(ctx, spanContext) } - ctx, span := rootTracer.Start(ctx, name) + // This lint is suppressed because we definitely do close the span + // in a defer statement everywhere openSpan is called. It seems like + // a useful lint, though. We should consider removing the suppression + // and fixing the lint. + + ctx, span := rootTracer.Start(ctx, name) // nolint:spancheck // convert attrs map to span.SetAttributes span.SetAttributes(mapToAttributes(attrs)...) - return ctx, span + return ctx, span //nolint:spancheck } diff --git a/telemetry/traces_test.go b/telemetry/traces_test.go index f31812c97..6bf185454 100644 --- a/telemetry/traces_test.go +++ b/telemetry/traces_test.go @@ -5,7 +5,7 @@ import ( "io" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" "go.opentelemetry.io/otel/exporters/stdout/stdouttrace" @@ -15,13 +15,13 @@ func TestNewTraceExporter(t *testing.T) { ctx := context.Background() http, err := otlptracehttp.New(ctx) - assert.NoError(t, err) + require.NoError(t, err) grpc, err := otlptracegrpc.New(ctx) - assert.NoError(t, err) + require.NoError(t, err) stdoutrace, err := stdouttrace.New() - assert.NoError(t, err) + require.NoError(t, err) tests := []struct { name string @@ -94,10 +94,10 @@ func TestNewTraceExporter(t *testing.T) { exporter, err := newTraceExporter(ctx, tt.telemetryOptions) if tt.expectError { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) - assert.IsType(t, tt.expectedType, exporter) + require.NoError(t, err) + require.IsType(t, tt.expectedType, exporter) } }) } diff --git a/terraform/cliconfig/config_test.go b/terraform/cliconfig/config_test.go index e92ea5abc..fecaf5582 100644 --- a/terraform/cliconfig/config_test.go +++ b/terraform/cliconfig/config_test.go @@ -6,7 +6,7 @@ import ( "path/filepath" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestConfig(t *testing.T) { @@ -18,7 +18,7 @@ func TestConfig(t *testing.T) { ) tempCacheDir, err := os.MkdirTemp("", "*") - assert.NoError(t, err) + require.NoError(t, err) testCases := []struct { providerInstallationMethods []ProviderInstallationMethod @@ -90,7 +90,7 @@ provider_installation { t.Parallel() tempDir, err := os.MkdirTemp("", "*") - assert.NoError(t, err) + require.NoError(t, err) configFile := filepath.Join(tempDir, ".terraformrc") for _, host := range testCase.hosts { @@ -99,12 +99,12 @@ provider_installation { testCase.config.AddProviderInstallationMethods(testCase.providerInstallationMethods...) err = testCase.config.Save(configFile) - assert.NoError(t, err) + require.NoError(t, err) hclBytes, err := os.ReadFile(configFile) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, testCase.expectedHCL, string(hclBytes)) + require.Equal(t, testCase.expectedHCL, string(hclBytes)) }) } } diff --git a/terraform/cliconfig/provider_installation.go b/terraform/cliconfig/provider_installation.go index eb4040569..af503ee78 100644 --- a/terraform/cliconfig/provider_installation.go +++ b/terraform/cliconfig/provider_installation.go @@ -58,9 +58,9 @@ type ProviderInstallationMethod interface { } type ProviderInstallationDirect struct { - Name string `hcl:",label"` - Include *[]string `hcl:"include,optional"` - Exclude *[]string `hcl:"exclude,optional"` + Name string `hcl:",label" json:"Name"` + Include *[]string `hcl:"include,optional" json:"Include"` + Exclude *[]string `hcl:"exclude,optional" json:"Exclude"` } func NewProviderInstallationDirect(include, exclude []string) *ProviderInstallationDirect { @@ -136,15 +136,16 @@ func (method *ProviderInstallationDirect) RemoveInclude(addrs []string) { } func (method *ProviderInstallationDirect) String() string { - b, _ := json.Marshal(method) //nolint:errcheck + // Odd that this err isn't checked. There should be an explanation why. + b, _ := json.Marshal(method) //nolint:errchkjson return string(b) } type ProviderInstallationFilesystemMirror struct { - Name string `hcl:",label"` - Path string `hcl:"path,attr"` - Include *[]string `hcl:"include,optional"` - Exclude *[]string `hcl:"exclude,optional"` + Name string `hcl:",label" json:"Name"` + Path string `hcl:"path,attr" json:"Path"` + Include *[]string `hcl:"include,optional" json:"Include"` + Exclude *[]string `hcl:"exclude,optional" json:"Exclude"` } func NewProviderInstallationFilesystemMirror(path string, include, exclude []string) *ProviderInstallationFilesystemMirror { @@ -221,15 +222,16 @@ func (method *ProviderInstallationFilesystemMirror) RemoveInclude(addrs []string } func (method *ProviderInstallationFilesystemMirror) String() string { - b, _ := json.Marshal(method) //nolint:errcheck + // Odd that this err isn't checked. There should be an explanation why. + b, _ := json.Marshal(method) //nolint:errchkjson return string(b) } type ProviderInstallationNetworkMirror struct { - Name string `hcl:",label"` - URL string `hcl:"url,attr"` - Include *[]string `hcl:"include,optional"` - Exclude *[]string `hcl:"exclude,optional"` + Name string `hcl:",label" json:"Name"` + URL string `hcl:"url,attr" json:"URL"` + Include *[]string `hcl:"include,optional" json:"Include"` + Exclude *[]string `hcl:"exclude,optional" json:"Exclude"` } func NewProviderInstallationNetworkMirror(url string, include, exclude []string) *ProviderInstallationNetworkMirror { @@ -306,6 +308,7 @@ func (method *ProviderInstallationNetworkMirror) RemoveInclude(addrs []string) { } func (method *ProviderInstallationNetworkMirror) String() string { - b, _ := json.Marshal(method) //nolint:errcheck + // Odd that this err isn't checked. There should be an explanation why. + b, _ := json.Marshal(method) //nolint:errchkjson return string(b) } diff --git a/terraform/getproviders/package_authentication.go b/terraform/getproviders/package_authentication.go index 647504ba0..4300632e0 100644 --- a/terraform/getproviders/package_authentication.go +++ b/terraform/getproviders/package_authentication.go @@ -4,6 +4,7 @@ import ( "bytes" "crypto/sha256" "encoding/hex" + goErrors "errors" "io" "os" "strings" @@ -243,7 +244,7 @@ func (auth signatureAuthentication) Authenticate(location string) (*PackageAuthe func (auth signatureAuthentication) checkDetachedSignature(keyring openpgp.KeyRing, signed, signature io.Reader, config *packet.Config) error { entity, err := openpgp.CheckDetachedSignature(keyring, signed, signature, config) - if err == openpgpErrors.ErrKeyExpired { + if goErrors.Is(err, openpgpErrors.ErrKeyExpired) { for id := range entity.Identities { log.Warnf("expired openpgp key from %s\n", id) } @@ -266,7 +267,7 @@ func (auth signatureAuthentication) findSigningKey() (string, string, error) { if err := auth.checkDetachedSignature(keyring, bytes.NewReader(auth.Document), bytes.NewReader(auth.Signature), nil); err != nil { // If the signature issuer does not match the the key, keep trying the rest of the provided keys. - if err == openpgpErrors.ErrUnknownIssuer { + if goErrors.Is(err, openpgpErrors.ErrUnknownIssuer) { continue } diff --git a/terraform/getter.go b/terraform/getter.go index 941ecb800..8d6e2dfaa 100644 --- a/terraform/getter.go +++ b/terraform/getter.go @@ -176,7 +176,7 @@ func (tfrGetter *RegistryGetter) GetFile(dst string, src *url.URL) error { } // getSubdir downloads the source into the destination, but with the proper subdir. -func (tfrGetter *RegistryGetter) getSubdir(ctx context.Context, dstPath, sourceURL, subDir string) error { +func (tfrGetter *RegistryGetter) getSubdir(_ context.Context, dstPath, sourceURL, subDir string) error { // Create a temporary directory to store the full source. This has to be a non-existent directory. tempdirPath, tempdirCloser, err := safetemp.Dir("", "getter") if err != nil { @@ -328,12 +328,13 @@ func httpGETAndGetResponse(ctx context.Context, getURL url.URL) ([]byte, *http.H return nil, nil, errors.WithStackTrace(err) } - defer func(Body io.ReadCloser) { - err := Body.Close() + defer func() { + err := resp.Body.Close() if err != nil { util.GlobalFallbackLogEntry.Warnf("Error closing response body: %v", err) } - }(resp.Body) + }() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, nil, errors.WithStackTrace(RegistryAPIErr{url: getURL.String(), statusCode: resp.StatusCode}) } diff --git a/terraform/getter_test.go b/terraform/getter_test.go index 938e2eca3..4ccddb505 100644 --- a/terraform/getter_test.go +++ b/terraform/getter_test.go @@ -8,7 +8,6 @@ import ( "testing" "github.com/gruntwork-io/terratest/modules/files" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -17,7 +16,7 @@ func TestGetModuleRegistryURLBasePath(t *testing.T) { basePath, err := getModuleRegistryURLBasePath(context.Background(), "registry.terraform.io") require.NoError(t, err) - assert.Equal(t, "/v1/modules/", basePath) + require.Equal(t, "/v1/modules/", basePath) } func TestGetTerraformHeader(t *testing.T) { @@ -30,7 +29,7 @@ func TestGetTerraformHeader(t *testing.T) { } terraformGetHeader, err := getTerraformGetHeader(context.Background(), testModuleURL) require.NoError(t, err) - assert.Contains(t, terraformGetHeader, "github.com/terraform-aws-modules/terraform-aws-vpc") + require.Contains(t, terraformGetHeader, "github.com/terraform-aws-modules/terraform-aws-vpc") } func TestGetDownloadURLFromHeader(t *testing.T) { @@ -93,7 +92,7 @@ func TestGetDownloadURLFromHeader(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { downloadURL, err := getDownloadURLFromHeader(testCase.moduleURL, testCase.terraformGet) require.NoError(t, err) - assert.Equal(t, testCase.expectedResult, downloadURL) + require.Equal(t, testCase.expectedResult, downloadURL) }) } } @@ -110,11 +109,11 @@ func TestTFRGetterRootDir(t *testing.T) { // The dest path must not exist for go getter to work moduleDestPath := filepath.Join(dstPath, "terraform-aws-vpc") - assert.False(t, files.FileExists(filepath.Join(moduleDestPath, "main.tf"))) + require.False(t, files.FileExists(filepath.Join(moduleDestPath, "main.tf"))) tfrGetter := new(RegistryGetter) require.NoError(t, tfrGetter.Get(moduleDestPath, testModuleURL)) - assert.True(t, files.FileExists(filepath.Join(moduleDestPath, "main.tf"))) + require.True(t, files.FileExists(filepath.Join(moduleDestPath, "main.tf"))) } func TestTFRGetterSubModule(t *testing.T) { @@ -129,24 +128,24 @@ func TestTFRGetterSubModule(t *testing.T) { // The dest path must not exist for go getter to work moduleDestPath := filepath.Join(dstPath, "terraform-aws-vpc") - assert.False(t, files.FileExists(filepath.Join(moduleDestPath, "main.tf"))) + require.False(t, files.FileExists(filepath.Join(moduleDestPath, "main.tf"))) tfrGetter := new(RegistryGetter) require.NoError(t, tfrGetter.Get(moduleDestPath, testModuleURL)) - assert.True(t, files.FileExists(filepath.Join(moduleDestPath, "main.tf"))) + require.True(t, files.FileExists(filepath.Join(moduleDestPath, "main.tf"))) } func TestBuildRequestUrlFullPath(t *testing.T) { t.Parallel() requestUrl, err := buildRequestUrl("gruntwork.io", "https://gruntwork.io/registry/modules/v1/", "/tfr-project/terraform-aws-tfr", "6.6.6") - assert.NoError(t, err) - assert.Equal(t, "https://gruntwork.io/registry/modules/v1/tfr-project/terraform-aws-tfr/6.6.6/download", requestUrl.String()) + require.NoError(t, err) + require.Equal(t, "https://gruntwork.io/registry/modules/v1/tfr-project/terraform-aws-tfr/6.6.6/download", requestUrl.String()) } func TestBuildRequestUrlRelativePath(t *testing.T) { t.Parallel() requestUrl, err := buildRequestUrl("gruntwork.io", "/registry/modules/v1", "/tfr-project/terraform-aws-tfr", "6.6.6") - assert.NoError(t, err) - assert.Equal(t, "https://gruntwork.io/registry/modules/v1/tfr-project/terraform-aws-tfr/6.6.6/download", requestUrl.String()) + require.NoError(t, err) + require.Equal(t, "https://gruntwork.io/registry/modules/v1/tfr-project/terraform-aws-tfr/6.6.6/download", requestUrl.String()) } diff --git a/test/integration_catalog_test.go b/test/integration_catalog_test.go index ac17dad90..1d6d21e94 100644 --- a/test/integration_catalog_test.go +++ b/test/integration_catalog_test.go @@ -11,7 +11,6 @@ import ( "github.com/gruntwork-io/terragrunt/cli/commands/catalog/tui/command" "github.com/gruntwork-io/terragrunt/config" "github.com/gruntwork-io/terragrunt/options" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -27,8 +26,8 @@ func TestScaffoldGitRepo(t *testing.T) { require.NoError(t, err) modules, err := repo.FindModules(ctx) - assert.NoError(t, err) - assert.Equal(t, 4, len(modules)) + require.NoError(t, err) + require.Len(t, modules, 4) } func TestScaffoldGitModule(t *testing.T) { @@ -43,31 +42,31 @@ func TestScaffoldGitModule(t *testing.T) { require.NoError(t, err) modules, err := repo.FindModules(ctx) - assert.NoError(t, err) + require.NoError(t, err) var auroraModule *module.Module for _, m := range modules { if m.Title() == "Terraform Fake AWS Aurora Module" { auroraModule = m } } - assert.NotNil(t, auroraModule) + require.NotNil(t, auroraModule) testPath := t.TempDir() opts, err := options.NewTerragruntOptionsForTest(testPath) - assert.NoError(t, err) + require.NoError(t, err) opts.ScaffoldVars = []string{"EnableRootInclude=false"} cmd := command.NewScaffold(opts, auroraModule) err = cmd.Run() - assert.NoError(t, err) + require.NoError(t, err) cfg := readConfig(t, opts) - assert.NotEmpty(t, cfg.Inputs) - assert.Equal(t, 1, len(cfg.Inputs)) + require.NotEmpty(t, cfg.Inputs) + require.Len(t, cfg.Inputs, 1) _, found := cfg.Inputs["vpc_id"] - assert.True(t, found) - assert.Contains(t, *cfg.Terraform.Source, "git::https://github.com/gruntwork-io/terraform-fake-modules.git//modules/aws/aurora") + require.True(t, found) + require.Contains(t, *cfg.Terraform.Source, "git::https://github.com/gruntwork-io/terraform-fake-modules.git//modules/aws/aurora") } func TestScaffoldGitModuleHttps(t *testing.T) { @@ -79,46 +78,46 @@ func TestScaffoldGitModuleHttps(t *testing.T) { require.NoError(t, err) repo, err := module.NewRepo(ctx, "https://github.com/gruntwork-io/terraform-fake-modules", tempDir) - assert.NoError(t, err) + require.NoError(t, err) modules, err := repo.FindModules(ctx) - assert.NoError(t, err) + require.NoError(t, err) var auroraModule *module.Module for _, m := range modules { if m.Title() == "Terraform Fake AWS Aurora Module" { auroraModule = m } } - assert.NotNil(t, auroraModule) + require.NotNil(t, auroraModule) testPath := t.TempDir() opts, err := options.NewTerragruntOptionsForTest(testPath) - assert.NoError(t, err) + require.NoError(t, err) opts.ScaffoldVars = []string{"EnableRootInclude=false"} cmd := command.NewScaffold(opts, auroraModule) err = cmd.Run() - assert.NoError(t, err) + require.NoError(t, err) cfg := readConfig(t, opts) - assert.NotEmpty(t, cfg.Inputs) - assert.Equal(t, 1, len(cfg.Inputs)) + require.NotEmpty(t, cfg.Inputs) + require.Len(t, cfg.Inputs, 1) _, found := cfg.Inputs["vpc_id"] - assert.True(t, found) - assert.Contains(t, *cfg.Terraform.Source, "git::https://github.com/gruntwork-io/terraform-fake-modules.git//modules/aws/aurora?ref=v0.0.5") + require.True(t, found) + require.Contains(t, *cfg.Terraform.Source, "git::https://github.com/gruntwork-io/terraform-fake-modules.git//modules/aws/aurora?ref=v0.0.5") runTerragrunt(t, fmt.Sprintf("terragrunt init --terragrunt-non-interactive --terragrunt-working-dir %s", opts.WorkingDir)) } func readConfig(t *testing.T, opts *options.TerragruntOptions) *config.TerragruntConfig { - assert.FileExists(t, fmt.Sprintf("%s/terragrunt.hcl", opts.WorkingDir)) + require.FileExists(t, fmt.Sprintf("%s/terragrunt.hcl", opts.WorkingDir)) opts, err := options.NewTerragruntOptionsForTest(filepath.Join(opts.WorkingDir, "terragrunt.hcl")) - assert.NoError(t, err) + require.NoError(t, err) cfg, err := config.ReadTerragruntConfig(context.Background(), opts, config.DefaultParserOptions(opts)) - assert.NoError(t, err) + require.NoError(t, err) return cfg } diff --git a/test/integration_debug_test.go b/test/integration_debug_test.go index 0451950bf..740bbb95d 100644 --- a/test/integration_debug_test.go +++ b/test/integration_debug_test.go @@ -46,7 +46,7 @@ func TestDebugGeneratedInputs(t *testing.T) { ) debugFile := util.JoinPath(rootPath, terragruntDebugFile) - assert.True(t, util.FileExists(debugFile)) + require.True(t, util.FileExists(debugFile)) require.Contains(t, stderr.String(), fmt.Sprintf("-chdir=\"%s\"", rootPath)) @@ -77,7 +77,7 @@ func TestDebugGeneratedInputs(t *testing.T) { var data map[string]interface{} require.NoError(t, json.Unmarshal(debugJsonContents, &data)) _, isDefined := data["undefined_var"] - assert.False(t, isDefined) + require.False(t, isDefined) } func TestTerragruntInputsWithDashes(t *testing.T) { @@ -203,13 +203,13 @@ func TestRenderJSONConfig(t *testing.T) { if assert.True(t, hasTerraform) { source, hasSource := terraformBlock.(map[string]interface{})["source"] require.True(t, hasSource) - assert.Equal(t, "./module", source) + require.Equal(t, "./module", source) } // Make sure included remote_state is rendered out remote_state, hasRemoteState := rendered["remote_state"] if assert.True(t, hasRemoteState) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "backend": "local", @@ -230,7 +230,7 @@ func TestRenderJSONConfig(t *testing.T) { // Make sure dependency blocks are rendered out dependencyBlocks, hasDependency := rendered["dependency"] if assert.True(t, hasDependency) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "dep": map[string]interface{}{ @@ -253,7 +253,7 @@ func TestRenderJSONConfig(t *testing.T) { // Make sure included generate block is rendered out generateBlocks, hasGenerate := rendered["generate"] if assert.True(t, hasGenerate) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "provider": map[string]interface{}{ @@ -276,7 +276,7 @@ func TestRenderJSONConfig(t *testing.T) { // Make sure all inputs are merged together inputsBlock, hasInputs := rendered["inputs"] if assert.True(t, hasInputs) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "env": "qa", @@ -315,13 +315,13 @@ func TestRenderJSONConfigWithIncludesDependenciesAndLocals(t *testing.T) { if assert.True(t, hasTerraform) { source, hasSource := terraformBlock.(map[string]interface{})["source"] require.True(t, hasSource) - assert.Equal(t, "./foo", source) + require.Equal(t, "./foo", source) } // Make sure top level locals are rendered out locals, hasLocals := rendered["locals"] if assert.True(t, hasLocals) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "foo": "bar", @@ -333,7 +333,7 @@ func TestRenderJSONConfigWithIncludesDependenciesAndLocals(t *testing.T) { // Make sure included dependency block is rendered out, and with the outputs rendered dependencyBlocks, hasDependency := rendered["dependency"] if assert.True(t, hasDependency) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "baz": map[string]interface{}{ @@ -356,7 +356,7 @@ func TestRenderJSONConfigWithIncludesDependenciesAndLocals(t *testing.T) { // Make sure generate block is rendered out generateBlocks, hasGenerate := rendered["generate"] if assert.True(t, hasGenerate) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "provider": map[string]interface{}{ @@ -376,7 +376,7 @@ func TestRenderJSONConfigWithIncludesDependenciesAndLocals(t *testing.T) { // Make sure all inputs are merged together inputsBlock, hasInputs := rendered["inputs"] if assert.True(t, hasInputs) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "foo": "bar", @@ -416,7 +416,7 @@ func TestRenderJSONConfigRunAll(t *testing.T) { // Make sure top level locals are rendered out bazLocals, bazHasLocals := bazRendered["locals"] if assert.True(t, bazHasLocals) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "self": "baz", @@ -434,7 +434,7 @@ func TestRenderJSONConfigRunAll(t *testing.T) { // Make sure top level locals are rendered out rootChildLocals, rootChildHasLocals := rootChildRendered["locals"] if assert.True(t, rootChildHasLocals) { - assert.Equal( + require.Equal( t, map[string]interface{}{ "foo": "bar", @@ -459,9 +459,9 @@ func TestDependencyGraphWithMultiInclude(t *testing.T) { ) stdoutStr := stdout.String() - assert.Contains(t, stdoutStr, `"main" -> "depa";`) - assert.Contains(t, stdoutStr, `"main" -> "depb";`) - assert.Contains(t, stdoutStr, `"main" -> "depc";`) + require.Contains(t, stdoutStr, `"main" -> "depa";`) + require.Contains(t, stdoutStr, `"main" -> "depb";`) + require.Contains(t, stdoutStr, `"main" -> "depc";`) } func runTerragruntValidateInputs(t *testing.T, moduleDir string, extraArgs []string, isSuccessTest bool) { diff --git a/test/integration_download_test.go b/test/integration_download_test.go index 9e6eed63e..cbc532dda 100644 --- a/test/integration_download_test.go +++ b/test/integration_download_test.go @@ -43,7 +43,7 @@ func TestLocalDownload(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", testFixtureLocalDownloadPath)) // As of Terraform 0.14.0 we should be copying the lock file from .terragrunt-cache to the working directory - assert.FileExists(t, util.JoinPath(testFixtureLocalDownloadPath, util.TerraformLockFile)) + require.FileExists(t, util.JoinPath(testFixtureLocalDownloadPath, util.TerraformLockFile)) // Run a second time to make sure the temporary folder can be reused without errors runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", testFixtureLocalDownloadPath)) @@ -80,7 +80,7 @@ func TestLocalDownloadWithAllowedHiddenFiles(t *testing.T) { logBufferContentsLineByLine(t, stdout, "output stdout") logBufferContentsLineByLine(t, stderr, "output stderr") require.NoError(t, err) - assert.Equal(t, "Hello world", stdout.String()) + require.Equal(t, "Hello world", stdout.String()) } func TestLocalDownloadWithRelativePath(t *testing.T) { @@ -130,7 +130,7 @@ func TestLocalWithMissingBackend(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), os.Stdout, os.Stderr) if assert.Error(t, err) { underlying := errors.Unwrap(err) - assert.IsType(t, terraform.BackendNotDefined{}, underlying) + require.IsType(t, terraform.BackendNotDefined{}, underlying) } } @@ -157,9 +157,9 @@ func TestInvalidRemoteDownload(t *testing.T) { logBufferContentsLineByLine(t, applyStdout, "apply stdout") logBufferContentsLineByLine(t, applyStderr, "apply stderr") - assert.Error(t, err) + require.Error(t, err) errMessage := "downloading source url" - assert.Containsf(t, err.Error(), errMessage, "expected error containing %q, got %s", errMessage, err) + require.Containsf(t, err.Error(), errMessage, "expected error containing %q, got %s", errMessage, err) } @@ -243,7 +243,7 @@ func TestCustomLockFile(t *testing.T) { // In our lock file, we intentionally have hashes for an older version of the AWS provider. If the lock file // copying works, then Terraform will stick with this older version. If there is a bug, Terraform will end up // installing a newer version (since the version is not pinned in the .tf code, only in the lock file). - assert.Contains(t, string(readFile), `version = "5.23.0"`) + require.Contains(t, string(readFile), `version = "5.23.0"`) } func TestExcludeDirs(t *testing.T) { @@ -302,10 +302,10 @@ func TestExcludeDirs(t *testing.T) { logBufferContentsLineByLine(t, showStdout, fmt.Sprintf("show stdout for %s", modulePath)) logBufferContentsLineByLine(t, showStderr, fmt.Sprintf("show stderr for %s", modulePath)) - assert.NoError(t, err) + require.NoError(t, err) output := showStdout.String() for _, excludedModuleOutput := range testCase.excludedModuleOutputs { - assert.NotContains(t, output, excludedModuleOutput) + require.NotContains(t, output, excludedModuleOutput) } } @@ -369,10 +369,10 @@ func TestIncludeDirs(t *testing.T) { logBufferContentsLineByLine(t, showStdout, fmt.Sprintf("show stdout for %s", modulePath)) logBufferContentsLineByLine(t, showStderr, fmt.Sprintf("show stderr for %s", modulePath)) - assert.NoError(t, err) + require.NoError(t, err) output := showStdout.String() for _, includedModuleOutput := range testCase.includedModuleOutputs { - assert.NotContains(t, output, includedModuleOutput) + require.NotContains(t, output, includedModuleOutput) } } @@ -395,13 +395,13 @@ func TestIncludeDirsDependencyConsistencyRegression(t *testing.T) { } includedModulesWithNone := runValidateAllWithIncludeAndGetIncludedModules(t, testPath, []string{}, false) - assert.Greater(t, len(includedModulesWithNone), 0) + require.NotEmpty(t, includedModulesWithNone) includedModulesWithAmzApp := runValidateAllWithIncludeAndGetIncludedModules(t, testPath, []string{"amazing-app/k8s"}, false) - assert.Equal(t, []string{"amazing-app/k8s", "clusters/eks"}, includedModulesWithAmzApp) + require.Equal(t, []string{"amazing-app/k8s", "clusters/eks"}, includedModulesWithAmzApp) includedModulesWithTestApp := runValidateAllWithIncludeAndGetIncludedModules(t, testPath, []string{"testapp/k8s"}, false) - assert.Equal(t, []string{"clusters/eks", "testapp/k8s"}, includedModulesWithTestApp) + require.Equal(t, []string{"clusters/eks", "testapp/k8s"}, includedModulesWithTestApp) } func TestIncludeDirsStrict(t *testing.T) { @@ -421,13 +421,13 @@ func TestIncludeDirsStrict(t *testing.T) { } includedModulesWithNone := runValidateAllWithIncludeAndGetIncludedModules(t, testPath, []string{}, true) - assert.Equal(t, []string{}, includedModulesWithNone) + require.Equal(t, []string{}, includedModulesWithNone) includedModulesWithAmzApp := runValidateAllWithIncludeAndGetIncludedModules(t, testPath, []string{"amazing-app/k8s"}, true) - assert.Equal(t, []string{"amazing-app/k8s"}, includedModulesWithAmzApp) + require.Equal(t, []string{"amazing-app/k8s"}, includedModulesWithAmzApp) includedModulesWithTestApp := runValidateAllWithIncludeAndGetIncludedModules(t, testPath, []string{"testapp/k8s"}, true) - assert.Equal(t, []string{"testapp/k8s"}, includedModulesWithTestApp) + require.Equal(t, []string{"testapp/k8s"}, includedModulesWithTestApp) } func TestTerragruntExternalDependencies(t *testing.T) { @@ -461,6 +461,6 @@ func TestTerragruntExternalDependencies(t *testing.T) { } for _, module := range modules { - assert.Contains(t, applyAllStdoutString, fmt.Sprintf("Hello World, %s", module)) + require.Contains(t, applyAllStdoutString, fmt.Sprintf("Hello World, %s", module)) } } diff --git a/test/integration_include_test.go b/test/integration_include_test.go index 8012676f6..7dc57607b 100644 --- a/test/integration_include_test.go +++ b/test/integration_include_test.go @@ -11,7 +11,6 @@ import ( "github.com/gruntwork-io/terragrunt/config" "github.com/gruntwork-io/terragrunt/util" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -56,7 +55,7 @@ func TestTerragruntWorksWithIncludeLocals(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, "us-west-1-test", outputs["region"].Value.(string)) + require.Equal(t, "us-west-1-test", outputs["region"].Value.(string)) }) } } @@ -114,9 +113,9 @@ func TestTerragruntRunAllModulesThatIncludeRestrictsSet(t *testing.T) { logBufferContentsLineByLine(t, stderr, "stderr") planOutput := stdout.String() - assert.Contains(t, planOutput, "alpha") - assert.NotContains(t, planOutput, "beta") - assert.NotContains(t, planOutput, "charlie") + require.Contains(t, planOutput, "alpha") + require.NotContains(t, planOutput, "beta") + require.NotContains(t, planOutput, "charlie") } func TestTerragruntRunAllModulesWithPrefix(t *testing.T) { @@ -142,20 +141,20 @@ func TestTerragruntRunAllModulesWithPrefix(t *testing.T) { logBufferContentsLineByLine(t, stderr, "stderr") planOutput := stdout.String() - assert.Contains(t, planOutput, "alpha") - assert.Contains(t, planOutput, "beta") - assert.Contains(t, planOutput, "charlie") + require.Contains(t, planOutput, "alpha") + require.Contains(t, planOutput, "beta") + require.Contains(t, planOutput, "charlie") stdoutLines := strings.Split(planOutput, "\n") for _, line := range stdoutLines { if strings.Contains(line, "alpha") { - assert.Contains(t, line, includeRunAllFixturePath+"a") + require.Contains(t, line, includeRunAllFixturePath+"a") } if strings.Contains(line, "beta") { - assert.Contains(t, line, includeRunAllFixturePath+"b") + require.Contains(t, line, includeRunAllFixturePath+"b") } if strings.Contains(line, "charlie") { - assert.Contains(t, line, includeRunAllFixturePath+"c") + require.Contains(t, line, includeRunAllFixturePath+"c") } } } @@ -176,13 +175,13 @@ func TestTerragruntWorksWithIncludeDeepMerge(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, "mock", outputs["attribute"].Value.(string)) - assert.Equal(t, "new val", outputs["new_attribute"].Value.(string)) - assert.Equal(t, "old val", outputs["old_attribute"].Value.(string)) - assert.Equal(t, []interface{}{"hello", "mock"}, outputs["list_attr"].Value.([]interface{})) - assert.Equal(t, map[string]interface{}{"foo": "bar", "bar": "baz", "test": "new val"}, outputs["map_attr"].Value.(map[string]interface{})) + require.Equal(t, "mock", outputs["attribute"].Value.(string)) + require.Equal(t, "new val", outputs["new_attribute"].Value.(string)) + require.Equal(t, "old val", outputs["old_attribute"].Value.(string)) + require.Equal(t, []interface{}{"hello", "mock"}, outputs["list_attr"].Value.([]interface{})) + require.Equal(t, map[string]interface{}{"foo": "bar", "bar": "baz", "test": "new val"}, outputs["map_attr"].Value.(map[string]interface{})) - assert.Equal( + require.Equal( t, map[string]interface{}{ "attribute": "mock", @@ -235,13 +234,13 @@ func TestTerragruntWorksWithMultipleInclude(t *testing.T) { } func validateMultipleIncludeTestOutput(t *testing.T, outputs map[string]TerraformOutput) { - assert.Equal(t, "mock", outputs["attribute"].Value.(string)) - assert.Equal(t, "new val", outputs["new_attribute"].Value.(string)) - assert.Equal(t, "old val", outputs["old_attribute"].Value.(string)) - assert.Equal(t, []interface{}{"hello", "mock", "foo"}, outputs["list_attr"].Value.([]interface{})) - assert.Equal(t, map[string]interface{}{"foo": "bar", "bar": "baz", "test": "new val"}, outputs["map_attr"].Value.(map[string]interface{})) + require.Equal(t, "mock", outputs["attribute"].Value.(string)) + require.Equal(t, "new val", outputs["new_attribute"].Value.(string)) + require.Equal(t, "old val", outputs["old_attribute"].Value.(string)) + require.Equal(t, []interface{}{"hello", "mock", "foo"}, outputs["list_attr"].Value.([]interface{})) + require.Equal(t, map[string]interface{}{"foo": "bar", "bar": "baz", "test": "new val"}, outputs["map_attr"].Value.(map[string]interface{})) - assert.Equal( + require.Equal( t, map[string]interface{}{ "attribute": "mock", @@ -267,9 +266,8 @@ func validateIncludeRemoteStateReflection(t *testing.T, s3BucketName string, key require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) remoteStateOut := map[string]interface{}{} require.NoError(t, json.Unmarshal([]byte(outputs["reflect"].Value.(string)), &remoteStateOut)) - assert.Equal( + require.Equal( t, - remoteStateOut, map[string]interface{}{ "backend": "s3", "disable_init": false, @@ -282,5 +280,6 @@ func validateIncludeRemoteStateReflection(t *testing.T, s3BucketName string, key "region": "us-west-2", }, }, + remoteStateOut, ) } diff --git a/test/integration_local_dev_test.go b/test/integration_local_dev_test.go index 48f1813bc..37758da1a 100644 --- a/test/integration_local_dev_test.go +++ b/test/integration_local_dev_test.go @@ -8,7 +8,6 @@ import ( "testing" "github.com/gruntwork-io/terragrunt/util" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -91,7 +90,7 @@ func TestGetTerragruntSourceHCL(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, fmt.Sprintf("HCL: %s", terraformSource), outputs["terragrunt_source"].Value) + require.Equal(t, fmt.Sprintf("HCL: %s", terraformSource), outputs["terragrunt_source"].Value) } func TestGetTerragruntSourceCLI(t *testing.T) { @@ -116,5 +115,5 @@ func TestGetTerragruntSourceCLI(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, fmt.Sprintf("CLI: %s", terraformSource), outputs["terragrunt_source"].Value) + require.Equal(t, fmt.Sprintf("CLI: %s", terraformSource), outputs["terragrunt_source"].Value) } diff --git a/test/integration_s3_encryption_test.go b/test/integration_s3_encryption_test.go index cf83cad67..2c0ffd768 100644 --- a/test/integration_s3_encryption_test.go +++ b/test/integration_s3_encryption_test.go @@ -44,7 +44,7 @@ func TestTerragruntS3SSEAES(t *testing.T) { client := terraws.NewS3Client(t, TERRAFORM_REMOTE_STATE_S3_REGION) resp, err := client.GetBucketEncryption(&s3.GetBucketEncryptionInput{Bucket: aws.String(s3BucketName)}) require.NoError(t, err) - require.Equal(t, 1, len(resp.ServerSideEncryptionConfiguration.Rules)) + require.Len(t, resp.ServerSideEncryptionConfiguration.Rules, 1) sseRule := resp.ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault require.NotNil(t, sseRule) assert.Equal(t, s3.ServerSideEncryptionAes256, aws.StringValue(sseRule.SSEAlgorithm)) @@ -71,7 +71,7 @@ func TestTerragruntS3SSECustomKey(t *testing.T) { client := terraws.NewS3Client(t, TERRAFORM_REMOTE_STATE_S3_REGION) resp, err := client.GetBucketEncryption(&s3.GetBucketEncryptionInput{Bucket: aws.String(s3BucketName)}) require.NoError(t, err) - require.Equal(t, 1, len(resp.ServerSideEncryptionConfiguration.Rules)) + require.Len(t, resp.ServerSideEncryptionConfiguration.Rules, 1) sseRule := resp.ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault require.NotNil(t, sseRule) assert.Equal(t, s3.ServerSideEncryptionAwsKms, aws.StringValue(sseRule.SSEAlgorithm)) @@ -108,7 +108,7 @@ func TestTerragruntS3SSEKeyNotReverted(t *testing.T) { client := terraws.NewS3Client(t, TERRAFORM_REMOTE_STATE_S3_REGION) resp, err := client.GetBucketEncryption(&s3.GetBucketEncryptionInput{Bucket: aws.String(s3BucketName)}) require.NoError(t, err) - require.Equal(t, 1, len(resp.ServerSideEncryptionConfiguration.Rules)) + require.Len(t, resp.ServerSideEncryptionConfiguration.Rules, 1) sseRule := resp.ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault require.NotNil(t, sseRule) assert.Equal(t, s3.ServerSideEncryptionAwsKms, aws.StringValue(sseRule.SSEAlgorithm)) @@ -142,7 +142,7 @@ func TestTerragruntS3EncryptionWarning(t *testing.T) { client := terraws.NewS3Client(t, TERRAFORM_REMOTE_STATE_S3_REGION) resp, err := client.GetBucketEncryption(&s3.GetBucketEncryptionInput{Bucket: aws.String(s3BucketName)}) require.NoError(t, err) - require.Equal(t, 1, len(resp.ServerSideEncryptionConfiguration.Rules)) + require.Len(t, resp.ServerSideEncryptionConfiguration.Rules, 1) sseRule := resp.ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault require.NotNil(t, sseRule) assert.Equal(t, s3.ServerSideEncryptionAwsKms, aws.StringValue(sseRule.SSEAlgorithm)) diff --git a/test/integration_scaffold_test.go b/test/integration_scaffold_test.go index 1461cd87d..1e3bd38a5 100644 --- a/test/integration_scaffold_test.go +++ b/test/integration_scaffold_test.go @@ -6,8 +6,6 @@ import ( "path/filepath" "testing" - "github.com/stretchr/testify/assert" - "github.com/gruntwork-io/terragrunt/util" "github.com/stretchr/testify/require" @@ -184,11 +182,11 @@ func TestScaffold3rdPartyModule(t *testing.T) { require.NoError(t, err) tmpEnvPath := filepath.Join(tmpRoot, "app") err = os.MkdirAll(tmpEnvPath, 0755) - assert.NoError(t, err) + require.NoError(t, err) // create "root" terragrunt.hcl err = os.WriteFile(filepath.Join(tmpRoot, "terragrunt.hcl"), []byte(""), 0644) - assert.NoError(t, err) + require.NoError(t, err) _, stderr, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt --terragrunt-non-interactive --terragrunt-working-dir %s scaffold %s", tmpEnvPath, TEST_SCAFFOLD_3RD_PARTY_MODULE)) require.NoError(t, err) diff --git a/test/integration_serial_test.go b/test/integration_serial_test.go index b2b09d3fb..6f2cae32a 100644 --- a/test/integration_serial_test.go +++ b/test/integration_serial_test.go @@ -20,7 +20,6 @@ import ( "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/hclwrite" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" terragruntinfo "github.com/gruntwork-io/terragrunt/cli/commands/terragrunt-info" @@ -95,7 +94,7 @@ func TestTerragruntProviderCacheWithFilesystemMirror(t *testing.T) { require.NoError(t, err) terraformrc := strings.Join(strings.Fields(string(terraformrcBytes)), " ") - assert.Contains(t, terraformrc, expectedProviderInstallation, "%s\n\n%s", terraformrc, expectedProviderInstallation) + require.Contains(t, terraformrc, expectedProviderInstallation, "%s\n\n%s", terraformrc, expectedProviderInstallation) } func TestTerragruntProviderCacheWithNetworkMirror(t *testing.T) { @@ -192,7 +191,7 @@ func TestTerragruntProviderCacheWithNetworkMirror(t *testing.T) { require.NoError(t, err) terraformrc := strings.Join(strings.Fields(string(terraformrcBytes)), " ") - assert.Contains(t, terraformrc, expectedProviderInstallation, "%s\n\n%s", terraformrc, expectedProviderInstallation) + require.Contains(t, terraformrc, expectedProviderInstallation, "%s\n\n%s", terraformrc, expectedProviderInstallation) } func TestTerragruntInputsFromDependency(t *testing.T) { @@ -241,7 +240,7 @@ func TestTerragruntInputsFromDependency(t *testing.T) { if testCase.downloadDir != "" { entries, err := os.ReadDir(testCase.downloadDir) require.NoError(t, err) - assert.Equal(t, len(appDirs), len(entries)) + require.Equal(t, len(appDirs), len(entries)) } runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt output --terragrunt-non-interactive --terragrunt-working-dir %s --terragrunt-download-dir=%s", appDir, testCase.downloadDir), &stdout, &stderr) @@ -254,7 +253,7 @@ func TestTerragruntInputsFromDependency(t *testing.T) { output := stdout.String() for key, value := range expectedOutpus { - assert.Contains(t, output, fmt.Sprintf("%s = %q\n", key, value)) + require.Contains(t, output, fmt.Sprintf("%s = %q\n", key, value)) } } } @@ -330,9 +329,9 @@ func TestTerragruntDownloadDir(t *testing.T) { var dat terragruntinfo.TerragruntInfoGroup err_unmarshal := json.Unmarshal(stdout.Bytes(), &dat) - assert.NoError(t, err_unmarshal) + require.NoError(t, err_unmarshal) // compare the results - assert.Equal(t, testCase.downloadDirReference, dat.DownloadDir) + require.Equal(t, testCase.downloadDirReference, dat.DownloadDir) }) } @@ -368,7 +367,7 @@ func TestExtraArguments(t *testing.T) { out := new(bytes.Buffer) runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", TEST_FIXTURE_EXTRA_ARGS_PATH), out, os.Stderr) t.Log(out.String()) - assert.Contains(t, out.String(), "Hello, World from dev!") + require.Contains(t, out.String(), "Hello, World from dev!") } func TestExtraArgumentsWithEnv(t *testing.T) { @@ -376,14 +375,14 @@ func TestExtraArgumentsWithEnv(t *testing.T) { t.Setenv("TF_VAR_env", "prod") runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", TEST_FIXTURE_EXTRA_ARGS_PATH), out, os.Stderr) t.Log(out.String()) - assert.Contains(t, out.String(), "Hello, World!") + require.Contains(t, out.String(), "Hello, World!") } func TestExtraArgumentsWithEnvVarBlock(t *testing.T) { out := new(bytes.Buffer) runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", TEST_FIXTURE_ENV_VARS_BLOCK_PATH), out, os.Stderr) t.Log(out.String()) - assert.Contains(t, out.String(), "I'm set in extra_arguments env_vars") + require.Contains(t, out.String(), "I'm set in extra_arguments env_vars") } func TestExtraArgumentsWithRegion(t *testing.T) { @@ -391,7 +390,7 @@ func TestExtraArgumentsWithRegion(t *testing.T) { t.Setenv("TF_VAR_region", "us-west-2") runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", TEST_FIXTURE_EXTRA_ARGS_PATH), out, os.Stderr) t.Log(out.String()) - assert.Contains(t, out.String(), "Hello, World from Oregon!") + require.Contains(t, out.String(), "Hello, World from Oregon!") } func TestPreserveEnvVarApplyAll(t *testing.T) { @@ -412,7 +411,7 @@ func TestPreserveEnvVarApplyAll(t *testing.T) { stdout := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt output text -no-color --terragrunt-non-interactive --terragrunt-working-dir %s", mod), &stdout, os.Stderr) require.NoError(t, err) - assert.Contains(t, stdout.String(), "Hello from the env") + require.Contains(t, stdout.String(), "Hello from the env") } } @@ -423,7 +422,7 @@ func TestPriorityOrderOfArgument(t *testing.T) { t.Log(out.String()) // And the result value for test should be the injected variable since the injected arguments are injected before the suplied parameters, // so our override of extra_var should be the last argument. - assert.Contains(t, out.String(), fmt.Sprintf(`test = "%s"`, injectedValue)) + require.Contains(t, out.String(), fmt.Sprintf(`test = "%s"`, injectedValue)) } func TestTerragruntValidateInputsWithEnvVar(t *testing.T) { @@ -480,7 +479,7 @@ func TestTerragruntLogLevelEnvVarOverridesDefault(t *testing.T) { runTerragruntCommand(t, fmt.Sprintf("terragrunt validate --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr), ) output := stderr.String() - assert.Contains(t, output, "level=debug") + require.Contains(t, output, "level=debug") } func TestTerragruntLogLevelEnvVarUnparsableLogsErrorButContinues(t *testing.T) { @@ -510,7 +509,7 @@ func testTerragruntParallelism(t *testing.T, parallelism int, numberOfModules in require.NoError(t, err) matches := regex.FindAllStringSubmatch(output, -1) - require.Equal(t, numberOfModules, len(matches)) + require.Len(t, matches, numberOfModules) var deploymentTimes []int for _, match := range matches { @@ -540,7 +539,7 @@ func testTerragruntParallelism(t *testing.T, parallelism int, numberOfModules in maxDiffInSeconds := 5.0 * scalingFactor for i, scaledTime := range scaledTimes { difference := math.Abs(scaledTime - float64(expectedTimings[i])) - require.True(t, difference <= maxDiffInSeconds, "Expected timing %d but got %f", expectedTimings[i], scaledTime) + require.LessOrEqual(t, difference, maxDiffInSeconds, "Expected timing %d but got %f", expectedTimings[i], scaledTime) } } @@ -593,7 +592,7 @@ func TestTerragruntWorksWithImpersonateGCSBackend(t *testing.T) { break } } - assert.True(t, ownerEmail, "Identity email should match the impersonated account") + require.True(t, ownerEmail, "Identity email should match the impersonated account") } func TestTerragruntProduceTelemetryTraces(t *testing.T) { @@ -604,13 +603,13 @@ func TestTerragruntProduceTelemetryTraces(t *testing.T) { rootPath := util.JoinPath(tmpEnvPath, TEST_FIXTURE_HOOKS_BEFORE_AND_AFTER_PATH) output, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) - assert.NoError(t, err) + require.NoError(t, err) // check that output have Telemetry json output - assert.Contains(t, output, "\"SpanContext\":") - assert.Contains(t, output, "\"TraceID\":") - assert.Contains(t, output, "\"Name\":\"hook_after_hook_1\"") - assert.Contains(t, output, "\"Name\":\"hook_after_hook_2\"") + require.Contains(t, output, "\"SpanContext\":") + require.Contains(t, output, "\"TraceID\":") + require.Contains(t, output, "\"Name\":\"hook_after_hook_1\"") + require.Contains(t, output, "\"Name\":\"hook_after_hook_2\"") } func TestTerragruntProduceTelemetryMetrics(t *testing.T) { @@ -621,15 +620,15 @@ func TestTerragruntProduceTelemetryMetrics(t *testing.T) { rootPath := util.JoinPath(tmpEnvPath, TEST_FIXTURE_HOOKS_BEFORE_AND_AFTER_PATH) output, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt apply -no-color -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) - assert.NoError(t, err) + require.NoError(t, err) // sleep for a bit to allow the metrics to be flushed time.Sleep(1 * time.Second) // check that output have Telemetry json output - assert.Contains(t, output, "{\"Name\":\"hook_after_hook_2_duration\"") - assert.Contains(t, output, "{\"Name\":\"run_") - assert.Contains(t, output, ",\"IsMonotonic\":true}}") + require.Contains(t, output, "{\"Name\":\"hook_after_hook_2_duration\"") + require.Contains(t, output, "{\"Name\":\"run_") + require.Contains(t, output, ",\"IsMonotonic\":true}}") } func TestTerragruntOutputJson(t *testing.T) { @@ -643,7 +642,7 @@ func TestTerragruntOutputJson(t *testing.T) { testPath := util.JoinPath(tmpEnvPath, TEST_FIXTURE_NOT_EXISTING_SOURCE) _, stderr, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt apply --terragrunt-json-log --terragrunt-non-interactive --terragrunt-working-dir %s", testPath)) - assert.Error(t, err) + require.Error(t, err) var msgs []string @@ -659,14 +658,14 @@ func TestTerragruntOutputJson(t *testing.T) { var output map[string]interface{} err = json.Unmarshal(jsonBytes, &output) - assert.NoError(t, err) + require.NoError(t, err) msg, ok := output["msg"].(string) - assert.True(t, ok) + require.True(t, ok) msgs = append(msgs, msg) } - assert.Contains(t, strings.Join(msgs, ""), "Downloading Terraform configurations from git::https://github.com/gruntwork-io/terragrunt.git?ref=v0.9.9") + require.Contains(t, strings.Join(msgs, ""), "Downloading Terraform configurations from git::https://github.com/gruntwork-io/terragrunt.git?ref=v0.9.9") } func TestTerragruntTerraformOutputJson(t *testing.T) { @@ -680,9 +679,9 @@ func TestTerragruntTerraformOutputJson(t *testing.T) { testPath := util.JoinPath(tmpEnvPath, TEST_FIXTURE_INIT_ERROR) _, stderr, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt apply --no-color --terragrunt-json-log --terragrunt-tf-logs-to-json --terragrunt-non-interactive --terragrunt-working-dir %s", testPath)) - assert.Error(t, err) + require.Error(t, err) - assert.Contains(t, stderr, "\"level\":\"info\",\"msg\":\"Initializing the backend...") + require.Contains(t, stderr, "\"level\":\"info\",\"msg\":\"Initializing the backend...") // check if output can be extracted in json jsonStrings := strings.Split(stderr, "\n") @@ -692,9 +691,9 @@ func TestTerragruntTerraformOutputJson(t *testing.T) { } var output map[string]interface{} err = json.Unmarshal([]byte(jsonString), &output) - assert.NoErrorf(t, err, "Failed to parse json %s", jsonString) - assert.NotNil(t, output["level"]) - assert.NotNil(t, output["time"]) + require.NoErrorf(t, err, "Failed to parse json %s", jsonString) + require.NotNil(t, output["level"]) + require.NotNil(t, output["time"]) } } @@ -719,12 +718,12 @@ func TestTerragruntOutputFromDependencyLogsJson(t *testing.T) { // apply dependency first dependencyTerragruntConfigPath := util.JoinPath(rootTerragruntPath, "dependency") _, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s ", dependencyTerragruntConfigPath)) - assert.NoError(t, err) + require.NoError(t, err) appTerragruntConfigPath := util.JoinPath(rootTerragruntPath, "app") stdout, stderr, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s %s", appTerragruntConfigPath, testCase.arg)) - assert.NoError(t, err) + require.NoError(t, err) output := fmt.Sprintf("%s %s", stderr, stdout) - assert.NotContains(t, output, "invalid character") + require.NotContains(t, output, "invalid character") }) } @@ -751,19 +750,19 @@ func TestTerragruntJsonPlanJsonOutput(t *testing.T) { require.NoError(t, err) list, err := findFilesWithExtension(tmpDir, ".json") require.NoError(t, err) - assert.Equal(t, 2, len(list)) + require.Len(t, list, 2) for _, file := range list { - assert.Equal(t, "tfplan.json", filepath.Base(file)) + require.Equal(t, "tfplan.json", filepath.Base(file)) // verify that file is not empty content, err := os.ReadFile(file) require.NoError(t, err) - assert.NotEmpty(t, content) + require.NotEmpty(t, content) // check that produced json is valid and can be unmarshalled var plan map[string]interface{} err = json.Unmarshal(content, &plan) require.NoError(t, err) // check that plan is not empty - assert.NotEmpty(t, plan) + require.NotEmpty(t, plan) } }) @@ -779,15 +778,15 @@ func TestTerragruntProduceTelemetryTracesWithRootSpanAndTraceID(t *testing.T) { rootPath := util.JoinPath(tmpEnvPath, TEST_FIXTURE_HOOKS_BEFORE_AND_AFTER_PATH) output, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) - assert.NoError(t, err) + require.NoError(t, err) // check that output have Telemetry json output - assert.Contains(t, output, "\"SpanContext\":{\"TraceID\":\"b2ff2d54551433d53dd807a6c94e81d1\"") - assert.Contains(t, output, "\"SpanID\":\"0e6f631d793c718a\"") - assert.Contains(t, output, "\"SpanContext\":") - assert.Contains(t, output, "\"TraceID\":") - assert.Contains(t, output, "\"Name\":\"hook_after_hook_1\"") - assert.Contains(t, output, "\"Name\":\"hook_after_hook_2\"") + require.Contains(t, output, "\"SpanContext\":{\"TraceID\":\"b2ff2d54551433d53dd807a6c94e81d1\"") + require.Contains(t, output, "\"SpanID\":\"0e6f631d793c718a\"") + require.Contains(t, output, "\"SpanContext\":") + require.Contains(t, output, "\"TraceID\":") + require.Contains(t, output, "\"Name\":\"hook_after_hook_1\"") + require.Contains(t, output, "\"Name\":\"hook_after_hook_2\"") } func TestTerragruntProduceTelemetryInCasOfError(t *testing.T) { @@ -801,10 +800,10 @@ func TestTerragruntProduceTelemetryInCasOfError(t *testing.T) { output, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt no-existing-command -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) require.Error(t, err) - assert.Contains(t, output, "\"SpanContext\":{\"TraceID\":\"b2ff2d54551433d53dd807a6c94e81d1\"") - assert.Contains(t, output, "\"SpanID\":\"0e6f631d793c718a\"") - assert.Contains(t, output, "exception.message") - assert.Contains(t, output, "\"Name\":\"exception\"") + require.Contains(t, output, "\"SpanContext\":{\"TraceID\":\"b2ff2d54551433d53dd807a6c94e81d1\"") + require.Contains(t, output, "\"SpanID\":\"0e6f631d793c718a\"") + require.Contains(t, output, "exception.message") + require.Contains(t, output, "\"Name\":\"exception\"") } // Since this test launches a large number of terraform processes, which sometimes fails with the message `Failed to write to log, write |1: file already closed`, for stability, we need to run it not parallel. @@ -820,11 +819,11 @@ func TestTerragruntProviderCache(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt run-all init --terragrunt-provider-cache --terragrunt-provider-cache-dir %s --terragrunt-log-level trace --terragrunt-non-interactive --terragrunt-working-dir %s", providerCacheDir, rootPath)) providers := map[string][]string{ - "first": []string{ + "first": { "hashicorp/aws/5.36.0", "hashicorp/azurerm/3.95.0", }, - "second": []string{ + "second": { "hashicorp/aws/5.40.0", "hashicorp/azurerm/3.95.0", "hashicorp/kubernetes/2.27.0", @@ -870,30 +869,30 @@ func TestTerragruntProviderCache(t *testing.T) { ) providerBlock := lockfile.Body().FirstMatchingBlock("provider", []string{filepath.Dir(provider)}) - assert.NotNil(t, providerBlock) + require.NotNil(t, providerBlock) providerPath := filepath.Join(appPath, ".terraform/providers", provider) - assert.True(t, util.FileExists(providerPath)) + require.True(t, util.FileExists(providerPath)) entries, err := os.ReadDir(providerPath) - assert.NoError(t, err) + require.NoError(t, err) for _, entry := range entries { actualProviderSymlinks++ - assert.Equal(t, fs.ModeSymlink, entry.Type()) + require.Equal(t, fs.ModeSymlink, entry.Type()) symlinkPath := filepath.Join(providerPath, entry.Name()) actualPath, err := os.Readlink(symlinkPath) - assert.NoError(t, err) + require.NoError(t, err) expectedPath := filepath.Join(providerCacheDir, provider, entry.Name()) - assert.Contains(t, actualPath, expectedPath) + require.Contains(t, actualPath, expectedPath) } - assert.Equal(t, expectedProviderSymlinks, actualProviderSymlinks) + require.Equal(t, expectedProviderSymlinks, actualProviderSymlinks) } } - assert.Equal(t, expectedApps, actualApps) + require.Equal(t, expectedApps, actualApps) } } diff --git a/test/integration_test.go b/test/integration_test.go index 7a79aebc9..0095edfd2 100644 --- a/test/integration_test.go +++ b/test/integration_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + goErrors "errors" "fmt" "io" "math/rand" @@ -247,7 +248,7 @@ func TestTerragruntExcludesFile(t *testing.T) { require.NoError(t, err) actualOutput := strings.Split(strings.TrimSpace(stdout), "\n") - assert.ElementsMatch(t, testCase.expectedOutput, actualOutput) + require.ElementsMatch(t, testCase.expectedOutput, actualOutput) }) } } @@ -292,7 +293,7 @@ func TestHclvalidateDiagnostic(t *testing.T) { StartLine: 6, HighlightStartOffset: 18, HighlightEndOffset: 26, - Values: []diagnostic.ExpressionValue{diagnostic.ExpressionValue{Traversal: "dependency.a", Statement: "is object with no attributes"}}, + Values: []diagnostic.ExpressionValue{{Traversal: "dependency.a", Statement: "is object with no attributes"}}, }, }, &diagnostic.Diagnostic{ @@ -356,7 +357,7 @@ func TestHclvalidateDiagnostic(t *testing.T) { err = json.Unmarshal([]byte(strings.TrimSpace(stdout)), &actualDiags) require.NoError(t, err) - assert.ElementsMatch(t, expectedDiags, actualDiags) + require.ElementsMatch(t, expectedDiags, actualDiags) } func TestHclvalidateInvalidConfigPath(t *testing.T) { @@ -377,7 +378,7 @@ func TestHclvalidateInvalidConfigPath(t *testing.T) { err = json.Unmarshal([]byte(strings.TrimSpace(stdout)), &actualPaths) require.NoError(t, err) - assert.ElementsMatch(t, expectedPaths, actualPaths) + require.ElementsMatch(t, expectedPaths, actualPaths) } func TestTerragruntProviderCacheMultiplePlatforms(t *testing.T) { @@ -414,7 +415,7 @@ func TestTerragruntProviderCacheMultiplePlatforms(t *testing.T) { for _, appName := range []string{"app1", "app2", "app3"} { appPath := filepath.Join(rootPath, appName) - assert.True(t, util.FileExists(appPath)) + require.True(t, util.FileExists(appPath)) lockfilePath := filepath.Join(appPath, ".terraform.lock.hcl") lockfileContent, err := os.ReadFile(lockfilePath) @@ -428,14 +429,14 @@ func TestTerragruntProviderCacheMultiplePlatforms(t *testing.T) { provider := path.Join(registryName, provider) providerBlock := lockfile.Body().FirstMatchingBlock("provider", []string{filepath.Dir(provider)}) - assert.NotNil(t, providerBlock) + require.NotNil(t, providerBlock) providerPath := filepath.Join(providerCacheDir, provider) - assert.True(t, util.FileExists(providerPath)) + require.True(t, util.FileExists(providerPath)) for _, platform := range platforms { platformPath := filepath.Join(providerPath, platform) - assert.True(t, util.FileExists(platformPath)) + require.True(t, util.FileExists(platformPath)) } } } @@ -449,7 +450,7 @@ func TestTerragruntInitOnce(t *testing.T) { stdout, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) require.NoError(t, err) - assert.Contains(t, stdout, "Initializing modules") + require.Contains(t, stdout, "Initializing modules") // update the config creation time without changing content cfgPath := filepath.Join(rootPath, "terragrunt.hcl") @@ -460,7 +461,7 @@ func TestTerragruntInitOnce(t *testing.T) { stdout, _, err = runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) require.NoError(t, err) - assert.NotContains(t, stdout, "Initializing modules", "init command executed more than once") + require.NotContains(t, stdout, "Initializing modules", "init command executed more than once") } func TestTerragruntDestroyOrder(t *testing.T) { @@ -473,8 +474,8 @@ func TestTerragruntDestroyOrder(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt run-all apply --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) stdout, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt run-all destroy --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) - assert.NoError(t, err) - assert.Regexp(t, regexp.MustCompile(`(?smi)(?:(Module E|Module D|Module B).*){3}(?:(Module A|Module C).*){2}`), stdout) + require.NoError(t, err) + require.Regexp(t, regexp.MustCompile(`(?smi)(?:(Module E|Module D|Module B).*){3}(?:(Module A|Module C).*){2}`), stdout) } func TestTerragruntApplyDestroyOrder(t *testing.T) { @@ -487,8 +488,8 @@ func TestTerragruntApplyDestroyOrder(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt run-all apply --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) stdout, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt run-all apply -destroy --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) - assert.NoError(t, err) - assert.Regexp(t, regexp.MustCompile(`(?smi)(?:(Module E|Module D|Module B).*){3}(?:(Module A|Module C).*){2}`), stdout) + require.NoError(t, err) + require.Regexp(t, regexp.MustCompile(`(?smi)(?:(Module E|Module D|Module B).*){3}(?:(Module A|Module C).*){2}`), stdout) } func TestTerragruntInitHookNoSourceNoBackend(t *testing.T) { @@ -510,9 +511,9 @@ func TestTerragruntInitHookNoSourceNoBackend(t *testing.T) { t.Errorf("Did not expect to get error: %s", err.Error()) } - assert.Equal(t, 1, strings.Count(output, "AFTER_INIT_ONLY_ONCE"), "Hooks on init command executed more than once") + require.Equal(t, 1, strings.Count(output, "AFTER_INIT_ONLY_ONCE"), "Hooks on init command executed more than once") // With no source, `init-from-module` should not execute - assert.NotContains(t, output, "AFTER_INIT_FROM_MODULE_ONLY_ONCE", "Hooks on init-from-module command executed when no source was specified") + require.NotContains(t, output, "AFTER_INIT_FROM_MODULE_ONLY_ONCE", "Hooks on init-from-module command executed when no source was specified") } func TestTerragruntInitHookNoSourceWithBackend(t *testing.T) { @@ -540,9 +541,9 @@ func TestTerragruntInitHookNoSourceWithBackend(t *testing.T) { t.Errorf("Did not expect to get error: %s", err.Error()) } - assert.Equal(t, 1, strings.Count(output, "AFTER_INIT_ONLY_ONCE"), "Hooks on init command executed more than once") + require.Equal(t, 1, strings.Count(output, "AFTER_INIT_ONLY_ONCE"), "Hooks on init command executed more than once") // With no source, `init-from-module` should not execute - assert.NotContains(t, output, "AFTER_INIT_FROM_MODULE_ONLY_ONCE", "Hooks on init-from-module command executed when no source was specified") + require.NotContains(t, output, "AFTER_INIT_FROM_MODULE_ONLY_ONCE", "Hooks on init-from-module command executed when no source was specified") } func TestTerragruntInitHookWithSourceNoBackend(t *testing.T) { @@ -566,8 +567,8 @@ func TestTerragruntInitHookWithSourceNoBackend(t *testing.T) { t.Errorf("Did not expect to get error: %s", err.Error()) } - assert.Equal(t, 1, strings.Count(output, "AFTER_INIT_ONLY_ONCE\n"), "Hooks on init command executed more than once") - assert.Equal(t, 1, strings.Count(output, "AFTER_INIT_FROM_MODULE_ONLY_ONCE\n"), "Hooks on init-from-module command executed more than once") + require.Equal(t, 1, strings.Count(output, "AFTER_INIT_ONLY_ONCE\n"), "Hooks on init command executed more than once") + require.Equal(t, 1, strings.Count(output, "AFTER_INIT_FROM_MODULE_ONLY_ONCE\n"), "Hooks on init-from-module command executed more than once") } func TestTerragruntInitHookWithSourceWithBackend(t *testing.T) { @@ -597,9 +598,9 @@ func TestTerragruntInitHookWithSourceWithBackend(t *testing.T) { } // `init` hook should execute only once - assert.Equal(t, 1, strings.Count(output, "AFTER_INIT_ONLY_ONCE"), "Hooks on init command executed more than once") + require.Equal(t, 1, strings.Count(output, "AFTER_INIT_ONLY_ONCE"), "Hooks on init command executed more than once") // `init-from-module` hook should execute only once - assert.Equal(t, 1, strings.Count(output, "AFTER_INIT_FROM_MODULE_ONLY_ONCE"), "Hooks on init-from-module command executed more than once") + require.Equal(t, 1, strings.Count(output, "AFTER_INIT_FROM_MODULE_ONLY_ONCE"), "Hooks on init-from-module command executed more than once") } func TestTerragruntHookRunAllApply(t *testing.T) { @@ -614,9 +615,9 @@ func TestTerragruntHookRunAllApply(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt run-all apply -auto-approve --terragrunt-log-level debug --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) _, beforeErr := os.ReadFile(beforeOnlyPath + "/file.out") - assert.NoError(t, beforeErr) + require.NoError(t, beforeErr) _, afterErr := os.ReadFile(afterOnlyPath + "/file.out") - assert.NoError(t, afterErr) + require.NoError(t, afterErr) } func TestTerragruntHookApplyAll(t *testing.T) { @@ -631,9 +632,9 @@ func TestTerragruntHookApplyAll(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt apply-all -auto-approve --terragrunt-log-level debug --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) _, beforeErr := os.ReadFile(beforeOnlyPath + "/file.out") - assert.NoError(t, beforeErr) + require.NoError(t, beforeErr) _, afterErr := os.ReadFile(afterOnlyPath + "/file.out") - assert.NoError(t, afterErr) + require.NoError(t, afterErr) } func TestTerragruntBeforeHook(t *testing.T) { @@ -647,7 +648,7 @@ func TestTerragruntBeforeHook(t *testing.T) { _, exception := os.ReadFile(rootPath + "/file.out") - assert.NoError(t, exception) + require.NoError(t, exception) } func TestTerragruntHookWorkingDir(t *testing.T) { @@ -672,7 +673,7 @@ func TestTerragruntAfterHook(t *testing.T) { _, exception := os.ReadFile(rootPath + "/file.out") - assert.NoError(t, exception) + require.NoError(t, exception) } func TestTerragruntBeforeAndAfterHook(t *testing.T) { @@ -695,16 +696,16 @@ func TestTerragruntBeforeAndAfterHook(t *testing.T) { t.Errorf("Did not expect to get error: %s", err.Error()) } - assert.Equal(t, 0, strings.Count(output, "BEFORE_TERRAGRUNT_READ_CONFIG"), "terragrunt-read-config before_hook should not be triggered") + require.Equal(t, 0, strings.Count(output, "BEFORE_TERRAGRUNT_READ_CONFIG"), "terragrunt-read-config before_hook should not be triggered") t.Logf("output: %s", output) - assert.Equal(t, 1, strings.Count(output, "AFTER_TERRAGRUNT_READ_CONFIG"), "Hooks on terragrunt-read-config command executed more than once") + require.Equal(t, 1, strings.Count(output, "AFTER_TERRAGRUNT_READ_CONFIG"), "Hooks on terragrunt-read-config command executed more than once") expectedHookOutput := fmt.Sprintf("TF_PATH=%s COMMAND=terragrunt-read-config HOOK_NAME=after_hook_3", wrappedBinary()) - assert.Equal(t, 1, strings.Count(output, expectedHookOutput)) + require.Equal(t, 1, strings.Count(output, expectedHookOutput)) - assert.NoError(t, beforeException) - assert.NoError(t, afterException) + require.NoError(t, beforeException) + require.NoError(t, afterException) } func TestTerragruntBeforeAfterAndErrorMergeHook(t *testing.T) { @@ -722,7 +723,7 @@ func TestTerragruntBeforeAfterAndErrorMergeHook(t *testing.T) { stdout := bytes.Buffer{} stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-config %s --terragrunt-working-dir %s", tmpTerragruntConfigPath, childPath), &stdout, &stderr) - assert.ErrorContains(t, err, "executable file not found in $PATH") + require.ErrorContains(t, err, "executable file not found in $PATH") _, beforeException := os.ReadFile(childPath + "/before.out") _, beforeChildException := os.ReadFile(childPath + "/before-child.out") @@ -733,16 +734,16 @@ func TestTerragruntBeforeAfterAndErrorMergeHook(t *testing.T) { _, errorHookChildException := os.ReadFile(childPath + "/error-hook-child.out") _, errorHookOverridenParentException := os.ReadFile(childPath + "/error-hook-merge-parent.out") - assert.NoError(t, beforeException) - assert.NoError(t, beforeChildException) - assert.NoError(t, afterException) - assert.NoError(t, afterParentException) - assert.NoError(t, errorHookParentException) - assert.NoError(t, errorHookChildException) + require.NoError(t, beforeException) + require.NoError(t, beforeChildException) + require.NoError(t, afterException) + require.NoError(t, afterParentException) + require.NoError(t, errorHookParentException) + require.NoError(t, errorHookChildException) // PathError because no file found - assert.Error(t, beforeOverriddenParentException) - assert.Error(t, errorHookOverridenParentException) + require.Error(t, beforeOverriddenParentException) + require.Error(t, errorHookOverridenParentException) } func TestTerragruntSkipOnError(t *testing.T) { @@ -759,19 +760,19 @@ func TestTerragruntSkipOnError(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) output := stdout.String() - assert.Contains(t, output, "BEFORE_SHOULD_DISPLAY") - assert.NotContains(t, output, "BEFORE_NODISPLAY") + require.Contains(t, output, "BEFORE_SHOULD_DISPLAY") + require.NotContains(t, output, "BEFORE_NODISPLAY") - assert.Contains(t, output, "AFTER_SHOULD_DISPLAY") - assert.NotContains(t, output, "AFTER_NODISPLAY") + require.Contains(t, output, "AFTER_SHOULD_DISPLAY") + require.NotContains(t, output, "AFTER_NODISPLAY") - assert.Contains(t, output, "ERROR_HOOK_EXECUTED") - assert.NotContains(t, output, "NOT_MATCHING_ERROR_HOOK") - assert.Contains(t, output, "PATTERN_MATCHING_ERROR_HOOK") + require.Contains(t, output, "ERROR_HOOK_EXECUTED") + require.NotContains(t, output, "NOT_MATCHING_ERROR_HOOK") + require.Contains(t, output, "PATTERN_MATCHING_ERROR_HOOK") } func TestTerragruntCatchErrorsInTerraformExecution(t *testing.T) { @@ -788,13 +789,13 @@ func TestTerragruntCatchErrorsInTerraformExecution(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) output := stderr.String() - assert.Contains(t, output, "pattern_matching_hook") - assert.Contains(t, output, "catch_all_matching_hook") - assert.NotContains(t, output, "not_matching_hook") + require.Contains(t, output, "pattern_matching_hook") + require.Contains(t, output, "catch_all_matching_hook") + require.NotContains(t, output, "not_matching_hook") } @@ -816,7 +817,7 @@ func TestTerragruntBeforeOneArgAction(t *testing.T) { if err != nil { t.Error("Expected successful execution of terragrunt with 1 before hook execution.") } else { - assert.Contains(t, output, "Running command: date") + require.Contains(t, output, "Running command: date") } } @@ -835,7 +836,7 @@ func TestTerragruntEmptyStringCommandHook(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) if err != nil { - assert.Contains(t, err.Error(), "Need at least one non-empty argument in 'execute'.") + require.Contains(t, err.Error(), "Need at least one non-empty argument in 'execute'.") } else { t.Error("Expected an Error with message: 'Need at least one argument'") } @@ -856,7 +857,7 @@ func TestTerragruntEmptyCommandListHook(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) if err != nil { - assert.Contains(t, err.Error(), "Need at least one non-empty argument in 'execute'.") + require.Contains(t, err.Error(), "Need at least one non-empty argument in 'execute'.") } else { t.Error("Expected an Error with message: 'Need at least one argument'") } @@ -886,7 +887,7 @@ func TestTerragruntHookInterpolation(t *testing.T) { t.Errorf("Did not expect to get error: %s", err.Error()) } - assert.Contains(t, output, homePath) + require.Contains(t, output, homePath) } @@ -946,34 +947,34 @@ func TestTerragruntSetsAccessLoggingForTfSTateS3BuckeToADifferentBucketWithGiven targetLoggingBucket := terraws.GetS3BucketLoggingTarget(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) targetLoggingBucketPrefix := terraws.GetS3BucketLoggingTargetPrefix(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) - assert.Equal(t, s3BucketLogsName, targetLoggingBucket) - assert.Equal(t, s3BucketLogsTargetPrefix, targetLoggingBucketPrefix) + require.Equal(t, s3BucketLogsName, targetLoggingBucket) + require.Equal(t, s3BucketLogsTargetPrefix, targetLoggingBucketPrefix) encryptionConfig, err := bucketEncryption(t, TERRAFORM_REMOTE_STATE_S3_REGION, targetLoggingBucket) - assert.NoError(t, err) - assert.NotNil(t, encryptionConfig) - assert.NotNil(t, encryptionConfig.ServerSideEncryptionConfiguration) + require.NoError(t, err) + require.NotNil(t, encryptionConfig) + require.NotNil(t, encryptionConfig.ServerSideEncryptionConfiguration) for _, rule := range encryptionConfig.ServerSideEncryptionConfiguration.Rules { if rule.ApplyServerSideEncryptionByDefault != nil { if rule.ApplyServerSideEncryptionByDefault.SSEAlgorithm != nil { - assert.Equal(t, s3.ServerSideEncryptionAes256, *rule.ApplyServerSideEncryptionByDefault.SSEAlgorithm) + require.Equal(t, s3.ServerSideEncryptionAes256, *rule.ApplyServerSideEncryptionByDefault.SSEAlgorithm) } } } policy, err := bucketPolicy(t, TERRAFORM_REMOTE_STATE_S3_REGION, targetLoggingBucket) - assert.NoError(t, err) - assert.NotNil(t, policy.Policy) + require.NoError(t, err) + require.NotNil(t, policy.Policy) policyInBucket, err := aws_helper.UnmarshalPolicy(*policy.Policy) - assert.NoError(t, err) + require.NoError(t, err) enforceSSE := false for _, statement := range policyInBucket.Statement { if statement.Sid == remote.SidEnforcedTLSPolicy { enforceSSE = true } } - assert.True(t, enforceSSE) + require.True(t, enforceSSE) } // Regression test to ensure that `accesslogging_bucket_name` is taken into account @@ -1005,19 +1006,19 @@ func TestTerragruntSetsAccessLoggingForTfSTateS3BuckeToADifferentBucketWithDefau targetLoggingBucketPrefix := terraws.GetS3BucketLoggingTargetPrefix(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) encryptionConfig, err := bucketEncryption(t, TERRAFORM_REMOTE_STATE_S3_REGION, targetLoggingBucket) - assert.NoError(t, err) - assert.NotNil(t, encryptionConfig) - assert.NotNil(t, encryptionConfig.ServerSideEncryptionConfiguration) + require.NoError(t, err) + require.NotNil(t, encryptionConfig) + require.NotNil(t, encryptionConfig.ServerSideEncryptionConfiguration) for _, rule := range encryptionConfig.ServerSideEncryptionConfiguration.Rules { if rule.ApplyServerSideEncryptionByDefault != nil { if rule.ApplyServerSideEncryptionByDefault.SSEAlgorithm != nil { - assert.Equal(t, s3.ServerSideEncryptionAes256, *rule.ApplyServerSideEncryptionByDefault.SSEAlgorithm) + require.Equal(t, s3.ServerSideEncryptionAes256, *rule.ApplyServerSideEncryptionByDefault.SSEAlgorithm) } } } - assert.Equal(t, s3BucketLogsName, targetLoggingBucket) - assert.Equal(t, remote.DefaultS3BucketAccessLoggingTargetPrefix, targetLoggingBucketPrefix) + require.Equal(t, s3BucketLogsName, targetLoggingBucket) + require.Equal(t, remote.DefaultS3BucketAccessLoggingTargetPrefix, targetLoggingBucketPrefix) } func TestTerragruntWorksWithGCSBackend(t *testing.T) { @@ -1085,9 +1086,9 @@ func TestTerragruntWorksWithNonDefaultConfigNamesAndRunAllCommand(t *testing.T) require.NoError(t, err) out := stdout.String() - assert.Equal(t, 1, strings.Count(out, "parent_hcl_file")) - assert.Equal(t, 1, strings.Count(out, "dependency_hcl")) - assert.Equal(t, 1, strings.Count(out, "common_hcl")) + require.Equal(t, 1, strings.Count(out, "parent_hcl_file")) + require.Equal(t, 1, strings.Count(out, "dependency_hcl")) + require.Equal(t, 1, strings.Count(out, "common_hcl")) } func TestTerragruntWorksWithNonDefaultConfigNames(t *testing.T) { @@ -1103,9 +1104,9 @@ func TestTerragruntWorksWithNonDefaultConfigNames(t *testing.T) { require.NoError(t, err) out := stdout.String() - assert.Equal(t, 1, strings.Count(out, "parent_hcl_file")) - assert.Equal(t, 1, strings.Count(out, "dependency_hcl")) - assert.Equal(t, 1, strings.Count(out, "common_hcl")) + require.Equal(t, 1, strings.Count(out, "parent_hcl_file")) + require.Equal(t, 1, strings.Count(out, "dependency_hcl")) + require.Equal(t, 1, strings.Count(out, "common_hcl")) } func TestTerragruntReportsTerraformErrorsWithPlanAll(t *testing.T) { @@ -1127,8 +1128,8 @@ func TestTerragruntReportsTerraformErrorsWithPlanAll(t *testing.T) { output := stdout.String() errOutput := stderr.String() fmt.Printf("STDERR is %s.\n STDOUT is %s", errOutput, output) - assert.True(t, strings.Contains(errOutput, "missingvar1") || strings.Contains(output, "missingvar1")) - assert.True(t, strings.Contains(errOutput, "missingvar2") || strings.Contains(output, "missingvar2")) + require.True(t, strings.Contains(errOutput, "missingvar1") || strings.Contains(output, "missingvar1")) + require.True(t, strings.Contains(errOutput, "missingvar2") || strings.Contains(output, "missingvar2")) } func TestTerragruntGraphDependenciesCommand(t *testing.T) { @@ -1150,7 +1151,7 @@ func TestTerragruntGraphDependenciesCommand(t *testing.T) { ) runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt graph-dependencies --terragrunt-working-dir %s", environmentPath), &stdout, &stderr) output := stdout.String() - assert.True(t, strings.Contains(output, strings.TrimSpace(` + require.True(t, strings.Contains(output, strings.TrimSpace(` digraph { "backend-app" ; "backend-app" -> "mysql"; @@ -1206,11 +1207,11 @@ func TestTerragruntOutputAllCommand(t *testing.T) { runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt output-all --terragrunt-non-interactive --terragrunt-working-dir %s", environmentPath), &stdout, &stderr) output := stdout.String() - assert.True(t, strings.Contains(output, "app1 output")) - assert.True(t, strings.Contains(output, "app2 output")) - assert.True(t, strings.Contains(output, "app3 output")) + require.True(t, strings.Contains(output, "app1 output")) + require.True(t, strings.Contains(output, "app2 output")) + require.True(t, strings.Contains(output, "app3 output")) - assert.True(t, (strings.Index(output, "app3 output") < strings.Index(output, "app1 output")) && (strings.Index(output, "app1 output") < strings.Index(output, "app2 output"))) + require.True(t, (strings.Index(output, "app3 output") < strings.Index(output, "app1 output")) && (strings.Index(output, "app1 output") < strings.Index(output, "app2 output"))) } func TestTerragruntOutputFromDependency(t *testing.T) { @@ -1234,10 +1235,10 @@ func TestTerragruntOutputFromDependency(t *testing.T) { t.Setenv("AWS_CSM_ENABLED", "true") err := runTerragruntCommand(t, fmt.Sprintf("terragrunt run-all apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s --terragrunt-log-level debug", rootTerragruntPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) output := stderr.String() - assert.NotContains(t, output, "invalid character") + require.NotContains(t, output, "invalid character") } func TestTerragruntValidateAllCommand(t *testing.T) { @@ -1269,7 +1270,7 @@ func TestTerragruntStdOut(t *testing.T) { runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt output foo --terragrunt-non-interactive --terragrunt-working-dir %s", TEST_FIXTURE_STDOUT), &stdout, &stderr) output := stdout.String() - assert.Equal(t, "\"foo\"\n", output) + require.Equal(t, "\"foo\"\n", output) } func TestTerragruntOutputAllCommandSpecificVariableIgnoreDependencyErrors(t *testing.T) { @@ -1299,7 +1300,7 @@ func TestTerragruntOutputAllCommandSpecificVariableIgnoreDependencyErrors(t *tes logBufferContentsLineByLine(t, stderr, "output-all stderr") // Without --terragrunt-ignore-dependency-errors, app2 never runs because its dependencies have "errors" since they don't have the output "app2_text". - assert.True(t, strings.Contains(output, "app2 output")) + require.True(t, strings.Contains(output, "app2 output")) } func testRemoteFixtureParallelism(t *testing.T, parallelism int, numberOfModules int, timeToDeployEachModule time.Duration) (string, int, error) { @@ -1382,7 +1383,7 @@ func TestTerragruntStackCommandsWithPlanFile(t *testing.T) { t.Parallel() tmpEnvPath, err := filepath.EvalSymlinks(copyEnvironment(t, TEST_FIXTURE_DISJOINT)) - assert.NoError(t, err) + require.NoError(t, err) disjointEnvironmentPath := util.JoinPath(tmpEnvPath, TEST_FIXTURE_DISJOINT) cleanupTerraformFolder(t, disjointEnvironmentPath) @@ -1401,8 +1402,11 @@ func TestInvalidSource(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init --terragrunt-working-dir %s", generateTestCase), &stdout, &stderr) require.Error(t, err) - _, ok := errors.Unwrap(err).(terraform.WorkingDirNotFound) - assert.True(t, ok) + + var workingDirNotFoundErr terraform.WorkingDirNotFound + // _, ok := errors.Unwrap(err).(terraform.WorkingDirNotFound) + ok := goErrors.As(err, &workingDirNotFoundErr) + require.True(t, ok) } // Run terragrunt plan -detailed-exitcode on a folder with some uncreated resources and make sure that you get an exit @@ -1415,8 +1419,8 @@ func TestExitCode(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan -detailed-exitcode --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), os.Stdout, os.Stderr) exitCode, exitCodeErr := util.GetExitCode(err) - assert.NoError(t, exitCodeErr) - assert.Equal(t, 2, exitCode) + require.NoError(t, exitCodeErr) + require.Equal(t, 2, exitCode) } func TestAutoRetryBasicRerun(t *testing.T) { @@ -1427,8 +1431,8 @@ func TestAutoRetryBasicRerun(t *testing.T) { modulePath := util.JoinPath(rootPath, TEST_FIXTURE_AUTO_RETRY_RERUN) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), out, os.Stderr) - assert.NoError(t, err) - assert.Contains(t, out.String(), "Apply complete!") + require.NoError(t, err) + require.Contains(t, out.String(), "Apply complete!") } func TestAutoRetrySkip(t *testing.T) { @@ -1439,8 +1443,8 @@ func TestAutoRetrySkip(t *testing.T) { modulePath := util.JoinPath(rootPath, TEST_FIXTURE_AUTO_RETRY_RERUN) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-no-auto-retry --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), out, os.Stderr) - assert.Error(t, err) - assert.NotContains(t, out.String(), "Apply complete!") + require.Error(t, err) + require.NotContains(t, out.String(), "Apply complete!") } func TestPlanfileOrder(t *testing.T) { @@ -1450,10 +1454,10 @@ func TestPlanfileOrder(t *testing.T) { modulePath := util.JoinPath(rootPath, TEST_FIXTURE_PLANFILE_ORDER) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-working-dir %s", modulePath), os.Stdout, os.Stderr) - assert.NoError(t, err) + require.NoError(t, err) err = runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-working-dir %s", modulePath), os.Stdout, os.Stderr) - assert.NoError(t, err) + require.NoError(t, err) } func TestAutoRetryExhaustRetries(t *testing.T) { @@ -1464,9 +1468,9 @@ func TestAutoRetryExhaustRetries(t *testing.T) { modulePath := util.JoinPath(rootPath, TEST_FIXTURE_AUTO_RETRY_EXHAUST) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), out, os.Stderr) - assert.Error(t, err) - assert.Contains(t, out.String(), "Failed to load backend") - assert.NotContains(t, out.String(), "Apply complete!") + require.Error(t, err) + require.Contains(t, out.String(), "Failed to load backend") + require.NotContains(t, out.String(), "Apply complete!") } func TestAutoRetryCustomRetryableErrors(t *testing.T) { @@ -1477,9 +1481,9 @@ func TestAutoRetryCustomRetryableErrors(t *testing.T) { modulePath := util.JoinPath(rootPath, TEST_FIXTURE_AUTO_RETRY_CUSTOM_ERRORS) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply --auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), out, os.Stderr) - assert.NoError(t, err) - assert.Contains(t, out.String(), "My own little error") - assert.Contains(t, out.String(), "Apply complete!") + require.NoError(t, err) + require.Contains(t, out.String(), "My own little error") + require.Contains(t, out.String(), "Apply complete!") } func TestAutoRetryGetDefaultErrors(t *testing.T) { @@ -1510,9 +1514,9 @@ func TestAutoRetryCustomRetryableErrorsFailsWhenRetryableErrorsNotSet(t *testing modulePath := util.JoinPath(rootPath, TEST_FIXTURE_AUTO_RETRY_CUSTOM_ERRORS_NOT_SET) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply --auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), out, os.Stderr) - assert.Error(t, err) - assert.Contains(t, out.String(), "My own little error") - assert.NotContains(t, out.String(), "Apply complete!") + require.Error(t, err) + require.Contains(t, out.String(), "My own little error") + require.NotContains(t, out.String(), "Apply complete!") } func TestAutoRetryFlagWithRecoverableError(t *testing.T) { @@ -1523,8 +1527,8 @@ func TestAutoRetryFlagWithRecoverableError(t *testing.T) { modulePath := util.JoinPath(rootPath, TEST_FIXTURE_AUTO_RETRY_RERUN) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-no-auto-retry --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), out, os.Stderr) - assert.Error(t, err) - assert.NotContains(t, out.String(), "Apply complete!") + require.Error(t, err) + require.NotContains(t, out.String(), "Apply complete!") } func TestAutoRetryEnvVarWithRecoverableError(t *testing.T) { @@ -1534,8 +1538,8 @@ func TestAutoRetryEnvVarWithRecoverableError(t *testing.T) { modulePath := util.JoinPath(rootPath, TEST_FIXTURE_AUTO_RETRY_RERUN) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), out, os.Stderr) - assert.Error(t, err) - assert.NotContains(t, out.String(), "Apply complete!") + require.Error(t, err) + require.NotContains(t, out.String(), "Apply complete!") } func TestAutoRetryApplyAllDependentModuleRetries(t *testing.T) { @@ -1546,12 +1550,12 @@ func TestAutoRetryApplyAllDependentModuleRetries(t *testing.T) { modulePath := util.JoinPath(rootPath, TEST_FIXTURE_AUTO_RETRY_APPLY_ALL_RETRIES) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply-all -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), out, os.Stderr) - assert.NoError(t, err) + require.NoError(t, err) s := out.String() - assert.Contains(t, s, "app1 output") - assert.Contains(t, s, "app2 output") - assert.Contains(t, s, "app3 output") - assert.Contains(t, s, "Apply complete!") + require.Contains(t, s, "app1 output") + require.Contains(t, s, "app2 output") + require.Contains(t, s, "app3 output") + require.Contains(t, s, "Apply complete!") } func TestAutoRetryConfigurableRetries(t *testing.T) { @@ -1564,9 +1568,9 @@ func TestAutoRetryConfigurableRetries(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), stdout, stderr) sleeps := regexp.MustCompile("Sleeping 0s before retrying.").FindAllStringIndex(stderr.String(), -1) - assert.NoError(t, err) - assert.Equal(t, 4, len(sleeps)) // 5 retries, so 4 sleeps - assert.Contains(t, stdout.String(), "Apply complete!") + require.NoError(t, err) + require.Len(t, sleeps, 4) // 5 retries, so 4 sleeps + require.Contains(t, stdout.String(), "Apply complete!") } func TestAutoRetryConfigurableRetriesErrors(t *testing.T) { @@ -1590,9 +1594,9 @@ func TestAutoRetryConfigurableRetriesErrors(t *testing.T) { modulePath := util.JoinPath(rootPath, tc.fixture) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", modulePath), stdout, stderr) - assert.Error(t, err) - assert.NotContains(t, stdout.String(), "Apply complete!") - assert.Contains(t, err.Error(), tc.errorMessage) + require.Error(t, err) + require.NotContains(t, stdout.String(), "Apply complete!") + require.Contains(t, err.Error(), tc.errorMessage) }) } } @@ -1615,16 +1619,16 @@ func TestAwsProviderPatch(t *testing.T) { mainContents = strings.ReplaceAll(mainContents, "__BRANCH_NAME__", branchName) require.NoError(t, os.WriteFile(mainTFFile, []byte(mainContents), 0444)) - assert.NoError( + require.NoError( t, runTerragruntCommand(t, fmt.Sprintf("terragrunt aws-provider-patch --terragrunt-override-attr region=\"eu-west-1\" --terragrunt-override-attr allowed_account_ids=[\"00000000000\"] --terragrunt-working-dir %s --terragrunt-log-level debug", modulePath), os.Stdout, stderr), ) t.Log(stderr.String()) - assert.Regexp(t, "Patching AWS provider in .+test/fixture-aws-provider-patch/example-module/main.tf", stderr.String()) + require.Regexp(t, "Patching AWS provider in .+test/fixture-aws-provider-patch/example-module/main.tf", stderr.String()) // Make sure the resulting terraform code is still valid - assert.NoError( + require.NoError( t, runTerragruntCommand(t, fmt.Sprintf("terragrunt validate --terragrunt-working-dir %s", modulePath), os.Stdout, os.Stderr), ) @@ -1681,12 +1685,12 @@ func TestTerraformCommandCliArgs(t *testing.T) { err := runTerragruntCommand(t, cmd, &stdout, &stderr) if testCase.expectedErr != nil { - assert.ErrorIs(t, err, testCase.expectedErr) + require.ErrorIs(t, err, testCase.expectedErr) } output := stdout.String() errOutput := stderr.String() - assert.True(t, strings.Contains(errOutput, testCase.expected) || strings.Contains(output, testCase.expected)) + require.True(t, strings.Contains(errOutput, testCase.expected) || strings.Contains(output, testCase.expected)) } } @@ -1730,7 +1734,7 @@ func TestTerraformSubcommandCliArgs(t *testing.T) { } output := stdout.String() errOutput := stderr.String() - assert.True(t, strings.Contains(errOutput, testCase.expected) || strings.Contains(output, testCase.expected)) + require.True(t, strings.Contains(errOutput, testCase.expected) || strings.Contains(output, testCase.expected)) } } @@ -1739,8 +1743,8 @@ func TestPreventDestroyOverride(t *testing.T) { cleanupTerraformFolder(t, TEST_FIXTURE_PREVENT_DESTROY_OVERRIDE) - assert.NoError(t, runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-working-dir %s", TEST_FIXTURE_PREVENT_DESTROY_OVERRIDE), os.Stdout, os.Stderr)) - assert.NoError(t, runTerragruntCommand(t, fmt.Sprintf("terragrunt destroy -auto-approve --terragrunt-working-dir %s", TEST_FIXTURE_PREVENT_DESTROY_OVERRIDE), os.Stdout, os.Stderr)) + require.NoError(t, runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-working-dir %s", TEST_FIXTURE_PREVENT_DESTROY_OVERRIDE), os.Stdout, os.Stderr)) + require.NoError(t, runTerragruntCommand(t, fmt.Sprintf("terragrunt destroy -auto-approve --terragrunt-working-dir %s", TEST_FIXTURE_PREVENT_DESTROY_OVERRIDE), os.Stdout, os.Stderr)) } func TestPreventDestroyNotSet(t *testing.T) { @@ -1748,12 +1752,12 @@ func TestPreventDestroyNotSet(t *testing.T) { cleanupTerraformFolder(t, TEST_FIXTURE_PREVENT_DESTROY_NOT_SET) - assert.NoError(t, runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-working-dir %s", TEST_FIXTURE_PREVENT_DESTROY_NOT_SET), os.Stdout, os.Stderr)) + require.NoError(t, runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-working-dir %s", TEST_FIXTURE_PREVENT_DESTROY_NOT_SET), os.Stdout, os.Stderr)) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt destroy -auto-approve --terragrunt-working-dir %s", TEST_FIXTURE_PREVENT_DESTROY_NOT_SET), os.Stdout, os.Stderr) if assert.Error(t, err) { underlying := errors.Unwrap(err) - assert.IsType(t, terraform.ModuleIsProtected{}, underlying) + require.IsType(t, terraform.ModuleIsProtected{}, underlying) } } @@ -1769,7 +1773,7 @@ func TestPreventDestroy(t *testing.T) { if assert.Error(t, err) { underlying := errors.Unwrap(err) - assert.IsType(t, terraform.ModuleIsProtected{}, underlying) + require.IsType(t, terraform.ModuleIsProtected{}, underlying) } } @@ -1785,7 +1789,7 @@ func TestPreventDestroyApply(t *testing.T) { if assert.Error(t, err) { underlying := errors.Unwrap(err) - assert.IsType(t, terraform.ModuleIsProtected{}, underlying) + require.IsType(t, terraform.ModuleIsProtected{}, underlying) } } @@ -1836,7 +1840,7 @@ func TestPreventDestroyDependencies(t *testing.T) { if assert.Error(t, err) { underlying := errors.Unwrap(err) - assert.IsType(t, &multierror.Error{}, underlying) + require.IsType(t, &multierror.Error{}, underlying) } // Check that modules C, D and E were deleted and modules A and B weren't. @@ -1850,35 +1854,35 @@ func TestPreventDestroyDependencies(t *testing.T) { logBufferContentsLineByLine(t, showStdout, fmt.Sprintf("show stdout for %s", modulePath)) logBufferContentsLineByLine(t, showStderr, fmt.Sprintf("show stderr for %s", modulePath)) - assert.NoError(t, err) + require.NoError(t, err) output := showStdout.String() switch moduleName { case "module-a": - assert.Contains(t, output, "Hello, Module A") + require.Contains(t, output, "Hello, Module A") case "module-b": - assert.Contains(t, output, "Hello, Module B") + require.Contains(t, output, "Hello, Module B") case "module-c": - assert.NotContains(t, output, "Hello, Module C") + require.NotContains(t, output, "Hello, Module C") case "module-d": - assert.NotContains(t, output, "Hello, Module D") + require.NotContains(t, output, "Hello, Module D") case "module-e": - assert.NotContains(t, output, "Hello, Module E") + require.NotContains(t, output, "Hello, Module E") } } } func validateInputs(t *testing.T, outputs map[string]TerraformOutput) { - assert.Equal(t, outputs["bool"].Value, true) - assert.Equal(t, outputs["list_bool"].Value, []interface{}{true, false}) - assert.Equal(t, outputs["list_number"].Value, []interface{}{1.0, 2.0, 3.0}) - assert.Equal(t, outputs["list_string"].Value, []interface{}{"a", "b", "c"}) - assert.Equal(t, outputs["map_bool"].Value, map[string]interface{}{"foo": true, "bar": false, "baz": true}) - assert.Equal(t, outputs["map_number"].Value, map[string]interface{}{"foo": 42.0, "bar": 12345.0}) - assert.Equal(t, outputs["map_string"].Value, map[string]interface{}{"foo": "bar"}) - assert.Equal(t, outputs["number"].Value, 42.0) - assert.Equal(t, outputs["object"].Value, map[string]interface{}{"list": []interface{}{1.0, 2.0, 3.0}, "map": map[string]interface{}{"foo": "bar"}, "num": 42.0, "str": "string"}) - assert.Equal(t, outputs["string"].Value, "string") - assert.Equal(t, outputs["from_env"].Value, "default") + require.Equal(t, true, outputs["bool"].Value) + require.Equal(t, []interface{}{true, false}, outputs["list_bool"].Value) + require.Equal(t, []interface{}{1.0, 2.0, 3.0}, outputs["list_number"].Value) + require.Equal(t, []interface{}{"a", "b", "c"}, outputs["list_string"].Value) + require.Equal(t, map[string]interface{}{"foo": true, "bar": false, "baz": true}, outputs["map_bool"].Value) + require.Equal(t, map[string]interface{}{"foo": 42.0, "bar": 12345.0}, outputs["map_number"].Value) + require.Equal(t, map[string]interface{}{"foo": "bar"}, outputs["map_string"].Value) + require.InEpsilon(t, 42.0, outputs["number"].Value, 0.0000000001) + require.Equal(t, map[string]interface{}{"list": []interface{}{1.0, 2.0, 3.0}, "map": map[string]interface{}{"foo": "bar"}, "num": 42.0, "str": "string"}, outputs["object"].Value) + require.Equal(t, "string", outputs["string"].Value) + require.Equal(t, "default", outputs["from_env"].Value) } func TestInputsPassedThroughCorrectly(t *testing.T) { @@ -1932,8 +1936,8 @@ func TestLocalsParsing(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["data"].Value, "Hello world\n") - assert.Equal(t, outputs["answer"].Value, float64(42)) + require.Equal(t, "Hello world\n", outputs["data"].Value) + require.InEpsilon(t, 42.0, outputs["answer"].Value, 0.0000000001) } func TestLocalsInInclude(t *testing.T) { @@ -1956,22 +1960,22 @@ func TestLocalsInInclude(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal( + require.Equal( t, filepath.Join(tmpEnvPath, TEST_FIXTURE_LOCALS_IN_INCLUDE), outputs["parent_terragrunt_dir"].Value, ) - assert.Equal( + require.Equal( t, childPath, outputs["terragrunt_dir"].Value, ) - assert.Equal( + require.Equal( t, "apply", outputs["terraform_command"].Value, ) - assert.Equal( + require.Equal( t, "[\"apply\",\"-auto-approve\",\"-no-color\"]", outputs["terraform_cli_args"].Value, @@ -1983,7 +1987,7 @@ func TestUndefinedLocalsReferenceBreaks(t *testing.T) { cleanupTerraformFolder(t, TEST_FIXTURE_LOCALS_ERROR_UNDEFINED_LOCAL) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", TEST_FIXTURE_LOCALS_ERROR_UNDEFINED_LOCAL), os.Stdout, os.Stderr) - assert.Error(t, err) + require.Error(t, err) } func TestUndefinedLocalsReferenceToInputsBreaks(t *testing.T) { @@ -1991,13 +1995,13 @@ func TestUndefinedLocalsReferenceToInputsBreaks(t *testing.T) { cleanupTerraformFolder(t, TEST_FIXTURE_LOCALS_ERROR_UNDEFINED_LOCAL_BUT_INPUT) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", TEST_FIXTURE_LOCALS_ERROR_UNDEFINED_LOCAL_BUT_INPUT), os.Stdout, os.Stderr) - assert.Error(t, err) + require.Error(t, err) } type TerraformOutput struct { - Sensitive bool - Type interface{} - Value interface{} + Sensitive bool `json:"Sensitive"` + Type interface{} `json:"Type"` + Value interface{} `json:"Value"` } func TestPreventDestroyDependenciesIncludedConfig(t *testing.T) { @@ -2045,7 +2049,7 @@ func TestPreventDestroyDependenciesIncludedConfig(t *testing.T) { if assert.Error(t, err) { underlying := errors.Unwrap(err) - assert.IsType(t, &multierror.Error{}, underlying) + require.IsType(t, &multierror.Error{}, underlying) } // Check that modules C, D and E were deleted and modules A and B weren't. @@ -2059,15 +2063,15 @@ func TestPreventDestroyDependenciesIncludedConfig(t *testing.T) { logBufferContentsLineByLine(t, showStdout, fmt.Sprintf("show stdout for %s", modulePath)) logBufferContentsLineByLine(t, showStderr, fmt.Sprintf("show stderr for %s", modulePath)) - assert.NoError(t, err) + require.NoError(t, err) output := showStdout.String() switch moduleName { case "module-a": - assert.Contains(t, output, "Hello, Module A") + require.Contains(t, output, "Hello, Module A") case "module-b": - assert.Contains(t, output, "Hello, Module B") + require.Contains(t, output, "Hello, Module B") case "module-c": - assert.NotContains(t, output, "Hello, Module C") + require.NotContains(t, output, "Hello, Module C") } } } @@ -2083,10 +2087,11 @@ func TestTerragruntMissingDependenciesFail(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init --terragrunt-working-dir %s", generateTestCase), &stdout, &stderr) require.Error(t, err) - parsedError, ok := errors.Unwrap(err).(config.DependencyDirNotFoundError) - assert.True(t, ok) - assert.True(t, len(parsedError.Dir) == 1) - assert.Contains(t, parsedError.Dir[0], "hl3-release") + var parsedError config.DependencyDirNotFoundError + ok := goErrors.As(err, &parsedError) + require.True(t, ok) + require.Len(t, parsedError.Dir, 1) + require.Contains(t, parsedError.Dir[0], "hl3-release") } func TestTerragruntExcludeExternalDependencies(t *testing.T) { @@ -2122,8 +2127,8 @@ func TestTerragruntExcludeExternalDependencies(t *testing.T) { t.Errorf("Did not expect to get error: %s", err.Error()) } - assert.Contains(t, applyAllStdoutString, fmt.Sprintf("Hello World, %s", includedModule)) - assert.NotContains(t, applyAllStdoutString, fmt.Sprintf("Hello World, %s", excludedModule)) + require.Contains(t, applyAllStdoutString, fmt.Sprintf("Hello World, %s", includedModule)) + require.NotContains(t, applyAllStdoutString, fmt.Sprintf("Hello World, %s", excludedModule)) } func TestApplySkipTrue(t *testing.T) { @@ -2142,9 +2147,9 @@ func TestApplySkipTrue(t *testing.T) { stdout := showStdout.String() stderr := showStderr.String() - assert.NoError(t, err) - assert.Regexp(t, regexp.MustCompile("Skipping terragrunt module .*fixture-skip/skip-true/terragrunt.hcl due to skip = true."), stderr) - assert.NotContains(t, stdout, "hello, Hobbs") + require.NoError(t, err) + require.Regexp(t, regexp.MustCompile("Skipping terragrunt module .*fixture-skip/skip-true/terragrunt.hcl due to skip = true."), stderr) + require.NotContains(t, stdout, "hello, Hobbs") } func TestApplySkipFalse(t *testing.T) { @@ -2163,9 +2168,9 @@ func TestApplySkipFalse(t *testing.T) { stderr := showStderr.String() stdout := showStdout.String() - assert.NoError(t, err) - assert.Contains(t, stdout, "hello, Hobbs") - assert.NotContains(t, stderr, "Skipping terragrunt module") + require.NoError(t, err) + require.Contains(t, stdout, "hello, Hobbs") + require.NotContains(t, stderr, "Skipping terragrunt module") } func TestApplyAllSkipTrue(t *testing.T) { @@ -2184,10 +2189,10 @@ func TestApplyAllSkipTrue(t *testing.T) { stdout := showStdout.String() stderr := showStderr.String() - assert.NoError(t, err) - assert.Regexp(t, regexp.MustCompile("Skipping terragrunt module .*fixture-skip/skip-true/terragrunt.hcl due to skip = true."), stderr) - assert.Contains(t, stdout, "hello, Ernie") - assert.Contains(t, stdout, "hello, Bert") + require.NoError(t, err) + require.Regexp(t, regexp.MustCompile("Skipping terragrunt module .*fixture-skip/skip-true/terragrunt.hcl due to skip = true."), stderr) + require.Contains(t, stdout, "hello, Ernie") + require.Contains(t, stdout, "hello, Bert") } func TestApplyAllSkipFalse(t *testing.T) { @@ -2206,11 +2211,11 @@ func TestApplyAllSkipFalse(t *testing.T) { stdout := showStdout.String() stderr := showStderr.String() - assert.NoError(t, err) - assert.Contains(t, stdout, "hello, Hobbs") - assert.Contains(t, stdout, "hello, Ernie") - assert.Contains(t, stdout, "hello, Bert") - assert.NotContains(t, stderr, "Skipping terragrunt module") + require.NoError(t, err) + require.Contains(t, stdout, "hello, Hobbs") + require.Contains(t, stdout, "hello, Ernie") + require.Contains(t, stdout, "hello, Bert") + require.NotContains(t, stderr, "Skipping terragrunt module") } func TestTerragruntInfo(t *testing.T) { @@ -2224,17 +2229,17 @@ func TestTerragruntInfo(t *testing.T) { showStderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt terragrunt-info --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") var dat terragruntinfo.TerragruntInfoGroup errUnmarshal := json.Unmarshal(showStdout.Bytes(), &dat) - assert.NoError(t, errUnmarshal) + require.NoError(t, errUnmarshal) - assert.Equal(t, dat.DownloadDir, fmt.Sprintf("%s/%s", rootPath, TERRAGRUNT_CACHE)) - assert.Equal(t, dat.TerraformBinary, wrappedBinary()) - assert.Equal(t, dat.IamRole, "") + require.Equal(t, fmt.Sprintf("%s/%s", rootPath, TERRAGRUNT_CACHE), dat.DownloadDir) + require.Equal(t, wrappedBinary(), dat.TerraformBinary) + require.Empty(t, dat.IamRole) } // Test case for yamldecode bug: https://github.com/gruntwork-io/terragrunt/issues/834 @@ -2258,9 +2263,9 @@ func TestYamlDecodeRegressions(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["test1"].Value, "003") - assert.Equal(t, outputs["test2"].Value, "1.00") - assert.Equal(t, outputs["test3"].Value, "0ba") + require.Equal(t, "003", outputs["test1"].Value) + require.Equal(t, "1.00", outputs["test2"].Value) + require.Equal(t, "0ba", outputs["test3"].Value) } // We test the path with remote_state blocks by: @@ -2322,7 +2327,7 @@ func dependencyOutputOptimizationTest(t *testing.T, moduleName string, forceInit outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal([]byte(stdout), &outputs)) - assert.Equal(t, expectedOutput, outputs["output"].Value) + require.Equal(t, expectedOutput, outputs["output"].Value) // If we want to force reinit, delete the relevant .terraform directories if forceInit { @@ -2336,13 +2341,13 @@ func dependencyOutputOptimizationTest(t *testing.T, moduleName string, forceInit require.NoError(t, err) require.NoError(t, json.Unmarshal([]byte(reout), &outputs)) - assert.Equal(t, expectedOutput, outputs["output"].Value) + require.Equal(t, expectedOutput, outputs["output"].Value) for _, logRegexp := range expectedOutputLogs { re, err := regexp.Compile(logRegexp) require.NoError(t, err) matches := re.FindAllString(reerr, -1) - assert.Greater(t, len(matches), 0) + require.NotEmpty(t, matches) } } @@ -2377,7 +2382,7 @@ func TestDependencyOutputOptimizationDisableTest(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal([]byte(stdout), &outputs)) - assert.Equal(t, expectedOutput, outputs["output"].Value) + require.Equal(t, expectedOutput, outputs["output"].Value) // Now delete the deepdep state and verify it no longer works, because it tries to fetch the deepdep dependency config.ClearOutputCache() @@ -2408,7 +2413,7 @@ func TestDependencyOutput(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, int(outputs["z"].Value.(float64)), 42) + require.Equal(t, 42, int(outputs["z"].Value.(float64))) } func TestDependencyOutputErrorBeforeApply(t *testing.T) { @@ -2423,9 +2428,9 @@ func TestDependencyOutputErrorBeforeApply(t *testing.T) { showStderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", app3Path), &showStdout, &showStderr) - assert.Error(t, err) + require.Error(t, err) // Verify that we fail because the dependency is not applied yet - assert.Contains(t, err.Error(), "has not been applied yet") + require.Contains(t, err.Error(), "has not been applied yet") logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2445,7 +2450,7 @@ func TestDependencyOutputSkipOutputs(t *testing.T) { // Test that even if the dependency (app1) is not applied, using skip_outputs will skip pulling the outputs so there // will be no errors. err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", emptyPath), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2463,7 +2468,7 @@ func TestDependencyOutputSkipOutputsWithMockOutput(t *testing.T) { showStderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", dependent3Path), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2477,11 +2482,11 @@ func TestDependencyOutputSkipOutputsWithMockOutput(t *testing.T) { ) outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["truth"].Value, "The answer is 0") + require.Equal(t, "The answer is 0", outputs["truth"].Value) // Now apply-all so that the dependency is applied, and verify it still uses the mock output err = runTerragruntCommand(t, fmt.Sprintf("terragrunt apply-all --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2495,7 +2500,7 @@ func TestDependencyOutputSkipOutputsWithMockOutput(t *testing.T) { ) outputs = map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["truth"].Value, "The answer is 0") + require.Equal(t, "The answer is 0", outputs["truth"].Value) } // Test that when you have a mock_output on a dependency, the dependency will use the mock as the output instead @@ -2512,7 +2517,7 @@ func TestDependencyMockOutput(t *testing.T) { showStderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", dependent1Path), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2526,7 +2531,7 @@ func TestDependencyMockOutput(t *testing.T) { ) outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["truth"].Value, "The answer is 0") + require.Equal(t, "The answer is 0", outputs["truth"].Value) // We need to bust the output cache that stores the dependency outputs so that the second run pulls the outputs. // This is only a problem during testing, where the process is shared across terragrunt runs. @@ -2534,7 +2539,7 @@ func TestDependencyMockOutput(t *testing.T) { // Now apply-all so that the dependency is applied, and verify it uses the dependency output err = runTerragruntCommand(t, fmt.Sprintf("terragrunt apply-all --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2548,7 +2553,7 @@ func TestDependencyMockOutput(t *testing.T) { ) outputs = map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["truth"].Value, "The answer is 42") + require.Equal(t, "The answer is 42", outputs["truth"].Value) } // Test default behavior when mock_outputs_merge_with_state is not set. It should behave, as before this parameter was added @@ -2566,7 +2571,7 @@ func TestDependencyMockOutputMergeWithStateDefault(t *testing.T) { stdout := bytes.Buffer{} stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", parentPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "plan stdout") logBufferContentsLineByLine(t, stderr, "plan stderr") @@ -2574,10 +2579,10 @@ func TestDependencyMockOutputMergeWithStateDefault(t *testing.T) { stdout.Reset() stderr.Reset() err = runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) // Verify that we fail because the dependency is not applied yet, and the new attribute is not available and in // this case, mocked outputs are not used. - assert.Contains(t, err.Error(), "This object does not have an attribute named \"test_output2\"") + require.Contains(t, err.Error(), "This object does not have an attribute named \"test_output2\"") logBufferContentsLineByLine(t, stdout, "plan stdout") logBufferContentsLineByLine(t, stderr, "plan stderr") @@ -2599,7 +2604,7 @@ func TestDependencyMockOutputMergeWithStateFalse(t *testing.T) { stdout := bytes.Buffer{} stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", parentPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "plan stdout") logBufferContentsLineByLine(t, stderr, "plan stderr") @@ -2607,10 +2612,10 @@ func TestDependencyMockOutputMergeWithStateFalse(t *testing.T) { stdout.Reset() stderr.Reset() err = runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) // Verify that we fail because the dependency is not applied yet, and the new attribute is not available and in // this case, mocked outputs are not used. - assert.Contains(t, err.Error(), "This object does not have an attribute named \"test_output2\"") + require.Contains(t, err.Error(), "This object does not have an attribute named \"test_output2\"") logBufferContentsLineByLine(t, stdout, "plan stdout") logBufferContentsLineByLine(t, stderr, "plan stderr") @@ -2630,7 +2635,7 @@ func TestDependencyMockOutputMergeWithStateTrue(t *testing.T) { stdout := bytes.Buffer{} stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", parentPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "plan stdout") logBufferContentsLineByLine(t, stderr, "plan stderr") @@ -2638,7 +2643,7 @@ func TestDependencyMockOutputMergeWithStateTrue(t *testing.T) { stdout.Reset() stderr.Reset() err = runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "apply stdout") logBufferContentsLineByLine(t, stderr, "apply stderr") @@ -2654,8 +2659,8 @@ func TestDependencyMockOutputMergeWithStateTrue(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["test_output1_from_parent"].Value, "value1") - assert.Equal(t, outputs["test_output2_from_parent"].Value, "fake-data2") + require.Equal(t, "value1", outputs["test_output1_from_parent"].Value) + require.Equal(t, "fake-data2", outputs["test_output2_from_parent"].Value) logBufferContentsLineByLine(t, stdout, "output stdout") logBufferContentsLineByLine(t, stderr, "output stderr") @@ -2675,7 +2680,7 @@ func TestDependencyMockOutputMergeWithStateTrueNotAllowed(t *testing.T) { stdout := bytes.Buffer{} stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", parentPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "plan stdout") logBufferContentsLineByLine(t, stderr, "plan stderr") @@ -2709,7 +2714,7 @@ func TestDependencyMockOutputMergeWithStateNoOverride(t *testing.T) { stdout := bytes.Buffer{} stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", parentPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "show stdout") logBufferContentsLineByLine(t, stderr, "show stderr") @@ -2717,7 +2722,7 @@ func TestDependencyMockOutputMergeWithStateNoOverride(t *testing.T) { stdout.Reset() stderr.Reset() err = runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) // Now check the outputs to make sure they are as expected stdout.Reset() @@ -2731,8 +2736,8 @@ func TestDependencyMockOutputMergeWithStateNoOverride(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["test_output1_from_parent"].Value, "value1") - assert.Equal(t, outputs["test_output2_from_parent"].Value, "value2") + require.Equal(t, "value1", outputs["test_output1_from_parent"].Value) + require.Equal(t, "value2", outputs["test_output2_from_parent"].Value) logBufferContentsLineByLine(t, stdout, "show stdout") logBufferContentsLineByLine(t, stderr, "show stderr") @@ -2751,8 +2756,8 @@ func TestDependencyMockOutputMergeStrategyWithStateDefault(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.Error(t, err) - assert.Contains(t, err.Error(), "This object does not have an attribute named \"test_output_list_string\"") + require.Error(t, err) + require.Contains(t, err.Error(), "This object does not have an attribute named \"test_output_list_string\"") logBufferContentsLineByLine(t, stdout, "apply stdout") logBufferContentsLineByLine(t, stderr, "apply stderr") } @@ -2770,8 +2775,8 @@ func TestDependencyMockOutputMergeStrategyWithStateCompatFalse(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.Error(t, err) - assert.Contains(t, err.Error(), "This object does not have an attribute named \"test_output_list_string\"") + require.Error(t, err) + require.Contains(t, err.Error(), "This object does not have an attribute named \"test_output_list_string\"") logBufferContentsLineByLine(t, stdout, "apply stdout") logBufferContentsLineByLine(t, stderr, "apply stderr") } @@ -2789,7 +2794,7 @@ func TestDependencyMockOutputMergeStrategyWithStateCompatTrue(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "apply stdout") logBufferContentsLineByLine(t, stderr, "apply stderr") @@ -2802,11 +2807,11 @@ func TestDependencyMockOutputMergeStrategyWithStateCompatTrue(t *testing.T) { logBufferContentsLineByLine(t, stdout, "output stdout") logBufferContentsLineByLine(t, stderr, "output stderr") - assert.Equal(t, "value1", outputs["test_output1_from_parent"].Value) - assert.Equal(t, "map_root1_sub1_value", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "map_root1", "map_root1_sub1", "value")) - assert.Equal(t, nil, util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "not_in_state", "abc", "value")) - assert.Equal(t, "fake-list-data", util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "0")) - assert.Equal(t, nil, util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "1")) + require.Equal(t, "value1", outputs["test_output1_from_parent"].Value) + require.Equal(t, "map_root1_sub1_value", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "map_root1", "map_root1_sub1", "value")) + require.Nil(t, util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "not_in_state", "abc", "value")) + require.Equal(t, "fake-list-data", util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "0")) + require.Nil(t, util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "1")) } // Test when both mock_outputs_merge_with_state and mock_outputs_merge_strategy_with_state are set, mock_outputs_merge_strategy_with_state is used @@ -2822,7 +2827,7 @@ func TestDependencyMockOutputMergeStrategyWithStateCompatConflict(t *testing.T) stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "apply stdout") logBufferContentsLineByLine(t, stderr, "apply stderr") @@ -2835,11 +2840,11 @@ func TestDependencyMockOutputMergeStrategyWithStateCompatConflict(t *testing.T) logBufferContentsLineByLine(t, stdout, "output stdout") logBufferContentsLineByLine(t, stderr, "output stderr") - assert.Equal(t, "value1", outputs["test_output1_from_parent"].Value) - assert.Equal(t, "map_root1_sub1_value", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "map_root1", "map_root1_sub1", "value")) - assert.Equal(t, nil, util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "not_in_state", "abc", "value")) - assert.Equal(t, "fake-list-data", util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "0")) - assert.Equal(t, nil, util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "1")) + require.Equal(t, "value1", outputs["test_output1_from_parent"].Value) + require.Equal(t, "map_root1_sub1_value", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "map_root1", "map_root1_sub1", "value")) + require.Nil(t, util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "not_in_state", "abc", "value")) + require.Equal(t, "fake-list-data", util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "0")) + require.Nil(t, util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "1")) } // Test when mock_outputs_merge_strategy_with_state = "no_merge" that mocks are not merged into the current state @@ -2855,8 +2860,8 @@ func TestDependencyMockOutputMergeStrategyWithStateNoMerge(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.Error(t, err) - assert.Contains(t, err.Error(), "This object does not have an attribute named \"test_output_list_string\"") + require.Error(t, err) + require.Contains(t, err.Error(), "This object does not have an attribute named \"test_output_list_string\"") logBufferContentsLineByLine(t, stdout, "apply stdout") logBufferContentsLineByLine(t, stderr, "apply stderr") } @@ -2875,7 +2880,7 @@ func TestDependencyMockOutputMergeStrategyWithStateShallow(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "apply stdout") logBufferContentsLineByLine(t, stderr, "apply stderr") @@ -2888,11 +2893,11 @@ func TestDependencyMockOutputMergeStrategyWithStateShallow(t *testing.T) { logBufferContentsLineByLine(t, stdout, "output stdout") logBufferContentsLineByLine(t, stderr, "output stderr") - assert.Equal(t, "value1", outputs["test_output1_from_parent"].Value) - assert.Equal(t, "map_root1_sub1_value", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "map_root1", "map_root1_sub1", "value")) - assert.Equal(t, nil, util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "not_in_state", "abc", "value")) - assert.Equal(t, "fake-list-data", util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "0")) - assert.Equal(t, nil, util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "1")) + require.Equal(t, "value1", outputs["test_output1_from_parent"].Value) + require.Equal(t, "map_root1_sub1_value", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "map_root1", "map_root1_sub1", "value")) + require.Nil(t, util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "not_in_state", "abc", "value")) + require.Equal(t, "fake-list-data", util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "0")) + require.Nil(t, util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "1")) } // Test when mock_outputs_merge_strategy_with_state = "deep" that the existing state is deeply merged into the mocks @@ -2910,7 +2915,7 @@ func TestDependencyMockOutputMergeStrategyWithStateDeepMapOnly(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", childPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "apply stdout") logBufferContentsLineByLine(t, stderr, "apply stderr") @@ -2923,12 +2928,12 @@ func TestDependencyMockOutputMergeStrategyWithStateDeepMapOnly(t *testing.T) { logBufferContentsLineByLine(t, stdout, "output stdout") logBufferContentsLineByLine(t, stderr, "output stderr") - assert.Equal(t, "value1", outputs["test_output1_from_parent"].Value) - assert.Equal(t, "fake-abc", outputs["test_output2_from_parent"].Value) - assert.Equal(t, "map_root1_sub1_value", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "map_root1", "map_root1_sub1", "value")) - assert.Equal(t, "fake-abc", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "not_in_state", "abc", "value")) - assert.Equal(t, "a", util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "0")) - assert.Equal(t, nil, util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "1")) + require.Equal(t, "value1", outputs["test_output1_from_parent"].Value) + require.Equal(t, "fake-abc", outputs["test_output2_from_parent"].Value) + require.Equal(t, "map_root1_sub1_value", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "map_root1", "map_root1_sub1", "value")) + require.Equal(t, "fake-abc", util.MustWalkTerraformOutput(outputs["test_output_map_map_string_from_parent"].Value, "not_in_state", "abc", "value")) + require.Equal(t, "a", util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "0")) + require.Nil(t, util.MustWalkTerraformOutput(outputs["test_output_list_string"].Value, "1")) } // Test that when you have a mock_output on a dependency, the dependency will use the mock as the output instead @@ -2945,9 +2950,9 @@ func TestDependencyMockOutputRestricted(t *testing.T) { showStderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", dependent2Path), &showStdout, &showStderr) - assert.Error(t, err) + require.Error(t, err) // Verify that we fail because the dependency is not applied yet - assert.Contains(t, err.Error(), "has not been applied yet") + require.Contains(t, err.Error(), "has not been applied yet") logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2956,7 +2961,7 @@ func TestDependencyMockOutputRestricted(t *testing.T) { showStdout.Reset() showStderr.Reset() err = runTerragruntCommand(t, fmt.Sprintf("terragrunt validate --terragrunt-non-interactive --terragrunt-working-dir %s", dependent2Path), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2965,7 +2970,7 @@ func TestDependencyMockOutputRestricted(t *testing.T) { showStdout.Reset() showStderr.Reset() err = runTerragruntCommand(t, fmt.Sprintf("terragrunt validate-all --terragrunt-non-interactive --terragrunt-working-dir %s", dependent2Path), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2973,7 +2978,7 @@ func TestDependencyMockOutputRestricted(t *testing.T) { showStdout.Reset() showStderr.Reset() err = runTerragruntCommand(t, fmt.Sprintf("terragrunt validate-all --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") logBufferContentsLineByLine(t, showStderr, "show stderr") @@ -2995,7 +3000,7 @@ func TestDependencyOutputTypeConversion(t *testing.T) { // Then apply the outputs module showStdout := bytes.Buffer{} showStderr := bytes.Buffer{} - assert.NoError( + require.NoError( t, runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &showStdout, &showStderr), ) @@ -3015,17 +3020,17 @@ func TestDependencyOutputTypeConversion(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["bool"].Value, true) - assert.Equal(t, outputs["list_bool"].Value, []interface{}{true, false}) - assert.Equal(t, outputs["list_number"].Value, []interface{}{1.0, 2.0, 3.0}) - assert.Equal(t, outputs["list_string"].Value, []interface{}{"a", "b", "c"}) - assert.Equal(t, outputs["map_bool"].Value, map[string]interface{}{"foo": true, "bar": false, "baz": true}) - assert.Equal(t, outputs["map_number"].Value, map[string]interface{}{"foo": 42.0, "bar": 12345.0}) - assert.Equal(t, outputs["map_string"].Value, map[string]interface{}{"foo": "bar"}) - assert.Equal(t, outputs["number"].Value, 42.0) - assert.Equal(t, outputs["object"].Value, map[string]interface{}{"list": []interface{}{1.0, 2.0, 3.0}, "map": map[string]interface{}{"foo": "bar"}, "num": 42.0, "str": "string"}) - assert.Equal(t, outputs["string"].Value, "string") - assert.Equal(t, outputs["from_env"].Value, "default") + require.Equal(t, true, outputs["bool"].Value) + require.Equal(t, []interface{}{true, false}, outputs["list_bool"].Value) + require.Equal(t, []interface{}{1.0, 2.0, 3.0}, outputs["list_number"].Value) + require.Equal(t, []interface{}{"a", "b", "c"}, outputs["list_string"].Value) + require.Equal(t, map[string]interface{}{"foo": true, "bar": false, "baz": true}, outputs["map_bool"].Value) + require.Equal(t, map[string]interface{}{"foo": 42.0, "bar": 12345.0}, outputs["map_number"].Value) + require.Equal(t, map[string]interface{}{"foo": "bar"}, outputs["map_string"].Value) + require.InEpsilon(t, 42.0, outputs["number"].Value.(float64), 0.0000001) + require.Equal(t, map[string]interface{}{"list": []interface{}{1.0, 2.0, 3.0}, "map": map[string]interface{}{"foo": "bar"}, "num": 42.0, "str": "string"}, outputs["object"].Value) + require.Equal(t, "string", outputs["string"].Value) + require.Equal(t, "default", outputs["from_env"].Value) } // Regression testing for https://github.com/gruntwork-io/terragrunt/issues/1102: Ordering keys from @@ -3096,8 +3101,8 @@ func TestDependencyOutputCycleHandling(t *testing.T) { ) logBufferContentsLineByLine(t, planStdout, "plan stdout") logBufferContentsLineByLine(t, planStderr, "plan stderr") - assert.Error(t, err) - assert.True(t, strings.Contains(err.Error(), "Found a dependency cycle between modules")) + require.Error(t, err) + require.True(t, strings.Contains(err.Error(), "Found a dependency cycle between modules")) }) } } @@ -3224,14 +3229,14 @@ func TestDependencyOutputWithHooks(t *testing.T) { config.ClearOutputCache() // The file should exist in the first run. - assert.True(t, util.FileExists(depPathFileOut)) - assert.False(t, util.FileExists(mainPathFileOut)) + require.True(t, util.FileExists(depPathFileOut)) + require.False(t, util.FileExists(mainPathFileOut)) // Now delete file and run just main again. It should NOT create file.out. require.NoError(t, os.Remove(depPathFileOut)) runTerragrunt(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", mainPath)) - assert.False(t, util.FileExists(depPathFileOut)) - assert.False(t, util.FileExists(mainPathFileOut)) + require.False(t, util.FileExists(depPathFileOut)) + require.False(t, util.FileExists(mainPathFileOut)) } func TestDeepDependencyOutputWithMock(t *testing.T) { @@ -3280,9 +3285,9 @@ func TestAWSGetCallerIdentityFunctions(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["account"].Value, *identity.Account) - assert.Equal(t, outputs["arn"].Value, *identity.Arn) - assert.Equal(t, outputs["user_id"].Value, *identity.UserId) + require.Equal(t, outputs["account"].Value, *identity.Account) + require.Equal(t, outputs["arn"].Value, *identity.Arn) + require.Equal(t, outputs["user_id"].Value, *identity.UserId) } func TestGetRepoRoot(t *testing.T) { @@ -3390,7 +3395,7 @@ func TestPathRelativeFromInclude(t *testing.T) { stderr := bytes.Buffer{} err = runTerragruntCommand(t, fmt.Sprintf("terragrunt output -no-color -json --terragrunt-non-interactive --terragrunt-working-dir %s", clusterPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) @@ -3404,9 +3409,9 @@ func TestPathRelativeFromInclude(t *testing.T) { stderr = bytes.Buffer{} err = runTerragruntCommand(t, fmt.Sprintf("terragrunt destroy -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", basePath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) - assert.Contains(t, stderr.String(), fmt.Sprintf("Detected dependent modules:\n%s", clusterPath)) + require.Contains(t, stderr.String(), fmt.Sprintf("Detected dependent modules:\n%s", clusterPath)) } func TestGetPathFromRepoRoot(t *testing.T) { @@ -3505,7 +3510,7 @@ func TestGetPlatform(t *testing.T) { require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) platform, hasPlatform := outputs["platform"] require.True(t, hasPlatform) - require.Equal(t, platform.Value, runtime.GOOS) + require.Equal(t, runtime.GOOS, platform.Value) } func TestDataDir(t *testing.T) { @@ -3524,14 +3529,14 @@ func TestDataDir(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) require.NoError(t, err) - assert.Contains(t, stdout.String(), "Initializing provider plugins") + require.Contains(t, stdout.String(), "Initializing provider plugins") stdout = bytes.Buffer{} stderr = bytes.Buffer{} err = runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) require.NoError(t, err) - assert.NotContains(t, stdout.String(), "Initializing provider plugins") + require.NotContains(t, stdout.String(), "Initializing provider plugins") } func TestReadTerragruntConfigWithDependency(t *testing.T) { @@ -3550,7 +3555,7 @@ func TestReadTerragruntConfigWithDependency(t *testing.T) { // Then apply the read config module showStdout := bytes.Buffer{} showStderr := bytes.Buffer{} - assert.NoError( + require.NoError( t, runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &showStdout, &showStderr), ) @@ -3570,17 +3575,17 @@ func TestReadTerragruntConfigWithDependency(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["bool"].Value, true) - assert.Equal(t, outputs["list_bool"].Value, []interface{}{true, false}) - assert.Equal(t, outputs["list_number"].Value, []interface{}{1.0, 2.0, 3.0}) - assert.Equal(t, outputs["list_string"].Value, []interface{}{"a", "b", "c"}) - assert.Equal(t, outputs["map_bool"].Value, map[string]interface{}{"foo": true, "bar": false, "baz": true}) - assert.Equal(t, outputs["map_number"].Value, map[string]interface{}{"foo": 42.0, "bar": 12345.0}) - assert.Equal(t, outputs["map_string"].Value, map[string]interface{}{"foo": "bar"}) - assert.Equal(t, outputs["number"].Value, 42.0) - assert.Equal(t, outputs["object"].Value, map[string]interface{}{"list": []interface{}{1.0, 2.0, 3.0}, "map": map[string]interface{}{"foo": "bar"}, "num": 42.0, "str": "string"}) - assert.Equal(t, outputs["string"].Value, "string") - assert.Equal(t, outputs["from_env"].Value, "default") + require.Equal(t, true, outputs["bool"].Value) + require.Equal(t, []interface{}{true, false}, outputs["list_bool"].Value) + require.Equal(t, []interface{}{1.0, 2.0, 3.0}, outputs["list_number"].Value) + require.Equal(t, []interface{}{"a", "b", "c"}, outputs["list_string"].Value) + require.Equal(t, map[string]interface{}{"foo": true, "bar": false, "baz": true}, outputs["map_bool"].Value) + require.Equal(t, map[string]interface{}{"foo": 42.0, "bar": 12345.0}, outputs["map_number"].Value) + require.Equal(t, map[string]interface{}{"foo": "bar"}, outputs["map_string"].Value) + require.InEpsilon(t, 42.0, outputs["number"].Value.(float64), 0.0000001) + require.Equal(t, map[string]interface{}{"list": []interface{}{1.0, 2.0, 3.0}, "map": map[string]interface{}{"foo": "bar"}, "num": 42.0, "str": "string"}, outputs["object"].Value) + require.Equal(t, "string", outputs["string"].Value) + require.Equal(t, "default", outputs["from_env"].Value) } func TestReadTerragruntConfigFromDependency(t *testing.T) { @@ -3592,7 +3597,7 @@ func TestReadTerragruntConfigFromDependency(t *testing.T) { showStdout := bytes.Buffer{} showStderr := bytes.Buffer{} - assert.NoError( + require.NoError( t, runTerragruntCommand(t, fmt.Sprintf("terragrunt apply-all --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &showStdout, &showStderr), ) @@ -3612,7 +3617,7 @@ func TestReadTerragruntConfigFromDependency(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["bar"].Value, "hello world") + require.Equal(t, "hello world", outputs["bar"].Value) } func TestReadTerragruntConfigWithDefault(t *testing.T) { @@ -3635,7 +3640,7 @@ func TestReadTerragruntConfigWithDefault(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["data"].Value, "default value") + require.Equal(t, "default value", outputs["data"].Value) } func TestReadTerragruntConfigWithOriginalTerragruntDir(t *testing.T) { @@ -3663,10 +3668,10 @@ func TestReadTerragruntConfigWithOriginalTerragruntDir(t *testing.T) { depOutputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(depStdout.Bytes(), &depOutputs)) - assert.Equal(t, depPathAbs, depOutputs["terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, depOutputs["original_terragrunt_dir"].Value) - assert.Equal(t, fooPathAbs, depOutputs["bar_terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, depOutputs["bar_original_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, depOutputs["terragrunt_dir"].Value) + require.Equal(t, depPathAbs, depOutputs["original_terragrunt_dir"].Value) + require.Equal(t, fooPathAbs, depOutputs["bar_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, depOutputs["bar_original_terragrunt_dir"].Value) // Run apply on the root module and make sure we get the expected outputs runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) @@ -3682,12 +3687,12 @@ func TestReadTerragruntConfigWithOriginalTerragruntDir(t *testing.T) { rootOutputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(rootStdout.Bytes(), &rootOutputs)) - assert.Equal(t, fooPathAbs, rootOutputs["terragrunt_dir"].Value) - assert.Equal(t, rootPathAbs, rootOutputs["original_terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, rootOutputs["dep_terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, rootOutputs["dep_original_terragrunt_dir"].Value) - assert.Equal(t, fooPathAbs, rootOutputs["dep_bar_terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, rootOutputs["dep_bar_original_terragrunt_dir"].Value) + require.Equal(t, fooPathAbs, rootOutputs["terragrunt_dir"].Value) + require.Equal(t, rootPathAbs, rootOutputs["original_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, rootOutputs["dep_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, rootOutputs["dep_original_terragrunt_dir"].Value) + require.Equal(t, fooPathAbs, rootOutputs["dep_bar_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, rootOutputs["dep_bar_original_terragrunt_dir"].Value) // Run 'run-all apply' and make sure all the outputs are identical in the root module and the dependency module runTerragrunt(t, fmt.Sprintf("terragrunt run-all apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath)) @@ -3714,16 +3719,16 @@ func TestReadTerragruntConfigWithOriginalTerragruntDir(t *testing.T) { runAllDepOutputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(runAllDepStdout.Bytes(), &runAllDepOutputs)) - assert.Equal(t, fooPathAbs, runAllRootOutputs["terragrunt_dir"].Value) - assert.Equal(t, rootPathAbs, runAllRootOutputs["original_terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, runAllRootOutputs["dep_terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, runAllRootOutputs["dep_original_terragrunt_dir"].Value) - assert.Equal(t, fooPathAbs, runAllRootOutputs["dep_bar_terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, runAllRootOutputs["dep_bar_original_terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, runAllDepOutputs["terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, runAllDepOutputs["original_terragrunt_dir"].Value) - assert.Equal(t, fooPathAbs, runAllDepOutputs["bar_terragrunt_dir"].Value) - assert.Equal(t, depPathAbs, runAllDepOutputs["bar_original_terragrunt_dir"].Value) + require.Equal(t, fooPathAbs, runAllRootOutputs["terragrunt_dir"].Value) + require.Equal(t, rootPathAbs, runAllRootOutputs["original_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, runAllRootOutputs["dep_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, runAllRootOutputs["dep_original_terragrunt_dir"].Value) + require.Equal(t, fooPathAbs, runAllRootOutputs["dep_bar_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, runAllRootOutputs["dep_bar_original_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, runAllDepOutputs["terragrunt_dir"].Value) + require.Equal(t, depPathAbs, runAllDepOutputs["original_terragrunt_dir"].Value) + require.Equal(t, fooPathAbs, runAllDepOutputs["bar_terragrunt_dir"].Value) + require.Equal(t, depPathAbs, runAllDepOutputs["bar_original_terragrunt_dir"].Value) } func TestReadTerragruntConfigFull(t *testing.T) { @@ -3746,27 +3751,26 @@ func TestReadTerragruntConfigFull(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - // Primitive config attributes - assert.Equal(t, outputs["terraform_binary"].Value, "terragrunt") - assert.Equal(t, outputs["terraform_version_constraint"].Value, "= 0.12.20") - assert.Equal(t, outputs["terragrunt_version_constraint"].Value, "= 0.23.18") - assert.Equal(t, outputs["download_dir"].Value, ".terragrunt-cache") - assert.Equal(t, outputs["iam_role"].Value, "TerragruntIAMRole") - assert.Equal(t, outputs["skip"].Value, "true") - assert.Equal(t, outputs["prevent_destroy"].Value, "true") + require.Equal(t, "terragrunt", outputs["terraform_binary"].Value) + require.Equal(t, "= 0.12.20", outputs["terraform_version_constraint"].Value) + require.Equal(t, "= 0.23.18", outputs["terragrunt_version_constraint"].Value) + require.Equal(t, ".terragrunt-cache", outputs["download_dir"].Value) + require.Equal(t, "TerragruntIAMRole", outputs["iam_role"].Value) + require.Equal(t, "true", outputs["skip"].Value) + require.Equal(t, "true", outputs["prevent_destroy"].Value) // Simple maps localstgOut := map[string]interface{}{} require.NoError(t, json.Unmarshal([]byte(outputs["localstg"].Value.(string)), &localstgOut)) - assert.Equal(t, localstgOut, map[string]interface{}{"the_answer": float64(42)}) + require.Equal(t, map[string]interface{}{"the_answer": float64(42)}, localstgOut) inputsOut := map[string]interface{}{} require.NoError(t, json.Unmarshal([]byte(outputs["inputs"].Value.(string)), &inputsOut)) - assert.Equal(t, inputsOut, map[string]interface{}{"doc": "Emmett Brown"}) + require.Equal(t, map[string]interface{}{"doc": "Emmett Brown"}, inputsOut) // Complex blocks depsOut := map[string]interface{}{} require.NoError(t, json.Unmarshal([]byte(outputs["dependencies"].Value.(string)), &depsOut)) - assert.Equal( + require.Equal( t, map[string]interface{}{ "paths": []interface{}{"../../fixture"}, @@ -3776,7 +3780,7 @@ func TestReadTerragruntConfigFull(t *testing.T) { generateOut := map[string]interface{}{} require.NoError(t, json.Unmarshal([]byte(outputs["generate"].Value.(string)), &generateOut)) - assert.Equal( + require.Equal( t, map[string]interface{}{ "provider": map[string]interface{}{ @@ -3796,7 +3800,7 @@ func TestReadTerragruntConfigFull(t *testing.T) { ) remoteStateOut := map[string]interface{}{} require.NoError(t, json.Unmarshal([]byte(outputs["remote_state"].Value.(string)), &remoteStateOut)) - assert.Equal( + require.Equal( t, map[string]interface{}{ "backend": "local", @@ -3809,7 +3813,7 @@ func TestReadTerragruntConfigFull(t *testing.T) { ) terraformOut := map[string]interface{}{} require.NoError(t, json.Unmarshal([]byte(outputs["terraformtg"].Value.(string)), &terraformOut)) - assert.Equal( + require.Equal( t, map[string]interface{}{ "source": "./delorean", @@ -3868,7 +3872,7 @@ func TestTerragruntGenerateBlockSkipRemove(t *testing.T) { generateTestCase := util.JoinPath(tmpEnvPath, TEST_FIXTURE_CODEGEN_PATH, "remove-file", "skip") runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) - assert.FileExists(t, filepath.Join(generateTestCase, "backend.tf")) + require.FileExists(t, filepath.Join(generateTestCase, "backend.tf")) } func TestTerragruntGenerateBlockRemove(t *testing.T) { @@ -3878,7 +3882,7 @@ func TestTerragruntGenerateBlockRemove(t *testing.T) { generateTestCase := util.JoinPath(tmpEnvPath, TEST_FIXTURE_CODEGEN_PATH, "remove-file", "remove") runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) - assert.NoFileExists(t, filepath.Join(generateTestCase, "backend.tf")) + require.NoFileExists(t, filepath.Join(generateTestCase, "backend.tf")) } func TestTerragruntGenerateBlockRemoveTerragruntSuccess(t *testing.T) { @@ -3888,7 +3892,7 @@ func TestTerragruntGenerateBlockRemoveTerragruntSuccess(t *testing.T) { generateTestCase := util.JoinPath(tmpEnvPath, TEST_FIXTURE_CODEGEN_PATH, "remove-file", "remove_terragrunt") runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) - assert.NoFileExists(t, filepath.Join(generateTestCase, "backend.tf")) + require.NoFileExists(t, filepath.Join(generateTestCase, "backend.tf")) } func TestTerragruntGenerateBlockRemoveTerragruntFail(t *testing.T) { @@ -3900,10 +3904,11 @@ func TestTerragruntGenerateBlockRemoveTerragruntFail(t *testing.T) { _, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) require.Error(t, err) - _, ok := errors.Unwrap(err).(codegen.GenerateFileRemoveError) - assert.True(t, ok) + var generateFileRemoveError codegen.GenerateFileRemoveError + ok := goErrors.As(err, &generateFileRemoveError) + require.True(t, ok) - assert.FileExists(t, filepath.Join(generateTestCase, "backend.tf")) + require.FileExists(t, filepath.Join(generateTestCase, "backend.tf")) } func TestTerragruntGenerateBlockSkip(t *testing.T) { @@ -3913,7 +3918,7 @@ func TestTerragruntGenerateBlockSkip(t *testing.T) { cleanupTerraformFolder(t, generateTestCase) cleanupTerragruntFolder(t, generateTestCase) runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) - assert.False(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) + require.False(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) } func TestTerragruntGenerateBlockOverwrite(t *testing.T) { @@ -3925,8 +3930,8 @@ func TestTerragruntGenerateBlockOverwrite(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) // If the state file was written as foo.tfstate, that means it overwrote the local backend config. - assert.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) - assert.False(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) + require.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) + require.False(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) } func TestTerragruntGenerateAttr(t *testing.T) { @@ -3952,8 +3957,8 @@ func TestTerragruntGenerateBlockOverwriteTerragruntSuccess(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) // If the state file was written as foo.tfstate, that means it overwrote the local backend config. - assert.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) - assert.False(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) + require.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) + require.False(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) } func TestTerragruntGenerateBlockOverwriteTerragruntFail(t *testing.T) { @@ -3967,8 +3972,9 @@ func TestTerragruntGenerateBlockOverwriteTerragruntFail(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase), &stdout, &stderr) require.Error(t, err) - _, ok := errors.Unwrap(err).(codegen.GenerateFileExistsError) - assert.True(t, ok) + var generateFileExistsError codegen.GenerateFileExistsError + ok := goErrors.As(err, &generateFileExistsError) + require.True(t, ok) } func TestTerragruntGenerateBlockNestedInherit(t *testing.T) { @@ -3980,10 +3986,10 @@ func TestTerragruntGenerateBlockNestedInherit(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) // If the state file was written as foo.tfstate, that means it inherited the config - assert.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) - assert.False(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) + require.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) + require.False(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) // Also check to make sure the child config generate block was included - assert.True(t, fileIsInFolder(t, "random_file.txt", generateTestCase)) + require.True(t, fileIsInFolder(t, "random_file.txt", generateTestCase)) } func TestTerragruntGenerateBlockNestedOverwrite(t *testing.T) { @@ -3995,10 +4001,10 @@ func TestTerragruntGenerateBlockNestedOverwrite(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) // If the state file was written as bar.tfstate, that means it overwrite the parent config - assert.False(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) - assert.True(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) + require.False(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) + require.True(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) // Also check to make sure the child config generate block was included - assert.True(t, fileIsInFolder(t, "random_file.txt", generateTestCase)) + require.True(t, fileIsInFolder(t, "random_file.txt", generateTestCase)) } func TestTerragruntGenerateBlockDisableSignature(t *testing.T) { @@ -4022,7 +4028,7 @@ func TestTerragruntGenerateBlockDisableSignature(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["text"].Value, "Hello, World!") + require.Equal(t, "Hello, World!", outputs["text"].Value) } func TestTerragruntGenerateBlockSameNameFail(t *testing.T) { @@ -4036,10 +4042,11 @@ func TestTerragruntGenerateBlockSameNameFail(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init --terragrunt-working-dir %s", generateTestCase), &stdout, &stderr) require.Error(t, err) - parsedError, ok := errors.Unwrap(err).(config.DuplicatedGenerateBlocksError) - assert.True(t, ok) - assert.True(t, len(parsedError.BlockName) == 1) - assert.Contains(t, parsedError.BlockName, "backend") + var parsedError config.DuplicatedGenerateBlocksError + ok := goErrors.As(err, &parsedError) + require.True(t, ok) + require.Len(t, parsedError.BlockName, 1) + require.Contains(t, parsedError.BlockName, "backend") } func TestTerragruntGenerateBlockSameNameIncludeFail(t *testing.T) { @@ -4053,10 +4060,11 @@ func TestTerragruntGenerateBlockSameNameIncludeFail(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init --terragrunt-working-dir %s", generateTestCase), &stdout, &stderr) require.Error(t, err) - parsedError, ok := errors.Unwrap(err).(config.DuplicatedGenerateBlocksError) - assert.True(t, ok) - assert.True(t, len(parsedError.BlockName) == 1) - assert.Contains(t, parsedError.BlockName, "backend") + var parsedError config.DuplicatedGenerateBlocksError + ok := goErrors.As(err, &parsedError) + require.True(t, ok) + require.Len(t, parsedError.BlockName, 1) + require.Contains(t, parsedError.BlockName, "backend") } func TestTerragruntGenerateBlockMultipleSameNameFail(t *testing.T) { @@ -4070,11 +4078,12 @@ func TestTerragruntGenerateBlockMultipleSameNameFail(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init --terragrunt-working-dir %s", generateTestCase), &stdout, &stderr) require.Error(t, err) - parsedError, ok := errors.Unwrap(err).(config.DuplicatedGenerateBlocksError) - assert.True(t, ok) - assert.True(t, len(parsedError.BlockName) == 2) - assert.Contains(t, parsedError.BlockName, "backend") - assert.Contains(t, parsedError.BlockName, "backend2") + var parsedError config.DuplicatedGenerateBlocksError + ok := goErrors.As(err, &parsedError) + require.True(t, ok) + require.Len(t, parsedError.BlockName, 2) + require.Contains(t, parsedError.BlockName, "backend") + require.Contains(t, parsedError.BlockName, "backend2") } func TestTerragruntGenerateBlockDisable(t *testing.T) { @@ -4088,7 +4097,7 @@ func TestTerragruntGenerateBlockDisable(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init --terragrunt-working-dir %s", generateTestCase), &stdout, &stderr) require.NoError(t, err) - assert.False(t, fileIsInFolder(t, "data.txt", generateTestCase)) + require.False(t, fileIsInFolder(t, "data.txt", generateTestCase)) } func TestTerragruntGenerateBlockEnable(t *testing.T) { @@ -4102,7 +4111,7 @@ func TestTerragruntGenerateBlockEnable(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init --terragrunt-working-dir %s", generateTestCase), &stdout, &stderr) require.NoError(t, err) - assert.True(t, fileIsInFolder(t, "data.txt", generateTestCase)) + require.True(t, fileIsInFolder(t, "data.txt", generateTestCase)) } func TestTerragruntRemoteStateCodegenGeneratesBackendBlock(t *testing.T) { @@ -4115,7 +4124,7 @@ func TestTerragruntRemoteStateCodegenGeneratesBackendBlock(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) // If the state file was written as foo.tfstate, that means it wrote out the local backend config. - assert.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) + require.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) } func TestTerragruntRemoteStateCodegenOverwrites(t *testing.T) { @@ -4128,8 +4137,8 @@ func TestTerragruntRemoteStateCodegenOverwrites(t *testing.T) { runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) // If the state file was written as foo.tfstate, that means it overwrote the local backend config. - assert.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) - assert.False(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) + require.True(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) + require.False(t, fileIsInFolder(t, "bar.tfstate", generateTestCase)) } func TestTerragruntRemoteStateCodegenGeneratesBackendBlockS3(t *testing.T) { @@ -4163,8 +4172,9 @@ func TestTerragruntRemoteStateCodegenErrorsIfExists(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase), &stdout, &stderr) require.Error(t, err) - _, ok := errors.Unwrap(err).(codegen.GenerateFileExistsError) - assert.True(t, ok) + var generateFileExistsError codegen.GenerateFileExistsError + ok := goErrors.As(err, &generateFileExistsError) + require.True(t, ok) } func TestTerragruntRemoteStateCodegenDoesNotGenerateWithSkip(t *testing.T) { @@ -4176,7 +4186,7 @@ func TestTerragruntRemoteStateCodegenDoesNotGenerateWithSkip(t *testing.T) { cleanupTerragruntFolder(t, generateTestCase) runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", generateTestCase)) - assert.False(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) + require.False(t, fileIsInFolder(t, "foo.tfstate", generateTestCase)) } func TestTerragruntValidateAllWithVersionChecks(t *testing.T) { @@ -4205,9 +4215,9 @@ func TestTerragruntIncludeParentHclFile(t *testing.T) { require.NoError(t, err) out := stdout.String() - assert.Equal(t, 1, strings.Count(out, "parent_hcl_file")) - assert.Equal(t, 1, strings.Count(out, "dependency_hcl")) - assert.Equal(t, 1, strings.Count(out, "common_hcl")) + require.Equal(t, 1, strings.Count(out, "parent_hcl_file")) + require.Equal(t, 1, strings.Count(out, "dependency_hcl")) + require.Equal(t, 1, strings.Count(out, "common_hcl")) } func TestTerragruntVersionConstraints(t *testing.T) { @@ -4279,7 +4289,7 @@ func TestReadTerragruntConfigIamRole(t *testing.T) { t.Parallel() identityArn, err := aws_helper.GetAWSIdentityArn(nil, &options.TerragruntOptions{}) - assert.NoError(t, err) + require.NoError(t, err) cleanupTerraformFolder(t, TEST_FIXTURE_READ_IAM_ROLE) @@ -4294,9 +4304,9 @@ func TestReadTerragruntConfigIamRole(t *testing.T) { output := fmt.Sprintf("%v %v %v", stderr.String(), stdout.String(), err.Error()) // Check that output contains value defined in IAM role - assert.Contains(t, output, "666666666666") + require.Contains(t, output, "666666666666") // Ensure that state file wasn't created with default IAM value - assert.True(t, util.FileNotExists(util.JoinPath(TEST_FIXTURE_READ_IAM_ROLE, identityArn+".txt"))) + require.True(t, util.FileNotExists(util.JoinPath(TEST_FIXTURE_READ_IAM_ROLE, identityArn+".txt"))) } func TestReadTerragruntAuthProviderCmd(t *testing.T) { @@ -4311,14 +4321,14 @@ func TestReadTerragruntAuthProviderCmd(t *testing.T) { runTerragrunt(t, fmt.Sprintf(`terragrunt run-all apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s --terragrunt-auth-provider-cmd %s`, rootPath, mockAuthCmd)) stdout, _, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt output -json --terragrunt-working-dir %s --terragrunt-auth-provider-cmd %s", appPath, mockAuthCmd)) - assert.NoError(t, err) + require.NoError(t, err) outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal([]byte(stdout), &outputs)) - assert.Equal(t, outputs["foo-app1"].Value, "app1-bar") - assert.Equal(t, outputs["foo-app2"].Value, "app2-bar") - assert.Equal(t, outputs["foo-app3"].Value, "app3-bar") + require.Equal(t, "app1-bar", outputs["foo-app1"].Value) + require.Equal(t, "app2-bar", outputs["foo-app2"].Value) + require.Equal(t, "app3-bar", outputs["foo-app3"].Value) } func TestIamRolesLoadingFromDifferentModules(t *testing.T) { @@ -4350,11 +4360,11 @@ func TestIamRolesLoadingFromDifferentModules(t *testing.T) { continue } } - assert.NotEmptyf(t, component1, "Missing role for component 1") - assert.NotEmptyf(t, component2, "Missing role for component 2") + require.NotEmptyf(t, component1, "Missing role for component 1") + require.NotEmptyf(t, component2, "Missing role for component 2") - assert.Contains(t, component1, "iam_roles_multiple_modules/component") - assert.Contains(t, component2, "iam_roles_multiple_modules/component2") + require.Contains(t, component1, "iam_roles_multiple_modules/component") + require.Contains(t, component2, "iam_roles_multiple_modules/component2") } func TestTerragruntVersionConstraintsPartialParse(t *testing.T) { @@ -4368,10 +4378,11 @@ func TestTerragruntVersionConstraintsPartialParse(t *testing.T) { logBufferContentsLineByLine(t, stdout, "stdout") logBufferContentsLineByLine(t, stderr, "stderr") - assert.Error(t, err) + require.Error(t, err) - _, isTgVersionError := errors.Unwrap(err).(terraform.InvalidTerragruntVersion) - assert.True(t, isTgVersionError) + var invalidVersionError terraform.InvalidTerragruntVersion + ok := goErrors.As(err, &invalidVersionError) + require.True(t, ok) } func TestLogFailedLocalsEvaluation(t *testing.T) { @@ -4381,13 +4392,13 @@ func TestLogFailedLocalsEvaluation(t *testing.T) { ) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s --terragrunt-log-level debug", TEST_FIXTURE_BROKEN_LOCALS), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) testdataDir, err := filepath.Abs(TEST_FIXTURE_BROKEN_LOCALS) require.NoError(t, err) output := stderr.String() - assert.Contains(t, output, fmt.Sprintf("Encountered error while evaluating locals in file %s", filepath.Join(testdataDir, "terragrunt.hcl"))) + require.Contains(t, output, fmt.Sprintf("Encountered error while evaluating locals in file %s", filepath.Join(testdataDir, "terragrunt.hcl"))) } func TestLogFailingDependencies(t *testing.T) { @@ -4399,13 +4410,13 @@ func TestLogFailingDependencies(t *testing.T) { path := filepath.Join(TEST_FIXTURE_BROKEN_DEPENDENCY, "app") err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s --terragrunt-log-level debug", path), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) testdataDir, err := filepath.Abs(TEST_FIXTURE_BROKEN_DEPENDENCY) require.NoError(t, err) output := stderr.String() - assert.Contains(t, output, fmt.Sprintf("%s invocation failed in %s", wrappedBinary(), testdataDir)) + require.Contains(t, output, fmt.Sprintf("%s invocation failed in %s", wrappedBinary(), testdataDir)) } func cleanupTerraformFolder(t *testing.T, templatesPath string) { @@ -4622,14 +4633,13 @@ func validateS3BucketExistsAndIsTagged(t *testing.T, awsRegion string, bucketNam t.Fatalf("Error creating S3 client: %v", err) } - remoteStateConfig := remote.RemoteStateConfigS3{Bucket: bucketName, Region: awsRegion} - assert.True(t, remote.DoesS3BucketExist(s3Client, &remoteStateConfig.Bucket), "Terragrunt failed to create remote state S3 bucket %s", bucketName) + require.True(t, remote.DoesS3BucketExist(s3Client, &bucketName), "Terragrunt failed to create remote state S3 bucket %s", bucketName) if expectedTags != nil { - assertS3Tags(expectedTags, bucketName, s3Client, t) + requireS3Tags(expectedTags, bucketName, s3Client, t) } - assertS3PublicAccessBlocks(t, s3Client, bucketName) + requireS3PublicAccessBlocks(t, s3Client, bucketName) } // Check that the DynamoDB table of the given name and region exists. Terragrunt should create this table during the test. @@ -4656,10 +4666,10 @@ func validateDynamoDBTableExistsAndIsTagged(t *testing.T, awsRegion string, tabl actualTags[*element.Key] = *element.Value } - assert.Equal(t, expectedTags, actualTags, "Did not find expected tags on dynamo table.") + require.Equal(t, expectedTags, actualTags, "Did not find expected tags on dynamo table.") } -func assertS3Tags(expectedTags map[string]string, bucketName string, client *s3.S3, t *testing.T) { +func requireS3Tags(expectedTags map[string]string, bucketName string, client *s3.S3, t *testing.T) { var in = s3.GetBucketTaggingInput{} in.SetBucket(bucketName) @@ -4676,20 +4686,20 @@ func assertS3Tags(expectedTags map[string]string, bucketName string, client *s3. actualTags[*element.Key] = *element.Value } - assert.Equal(t, expectedTags, actualTags, "Did not find expected tags on s3 bucket.") + require.Equal(t, expectedTags, actualTags, "Did not find expected tags on s3 bucket.") } -func assertS3PublicAccessBlocks(t *testing.T, client *s3.S3, bucketName string) { +func requireS3PublicAccessBlocks(t *testing.T, client *s3.S3, bucketName string) { resp, err := client.GetPublicAccessBlock( &s3.GetPublicAccessBlockInput{Bucket: aws.String(bucketName)}, ) require.NoError(t, err) publicAccessBlockConfig := resp.PublicAccessBlockConfiguration - assert.True(t, aws.BoolValue(publicAccessBlockConfig.BlockPublicAcls)) - assert.True(t, aws.BoolValue(publicAccessBlockConfig.BlockPublicPolicy)) - assert.True(t, aws.BoolValue(publicAccessBlockConfig.IgnorePublicAcls)) - assert.True(t, aws.BoolValue(publicAccessBlockConfig.RestrictPublicBuckets)) + require.True(t, aws.BoolValue(publicAccessBlockConfig.BlockPublicAcls)) + require.True(t, aws.BoolValue(publicAccessBlockConfig.BlockPublicPolicy)) + require.True(t, aws.BoolValue(publicAccessBlockConfig.IgnorePublicAcls)) + require.True(t, aws.BoolValue(publicAccessBlockConfig.RestrictPublicBuckets)) } // createS3BucketE create test S3 bucket. @@ -4808,7 +4818,8 @@ func bucketEncryption(t *testing.T, awsRegion string, bucketName string) (*s3.Ge input := &s3.GetBucketEncryptionInput{Bucket: aws.String(bucketName)} output, err := s3Client.GetBucketEncryption(input) if err != nil { - return nil, nil + // TODO: Remove this lint suppression + return nil, nil //nolint:nilerr } return output, nil @@ -4870,7 +4881,7 @@ func createDynamoDbClientForTest(t *testing.T, awsRegion string) *dynamodb.Dynam func cleanupTableForTest(t *testing.T, tableName string, awsRegion string) { client := createDynamoDbClientForTest(t, awsRegion) err := terragruntDynamoDb.DeleteTable(tableName, client) - assert.NoError(t, err) + require.NoError(t, err) } // Check that the GCS Bucket of the given name and location exists. Terragrunt should create this bucket during the test. @@ -4884,7 +4895,7 @@ func validateGCSBucketExistsAndIsLabeled(t *testing.T, location string, bucketNa } // verify the bucket exists - assert.True(t, remote.DoesGCSBucketExist(gcsClient, &remoteStateConfig), "Terragrunt failed to create remote state GCS bucket %s", bucketName) + require.True(t, remote.DoesGCSBucketExist(gcsClient, &remoteStateConfig), "Terragrunt failed to create remote state GCS bucket %s", bucketName) // verify the bucket location ctx := context.Background() @@ -4894,10 +4905,10 @@ func validateGCSBucketExistsAndIsLabeled(t *testing.T, location string, bucketNa t.Fatal(err) } - assert.Equal(t, strings.ToUpper(location), attrs.Location, "Did not find GCS bucket in expected location.") + require.Equal(t, strings.ToUpper(location), attrs.Location, "Did not find GCS bucket in expected location.") if expectedLabels != nil { - assertGCSLabels(t, expectedLabels, bucketName, gcsClient) + requireGCSLabels(t, expectedLabels, bucketName, gcsClient) } } @@ -4921,7 +4932,7 @@ func gcsObjectAttrs(t *testing.T, bucketName string, objectName string) *storage return attrs } -func assertGCSLabels(t *testing.T, expectedLabels map[string]string, bucketName string, client *storage.Client) { +func requireGCSLabels(t *testing.T, expectedLabels map[string]string, bucketName string, client *storage.Client) { ctx := context.Background() bucket := client.Bucket(bucketName) @@ -4936,7 +4947,7 @@ func assertGCSLabels(t *testing.T, expectedLabels map[string]string, bucketName actualLabels[key] = value } - assert.Equal(t, expectedLabels, actualLabels, "Did not find expected labels on GCS bucket.") + require.Equal(t, expectedLabels, actualLabels, "Did not find expected labels on GCS bucket.") } // Create the specified GCS bucket @@ -4983,7 +4994,7 @@ func deleteGCSBucket(t *testing.T, bucketName string) { for { objectAttrs, err := it.Next() - if err == iterator.Done { + if goErrors.Is(err, iterator.Done) { break } @@ -5006,7 +5017,7 @@ func deleteGCSBucket(t *testing.T, bucketName string) { func fileIsInFolder(t *testing.T, name string, path string) bool { found := false err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { - assert.NoError(t, err) + require.NoError(t, err) if filepath.Base(path) == name { found = true } @@ -5085,19 +5096,19 @@ func TestSopsDecryptedCorrectly(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["json_bool_array"].Value, []interface{}{true, false}) - assert.Equal(t, outputs["json_string_array"].Value, []interface{}{"example_value1", "example_value2"}) - assert.Equal(t, outputs["json_number"].Value, 1234.56789) - assert.Equal(t, outputs["json_string"].Value, "example_value") - assert.Equal(t, outputs["json_hello"].Value, "Welcome to SOPS! Edit this file as you please!") - assert.Equal(t, outputs["yaml_bool_array"].Value, []interface{}{true, false}) - assert.Equal(t, outputs["yaml_string_array"].Value, []interface{}{"example_value1", "example_value2"}) - assert.Equal(t, outputs["yaml_number"].Value, 1234.5679) - assert.Equal(t, outputs["yaml_string"].Value, "example_value") - assert.Equal(t, outputs["yaml_hello"].Value, "Welcome to SOPS! Edit this file as you please!") - assert.Equal(t, outputs["text_value"].Value, "Raw Secret Example") - assert.Contains(t, outputs["env_value"].Value, "DB_PASSWORD=tomato") - assert.Contains(t, outputs["ini_value"].Value, "password = potato") + require.Equal(t, []interface{}{true, false}, outputs["json_bool_array"].Value) + require.Equal(t, []interface{}{"example_value1", "example_value2"}, outputs["json_string_array"].Value) + require.InEpsilon(t, 1234.56789, outputs["json_number"].Value, 0.0001) + require.Equal(t, "example_value", outputs["json_string"].Value) + require.Equal(t, "Welcome to SOPS! Edit this file as you please!", outputs["json_hello"].Value) + require.Equal(t, []interface{}{true, false}, outputs["yaml_bool_array"].Value) + require.Equal(t, []interface{}{"example_value1", "example_value2"}, outputs["yaml_string_array"].Value) + require.InEpsilon(t, 1234.5679, outputs["yaml_number"].Value, 0.0001) + require.Equal(t, "example_value", outputs["yaml_string"].Value) + require.Equal(t, "Welcome to SOPS! Edit this file as you please!", outputs["yaml_hello"].Value) + require.Equal(t, "Raw Secret Example", outputs["text_value"].Value) + require.Contains(t, outputs["env_value"].Value, "DB_PASSWORD=tomato") + require.Contains(t, outputs["ini_value"].Value, "password = potato") } func TestSopsDecryptedCorrectlyRunAll(t *testing.T) { @@ -5118,19 +5129,19 @@ func TestSopsDecryptedCorrectlyRunAll(t *testing.T) { outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, outputs["json_bool_array"].Value, []interface{}{true, false}) - assert.Equal(t, outputs["json_string_array"].Value, []interface{}{"example_value1", "example_value2"}) - assert.Equal(t, outputs["json_number"].Value, 1234.56789) - assert.Equal(t, outputs["json_string"].Value, "example_value") - assert.Equal(t, outputs["json_hello"].Value, "Welcome to SOPS! Edit this file as you please!") - assert.Equal(t, outputs["yaml_bool_array"].Value, []interface{}{true, false}) - assert.Equal(t, outputs["yaml_string_array"].Value, []interface{}{"example_value1", "example_value2"}) - assert.Equal(t, outputs["yaml_number"].Value, 1234.5679) - assert.Equal(t, outputs["yaml_string"].Value, "example_value") - assert.Equal(t, outputs["yaml_hello"].Value, "Welcome to SOPS! Edit this file as you please!") - assert.Equal(t, outputs["text_value"].Value, "Raw Secret Example") - assert.Contains(t, outputs["env_value"].Value, "DB_PASSWORD=tomato") - assert.Contains(t, outputs["ini_value"].Value, "password = potato") + require.Equal(t, []interface{}{true, false}, outputs["json_bool_array"].Value) + require.Equal(t, []interface{}{"example_value1", "example_value2"}, outputs["json_string_array"].Value) + require.InEpsilon(t, 1234.56789, outputs["json_number"].Value, 0.0001) + require.Equal(t, "example_value", outputs["json_string"].Value) + require.Equal(t, "Welcome to SOPS! Edit this file as you please!", outputs["json_hello"].Value) + require.Equal(t, []interface{}{true, false}, outputs["yaml_bool_array"].Value) + require.Equal(t, []interface{}{"example_value1", "example_value2"}, outputs["yaml_string_array"].Value) + require.InEpsilon(t, 1234.5679, outputs["yaml_number"].Value, 0.0001) + require.Equal(t, "example_value", outputs["yaml_string"].Value) + require.Equal(t, "Welcome to SOPS! Edit this file as you please!", outputs["yaml_hello"].Value) + require.Equal(t, "Raw Secret Example", outputs["text_value"].Value) + require.Contains(t, outputs["env_value"].Value, "DB_PASSWORD=tomato") + require.Contains(t, outputs["ini_value"].Value, "password = potato") } func TestTerragruntRunAllCommandPrompt(t *testing.T) { @@ -5150,8 +5161,8 @@ func TestTerragruntRunAllCommandPrompt(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt run-all apply --terragrunt-working-dir %s", environmentPath), &stdout, &stderr) logBufferContentsLineByLine(t, stdout, "stdout") logBufferContentsLineByLine(t, stderr, "stderr") - assert.Contains(t, stderr.String(), "Are you sure you want to run 'terragrunt apply' in each folder of the stack described above? (y/n)") - assert.Error(t, err) + require.Contains(t, stderr.String(), "Are you sure you want to run 'terragrunt apply' in each folder of the stack described above? (y/n)") + require.Error(t, err) } func TestTerragruntLocalRunOnce(t *testing.T) { @@ -5162,11 +5173,11 @@ func TestTerragruntLocalRunOnce(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init --terragrunt-working-dir %s", TEST_FIXTURE_LOCAL_RUN_ONCE), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) errout := stdout.String() - assert.Equal(t, 1, strings.Count(errout, "foo")) + require.Equal(t, 1, strings.Count(errout, "foo")) } func TestTerragruntInitRunCmd(t *testing.T) { @@ -5177,22 +5188,22 @@ func TestTerragruntInitRunCmd(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init --terragrunt-working-dir %s", TEST_FIXTURE_LOCAL_RUN_MULTIPLE), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) errout := stdout.String() // Check for cached values between locals and inputs sections - assert.Equal(t, 1, strings.Count(errout, "potato")) - assert.Equal(t, 1, strings.Count(errout, "carrot")) - assert.Equal(t, 1, strings.Count(errout, "bar")) - assert.Equal(t, 1, strings.Count(errout, "foo")) + require.Equal(t, 1, strings.Count(errout, "potato")) + require.Equal(t, 1, strings.Count(errout, "carrot")) + require.Equal(t, 1, strings.Count(errout, "bar")) + require.Equal(t, 1, strings.Count(errout, "foo")) - assert.Equal(t, 1, strings.Count(errout, "input_variable")) + require.Equal(t, 1, strings.Count(errout, "input_variable")) // Commands executed multiple times because of different arguments - assert.Equal(t, 4, strings.Count(errout, "uuid")) - assert.Equal(t, 6, strings.Count(errout, "random_arg")) - assert.Equal(t, 4, strings.Count(errout, "another_arg")) + require.Equal(t, 4, strings.Count(errout, "uuid")) + require.Equal(t, 6, strings.Count(errout, "random_arg")) + require.Equal(t, 4, strings.Count(errout, "another_arg")) } func TestShowWarningWithDependentModulesBeforeDestroy(t *testing.T) { @@ -5211,20 +5222,20 @@ func TestShowWarningWithDependentModulesBeforeDestroy(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt run-all init --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) err = runTerragruntCommand(t, fmt.Sprintf("terragrunt run-all apply --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) // try to destroy vpc module and check if warning is printed in output stdout = bytes.Buffer{} stderr = bytes.Buffer{} err = runTerragruntCommand(t, fmt.Sprintf("terragrunt destroy --terragrunt-non-interactive --terragrunt-working-dir %s", vpcPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) output := stderr.String() - assert.Equal(t, 1, strings.Count(output, appV1Path)) - assert.Equal(t, 1, strings.Count(output, appV2Path)) + require.Equal(t, 1, strings.Count(output, appV1Path)) + require.Equal(t, 1, strings.Count(output, appV2Path)) } func TestTerragruntOutputFromRemoteState(t *testing.T) { @@ -5260,12 +5271,12 @@ func TestTerragruntOutputFromRemoteState(t *testing.T) { runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt run-all output --terragrunt-fetch-dependency-output-from-state --terragrunt-non-interactive --terragrunt-log-level debug --terragrunt-working-dir %s", environmentPath), &stdout, &stderr) output := stdout.String() - assert.True(t, strings.Contains(output, "app1 output")) - assert.True(t, strings.Contains(output, "app2 output")) - assert.True(t, strings.Contains(output, "app3 output")) - assert.False(t, strings.Contains(stderr.String(), "terraform output -json")) + require.True(t, strings.Contains(output, "app1 output")) + require.True(t, strings.Contains(output, "app2 output")) + require.True(t, strings.Contains(output, "app3 output")) + require.False(t, strings.Contains(stderr.String(), "terraform output -json")) - assert.True(t, (strings.Index(output, "app3 output") < strings.Index(output, "app1 output")) && (strings.Index(output, "app1 output") < strings.Index(output, "app2 output"))) + require.True(t, (strings.Index(output, "app3 output") < strings.Index(output, "app1 output")) && (strings.Index(output, "app1 output") < strings.Index(output, "app2 output"))) } func TestShowErrorWhenRunAllInvokedWithoutArguments(t *testing.T) { @@ -5278,8 +5289,9 @@ func TestShowErrorWhenRunAllInvokedWithoutArguments(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt run-all --terragrunt-non-interactive --terragrunt-working-dir %s", appPath), &stdout, &stderr) require.Error(t, err) - _, ok := errors.Unwrap(err).(runall.MissingCommand) - assert.True(t, ok) + var missingCommandError runall.MissingCommand + ok := goErrors.As(err, &missingCommandError) + require.True(t, ok) } func TestPathRelativeToIncludeInvokedInCorrectPathFromChild(t *testing.T) { @@ -5292,8 +5304,8 @@ func TestPathRelativeToIncludeInvokedInCorrectPathFromChild(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt version --terragrunt-log-level trace --terragrunt-non-interactive --terragrunt-working-dir %s", appPath), &stdout, &stderr) require.NoError(t, err) output := stdout.String() - assert.Equal(t, 1, strings.Count(output, "path_relative_to_inclue: app\n")) - assert.Equal(t, 0, strings.Count(output, "path_relative_to_inclue: .\n")) + require.Equal(t, 1, strings.Count(output, "path_relative_to_inclue: app\n")) + require.Equal(t, 0, strings.Count(output, "path_relative_to_inclue: .\n")) } func TestTerragruntInitConfirmation(t *testing.T) { @@ -5311,7 +5323,7 @@ func TestTerragruntInitConfirmation(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt run-all init --terragrunt-working-dir %s", tmpEnvPath), &stdout, &stderr) require.Error(t, err) errout := stderr.String() - assert.Equal(t, 1, strings.Count(errout, "does not exist or you don't have permissions to access it. Would you like Terragrunt to create it? (y/n)")) + require.Equal(t, 1, strings.Count(errout, "does not exist or you don't have permissions to access it. Would you like Terragrunt to create it? (y/n)")) } func TestNoMultipleInitsWithoutSourceChange(t *testing.T) { @@ -5327,7 +5339,7 @@ func TestNoMultipleInitsWithoutSourceChange(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) require.NoError(t, err) // providers initialization during first plan - assert.Equal(t, 1, strings.Count(stdout.String(), "has been successfully initialized!")) + require.Equal(t, 1, strings.Count(stdout.String(), "has been successfully initialized!")) stdout = bytes.Buffer{} stderr = bytes.Buffer{} @@ -5336,7 +5348,7 @@ func TestNoMultipleInitsWithoutSourceChange(t *testing.T) { require.NoError(t, err) // no initialization expected for second plan run // https://github.com/gruntwork-io/terragrunt/issues/1921 - assert.Equal(t, 0, strings.Count(stdout.String(), "has been successfully initialized!")) + require.Equal(t, 0, strings.Count(stdout.String(), "has been successfully initialized!")) } func TestAutoInitWhenSourceIsChanged(t *testing.T) { @@ -5360,7 +5372,7 @@ func TestAutoInitWhenSourceIsChanged(t *testing.T) { err = runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) require.NoError(t, err) // providers initialization during first plan - assert.Equal(t, 1, strings.Count(stdout.String(), "has been successfully initialized!")) + require.Equal(t, 1, strings.Count(stdout.String(), "has been successfully initialized!")) updatedHcl = strings.ReplaceAll(contents, "__TAG_VALUE__", "v0.35.2") require.NoError(t, os.WriteFile(terragruntHcl, []byte(updatedHcl), 0444)) @@ -5371,7 +5383,7 @@ func TestAutoInitWhenSourceIsChanged(t *testing.T) { err = runTerragruntCommand(t, fmt.Sprintf("terragrunt plan --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) require.NoError(t, err) // auto initialization when source is changed - assert.Equal(t, 1, strings.Count(stdout.String(), "has been successfully initialized!")) + require.Equal(t, 1, strings.Count(stdout.String(), "has been successfully initialized!")) } func TestNoColor(t *testing.T) { @@ -5387,9 +5399,9 @@ func TestNoColor(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan -no-color --terragrunt-working-dir %s", testPath), &stdout, &stderr) require.NoError(t, err) // providers initialization during first plan - assert.Equal(t, 1, strings.Count(stdout.String(), "has been successfully initialized!")) + require.Equal(t, 1, strings.Count(stdout.String(), "has been successfully initialized!")) - assert.NotContains(t, stdout.String(), "[") + require.NotContains(t, stdout.String(), "[") } func TestRenderJsonAttributesMetadata(t *testing.T) { @@ -5426,7 +5438,7 @@ func TestRenderJsonAttributesMetadata(t *testing.T) { "value": "us-east-1", }, } - assert.True(t, reflect.DeepEqual(expectedInputs, inputs)) + require.True(t, reflect.DeepEqual(expectedInputs, inputs)) var locals = renderedJson[config.MetadataLocals] var expectedLocals = map[string]interface{}{ @@ -5435,63 +5447,63 @@ func TestRenderJsonAttributesMetadata(t *testing.T) { "value": "us-east-1", }, } - assert.True(t, reflect.DeepEqual(expectedLocals, locals)) + require.True(t, reflect.DeepEqual(expectedLocals, locals)) var downloadDir = renderedJson[config.MetadataDownloadDir] var expecteDownloadDir = map[string]interface{}{ "metadata": expectedMetadata, "value": "/tmp", } - assert.True(t, reflect.DeepEqual(expecteDownloadDir, downloadDir)) + require.True(t, reflect.DeepEqual(expecteDownloadDir, downloadDir)) var iamAssumeRoleDuration = renderedJson[config.MetadataIamAssumeRoleDuration] expectedIamAssumeRoleDuration := map[string]interface{}{ "metadata": expectedMetadata, "value": float64(666), } - assert.True(t, reflect.DeepEqual(expectedIamAssumeRoleDuration, iamAssumeRoleDuration)) + require.True(t, reflect.DeepEqual(expectedIamAssumeRoleDuration, iamAssumeRoleDuration)) var iamAssumeRoleName = renderedJson[config.MetadataIamAssumeRoleSessionName] expectedIamAssumeRoleName := map[string]interface{}{ "metadata": expectedMetadata, "value": "qwe", } - assert.True(t, reflect.DeepEqual(expectedIamAssumeRoleName, iamAssumeRoleName)) + require.True(t, reflect.DeepEqual(expectedIamAssumeRoleName, iamAssumeRoleName)) var iamRole = renderedJson[config.MetadataIamRole] expectedIamRole := map[string]interface{}{ "metadata": expectedMetadata, "value": "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME", } - assert.True(t, reflect.DeepEqual(expectedIamRole, iamRole)) + require.True(t, reflect.DeepEqual(expectedIamRole, iamRole)) var preventDestroy = renderedJson[config.MetadataPreventDestroy] expectedPreventDestroy := map[string]interface{}{ "metadata": expectedMetadata, "value": true, } - assert.True(t, reflect.DeepEqual(expectedPreventDestroy, preventDestroy)) + require.True(t, reflect.DeepEqual(expectedPreventDestroy, preventDestroy)) var skip = renderedJson[config.MetadataSkip] expectedSkip := map[string]interface{}{ "metadata": expectedMetadata, "value": true, } - assert.True(t, reflect.DeepEqual(expectedSkip, skip)) + require.True(t, reflect.DeepEqual(expectedSkip, skip)) var terraformBinary = renderedJson[config.MetadataTerraformBinary] expectedTerraformBinary := map[string]interface{}{ "metadata": expectedMetadata, "value": wrappedBinary(), } - assert.True(t, reflect.DeepEqual(expectedTerraformBinary, terraformBinary)) + require.True(t, reflect.DeepEqual(expectedTerraformBinary, terraformBinary)) var terraformVersionConstraint = renderedJson[config.MetadataTerraformVersionConstraint] expectedTerraformVersionConstraint := map[string]interface{}{ "metadata": expectedMetadata, "value": ">= 0.11", } - assert.True(t, reflect.DeepEqual(expectedTerraformVersionConstraint, terraformVersionConstraint)) + require.True(t, reflect.DeepEqual(expectedTerraformVersionConstraint, terraformVersionConstraint)) } func TestOutputModuleGroups(t *testing.T) { @@ -5564,7 +5576,7 @@ func TestOutputModuleGroups(t *testing.T) { runTerragruntRedirectOutput(t, fmt.Sprintf("terragrunt output-module-groups --terragrunt-working-dir %s %s", environmentPath, tt.subCommand), &stdout, &stderr) output := strings.ReplaceAll(stdout.String(), " ", "") expectedOutput := strings.ReplaceAll(strings.ReplaceAll(tt.expectedOutput, "\t", ""), " ", "") - assert.True(t, strings.Contains(strings.TrimSpace(output), strings.TrimSpace(expectedOutput))) + require.True(t, strings.Contains(strings.TrimSpace(output), strings.TrimSpace(expectedOutput))) }) } } @@ -5604,7 +5616,7 @@ func TestRenderJsonMetadataDependency(t *testing.T) { "value": "test_value", }, } - assert.True(t, reflect.DeepEqual(expectedInputs, inputs)) + require.True(t, reflect.DeepEqual(expectedInputs, inputs)) var dependencies = renderedJson[config.MetadataDependencies] var expectedDependencies = []interface{}{ @@ -5617,7 +5629,7 @@ func TestRenderJsonMetadataDependency(t *testing.T) { "value": "../dependency1", }, } - assert.True(t, reflect.DeepEqual(expectedDependencies, dependencies)) + require.True(t, reflect.DeepEqual(expectedDependencies, dependencies)) } func TestRenderJsonWithMockOutputs(t *testing.T) { @@ -5664,11 +5676,11 @@ func TestRenderJsonWithMockOutputs(t *testing.T) { }, } serializedDependency, err := json.Marshal(dependency) - assert.NoError(t, err) + require.NoError(t, err) serializedExpectedDependency, err := json.Marshal(expectedDependency) - assert.NoError(t, err) - assert.Equal(t, string(serializedExpectedDependency), string(serializedDependency)) + require.NoError(t, err) + require.Equal(t, string(serializedExpectedDependency), string(serializedDependency)) } func TestRenderJsonMetadataIncludes(t *testing.T) { @@ -5721,7 +5733,7 @@ func TestRenderJsonMetadataIncludes(t *testing.T) { "value": "123", }, } - assert.True(t, reflect.DeepEqual(expectedInputs, inputs)) + require.True(t, reflect.DeepEqual(expectedInputs, inputs)) var locals = renderedJson[config.MetadataLocals] var expectedLocals = map[string]interface{}{ @@ -5730,7 +5742,7 @@ func TestRenderJsonMetadataIncludes(t *testing.T) { "value": "xyz", }, } - assert.True(t, reflect.DeepEqual(expectedLocals, locals)) + require.True(t, reflect.DeepEqual(expectedLocals, locals)) var generate = renderedJson[config.MetadataGenerateConfigs] var expectedGenerate = map[string]interface{}{ @@ -5750,12 +5762,12 @@ func TestRenderJsonMetadataIncludes(t *testing.T) { // compare fields by serialization in json since map from "value" field is not deterministic serializedGenerate, err := json.Marshal(generate) - assert.NoError(t, err) + require.NoError(t, err) serializedExpectedGenerate, err := json.Marshal(expectedGenerate) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, string(serializedExpectedGenerate), string(serializedGenerate)) + require.Equal(t, string(serializedExpectedGenerate), string(serializedGenerate)) var remoteState = renderedJson[config.MetadataRemoteState] var expectedRemoteState = map[string]interface{}{ @@ -5775,12 +5787,12 @@ func TestRenderJsonMetadataIncludes(t *testing.T) { // compare fields by serialization in json since map from "value" field is not deterministic serializedRemoteState, err := json.Marshal(remoteState) - assert.NoError(t, err) + require.NoError(t, err) serializedExpectedRemoteState, err := json.Marshal(expectedRemoteState) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, string(serializedExpectedRemoteState), string(serializedRemoteState)) + require.Equal(t, string(serializedExpectedRemoteState), string(serializedRemoteState)) } func TestRenderJsonMetadataDepenency(t *testing.T) { @@ -5847,12 +5859,12 @@ func TestRenderJsonMetadataDepenency(t *testing.T) { // compare fields by serialization in json since map from "value" field is not deterministic serializedDependency, err := json.Marshal(dependency) - assert.NoError(t, err) + require.NoError(t, err) serializedExpectedDependency, err := json.Marshal(expectedDependency) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, string(serializedExpectedDependency), string(serializedDependency)) + require.Equal(t, string(serializedExpectedDependency), string(serializedDependency)) } func TestRenderJsonMetadataTerraform(t *testing.T) { @@ -5896,12 +5908,12 @@ func TestRenderJsonMetadataTerraform(t *testing.T) { // compare fields by serialization in json since map from "value" field is not deterministic serializedTerraform, err := json.Marshal(terraform) - assert.NoError(t, err) + require.NoError(t, err) serializedExpectedTerraform, err := json.Marshal(expectedTerraform) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, string(serializedExpectedTerraform), string(serializedTerraform)) + require.Equal(t, string(serializedExpectedTerraform), string(serializedTerraform)) var remoteState = renderedJson[config.MetadataRemoteState] var expectedRemoteState = map[string]interface{}{ @@ -5921,12 +5933,12 @@ func TestRenderJsonMetadataTerraform(t *testing.T) { // compare fields by serialization in json since map from "value" field is not deterministic serializedRemoteState, err := json.Marshal(remoteState) - assert.NoError(t, err) + require.NoError(t, err) serializedExpectedRemoteState, err := json.Marshal(expectedRemoteState) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, string(serializedExpectedRemoteState), string(serializedRemoteState)) + require.Equal(t, string(serializedExpectedRemoteState), string(serializedRemoteState)) } func TestTerragruntRenderJsonHelp(t *testing.T) { @@ -5940,14 +5952,14 @@ func TestTerragruntRenderJsonHelp(t *testing.T) { showStderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt render-json --help --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &showStdout, &showStderr) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, showStdout, "show stdout") output := showStdout.String() - assert.Contains(t, output, "terragrunt render-json") - assert.Contains(t, output, "--with-metadata") + require.Contains(t, output, "terragrunt render-json") + require.Contains(t, output, "--with-metadata") } func TestStartsWith(t *testing.T) { @@ -6128,7 +6140,7 @@ func TestInitFailureModulePrefix(t *testing.T) { runTerragruntCommand(t, fmt.Sprintf("terragrunt init -no-color --terragrunt-include-module-prefix --terragrunt-non-interactive --terragrunt-working-dir %s", initTestCase), &stdout, &stderr), ) logBufferContentsLineByLine(t, stderr, "init") - assert.Contains(t, stderr.String(), "[fixture-init-error] Error") + require.Contains(t, stderr.String(), "[fixture-init-error] Error") } func TestDependencyOutputModulePrefix(t *testing.T) { @@ -6152,7 +6164,7 @@ func TestDependencyOutputModulePrefix(t *testing.T) { // validate that output is valid json outputs := map[string]TerraformOutput{} require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) - assert.Equal(t, int(outputs["z"].Value.(float64)), 42) + require.Equal(t, 42, int(outputs["z"].Value.(float64))) } func TestErrorExplaining(t *testing.T) { @@ -6168,10 +6180,10 @@ func TestErrorExplaining(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init -no-color --terragrunt-include-module-prefix --terragrunt-non-interactive --terragrunt-working-dir %s", initTestCase), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) explanation := shell.ExplainError(err) - assert.Contains(t, explanation, "Check your credentials and permissions") + require.Contains(t, explanation, "Check your credentials and permissions") } func TestExplainingMissingCredentials(t *testing.T) { @@ -6191,7 +6203,7 @@ func TestExplainingMissingCredentials(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt init -no-color --terragrunt-include-module-prefix --terragrunt-non-interactive --terragrunt-working-dir %s", initTestCase), &stdout, &stderr) explanation := shell.ExplainError(err) - assert.Contains(t, explanation, "Missing AWS credentials") + require.Contains(t, explanation, "Missing AWS credentials") } func TestModulePathInPlanErrorMessage(t *testing.T) { @@ -6204,10 +6216,10 @@ func TestModulePathInPlanErrorMessage(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt plan -no-color --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) output := fmt.Sprintf("%s\n%s\n%v\n", stdout.String(), stderr.String(), err.Error()) - assert.Contains(t, output, fmt.Sprintf("prefix=[%s]", util.JoinPath(tmpEnvPath, TEST_FIXTURE_MODULE_PATH_ERROR, "d1"))) - assert.Contains(t, output, "1 error occurred") + require.Contains(t, output, fmt.Sprintf("prefix=[%s]", util.JoinPath(tmpEnvPath, TEST_FIXTURE_MODULE_PATH_ERROR, "d1"))) + require.Contains(t, output, "1 error occurred") } func TestModulePathInRunAllPlanErrorMessage(t *testing.T) { @@ -6220,10 +6232,10 @@ func TestModulePathInRunAllPlanErrorMessage(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt run-all plan -no-color --terragrunt-non-interactive --terragrunt-working-dir %s", rootPath), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) output := fmt.Sprintf("%s\n%s\n%v\n", stdout.String(), stderr.String(), err.Error()) - assert.Contains(t, output, "finished with an error") - assert.Contains(t, output, fmt.Sprintf("Module %s", util.JoinPath(tmpEnvPath, TEST_FIXTURE_MODULE_PATH_ERROR, "d1"))) + require.Contains(t, output, "finished with an error") + require.Contains(t, output, fmt.Sprintf("Module %s", util.JoinPath(tmpEnvPath, TEST_FIXTURE_MODULE_PATH_ERROR, "d1"))) } @@ -6245,10 +6257,10 @@ func TestHclFmtDiff(t *testing.T) { output := stdout.String() expectedDiff, err := os.ReadFile(util.JoinPath(rootPath, "expected.diff")) - assert.NoError(t, err) + require.NoError(t, err) logBufferContentsLineByLine(t, stdout, "output") - assert.Contains(t, output, string(expectedDiff)) + require.Contains(t, output, string(expectedDiff)) } func TestDestroyDependentModule(t *testing.T) { @@ -6274,13 +6286,13 @@ func TestDestroyDependentModule(t *testing.T) { stderr := bytes.Buffer{} err = runTerragruntCommand(t, fmt.Sprintf("terragrunt destroy -auto-approve --terragrunt-non-interactive --terragrunt-log-level debug --terragrunt-working-dir %s", util.JoinPath(rootPath, "c")), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) - assert.True(t, strings.Contains(stderr.String(), util.JoinPath(rootPath, "b", "terragrunt.hcl"))) - assert.True(t, strings.Contains(stderr.String(), util.JoinPath(rootPath, "a", "terragrunt.hcl"))) + require.True(t, strings.Contains(stderr.String(), util.JoinPath(rootPath, "b", "terragrunt.hcl"))) + require.True(t, strings.Contains(stderr.String(), util.JoinPath(rootPath, "a", "terragrunt.hcl"))) - assert.True(t, strings.Contains(stderr.String(), "\"value\": \"module-b.txt\"")) - assert.True(t, strings.Contains(stderr.String(), "\"value\": \"module-a.txt\"")) + require.True(t, strings.Contains(stderr.String(), "\"value\": \"module-b.txt\"")) + require.True(t, strings.Contains(stderr.String(), "\"value\": \"module-a.txt\"")) } func TestDownloadSourceWithRef(t *testing.T) { @@ -6353,8 +6365,8 @@ func TestInitSkipCache(t *testing.T) { ) // verify that init was invoked - assert.Contains(t, stdout.String(), "has been successfully initialized!") - assert.Contains(t, stderr.String(), "Running command: "+wrappedBinary()+" init") + require.Contains(t, stdout.String(), "has been successfully initialized!") + require.Contains(t, stderr.String(), "Running command: "+wrappedBinary()+" init") stdout = bytes.Buffer{} stderr = bytes.Buffer{} @@ -6365,8 +6377,8 @@ func TestInitSkipCache(t *testing.T) { ) // verify that init wasn't invoked second time since cache directories are ignored - assert.NotContains(t, stdout.String(), "has been successfully initialized!") - assert.NotContains(t, stderr.String(), "Running command: "+wrappedBinary()+" init") + require.NotContains(t, stdout.String(), "has been successfully initialized!") + require.NotContains(t, stderr.String(), "Running command: "+wrappedBinary()+" init") // verify that after adding new file, init is executed tfFile := util.JoinPath(tmpEnvPath, TEST_FIXTURE_INIT_CACHE, "app", "project.tf") @@ -6383,8 +6395,8 @@ func TestInitSkipCache(t *testing.T) { ) // verify that init was invoked - assert.Contains(t, stdout.String(), "has been successfully initialized!") - assert.Contains(t, stderr.String(), "Running command: "+wrappedBinary()+" init") + require.Contains(t, stdout.String(), "has been successfully initialized!") + require.Contains(t, stderr.String(), "Running command: "+wrappedBinary()+" init") } func TestRenderJsonWithInputsNotExistingOutput(t *testing.T) { @@ -6425,7 +6437,7 @@ func TestRenderJsonWithInputsNotExistingOutput(t *testing.T) { "value": "", }, } - assert.True(t, reflect.DeepEqual(expectedInputs, inputs)) + require.True(t, reflect.DeepEqual(expectedInputs, inputs)) } func TestTerragruntFailIfBucketCreationIsRequired(t *testing.T) { @@ -6443,7 +6455,7 @@ func TestTerragruntFailIfBucketCreationIsRequired(t *testing.T) { stdout := bytes.Buffer{} stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply --terragrunt-fail-on-state-bucket-creation --terragrunt-non-interactive --terragrunt-config %s --terragrunt-working-dir %s", tmpTerragruntConfigPath, rootPath), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) } func TestTerragruntDisableBucketUpdate(t *testing.T) { @@ -6457,7 +6469,7 @@ func TestTerragruntDisableBucketUpdate(t *testing.T) { lockTableName := fmt.Sprintf("terragrunt-test-locks-%s", strings.ToLower(uniqueId())) err := createS3BucketE(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) - assert.NoError(t, err) + require.NoError(t, err) defer deleteS3Bucket(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) defer cleanupTableForTest(t, lockTableName, TERRAFORM_REMOTE_STATE_S3_REGION) @@ -6468,7 +6480,7 @@ func TestTerragruntDisableBucketUpdate(t *testing.T) { _, err = bucketPolicy(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) // validate that bucket policy is not updated, because of --terragrunt-disable-bucket-update - assert.Error(t, err) + require.Error(t, err) } func TestTerragruntPassNullValues(t *testing.T) { @@ -6493,8 +6505,8 @@ func TestTerragruntPassNullValues(t *testing.T) { require.NoError(t, json.Unmarshal(stdout.Bytes(), &outputs)) // check that the null values are passed correctly - assert.Equal(t, outputs["output1"].Value, nil) - assert.Equal(t, outputs["output2"].Value, "variable 2") + require.Nil(t, outputs["output1"].Value) + require.Equal(t, "variable 2", outputs["output2"].Value) // check that file with null values is removed cachePath := filepath.Join(TEST_FIXTURE_NULL_VALUE, TERRAGRUNT_CACHE) @@ -6509,8 +6521,8 @@ func TestTerragruntPassNullValues(t *testing.T) { } return nil }) - assert.Falsef(t, foundNullValuesFile, "Found %s file in cache directory", terraform.NullTFVarsFile) - assert.NoError(t, err) + require.Falsef(t, foundNullValuesFile, "Found %s file in cache directory", terraform.NullTFVarsFile) + require.NoError(t, err) } func TestTerragruntPrintAwsErrors(t *testing.T) { @@ -6532,8 +6544,8 @@ func TestTerragruntPrintAwsErrors(t *testing.T) { err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply --terragrunt-non-interactive --terragrunt-config %s --terragrunt-working-dir %s", tmpTerragruntConfigFile, rootPath), &stdout, &stderr) require.Error(t, err) message := fmt.Sprintf("%v", err.Error()) - assert.True(t, strings.Contains(message, "AllAccessDisabled: All access to this object has been disabled") || strings.Contains(message, "BucketRegionError: incorrect region")) - assert.Contains(t, message, s3BucketName) + require.True(t, strings.Contains(message, "AllAccessDisabled: All access to this object has been disabled") || strings.Contains(message, "BucketRegionError: incorrect region")) + require.Contains(t, message, s3BucketName) } func TestTerragruntErrorWhenStateBucketIsInDifferentRegion(t *testing.T) { @@ -6553,15 +6565,15 @@ func TestTerragruntErrorWhenStateBucketIsInDifferentRegion(t *testing.T) { stdout := bytes.Buffer{} stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply --terragrunt-non-interactive --terragrunt-config %s --terragrunt-working-dir %s", tmpTerragruntConfigFile, rootPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) copyTerragruntConfigAndFillPlaceholders(t, originalTerragruntConfigPath, tmpTerragruntConfigFile, s3BucketName, lockTableName, "us-west-2") stdout = bytes.Buffer{} stderr = bytes.Buffer{} err = runTerragruntCommand(t, fmt.Sprintf("terragrunt apply --terragrunt-non-interactive --terragrunt-config %s --terragrunt-working-dir %s", tmpTerragruntConfigFile, rootPath), &stdout, &stderr) - assert.Error(t, err) - assert.Contains(t, err.Error(), "BucketRegionError: incorrect region") + require.Error(t, err) + require.Contains(t, err.Error(), "BucketRegionError: incorrect region") } func TestTerragruntCheckMissingGCSBucket(t *testing.T) { @@ -6577,8 +6589,8 @@ func TestTerragruntCheckMissingGCSBucket(t *testing.T) { stderr := bytes.Buffer{} tmpTerragruntGCSConfigPath := createTmpTerragruntGCSConfig(t, TEST_FIXTURE_GCS_NO_BUCKET, project, TERRAFORM_REMOTE_STATE_GCP_REGION, gcsBucketName, config.DefaultTerragruntConfigPath) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-config %s --terragrunt-working-dir %s", tmpTerragruntGCSConfigPath, TEST_FIXTURE_GCS_NO_BUCKET), &stdout, &stderr) - assert.Error(t, err) - assert.Contains(t, err.Error(), "Missing required GCS remote state configuration bucket") + require.Error(t, err) + require.Contains(t, err.Error(), "Missing required GCS remote state configuration bucket") } func TestTerragruntNoPrefixGCSBucket(t *testing.T) { @@ -6596,7 +6608,7 @@ func TestTerragruntNoPrefixGCSBucket(t *testing.T) { stderr := bytes.Buffer{} tmpTerragruntGCSConfigPath := createTmpTerragruntGCSConfig(t, TEST_FIXTURE_GCS_NO_PREFIX, project, TERRAFORM_REMOTE_STATE_GCP_REGION, gcsBucketName, config.DefaultTerragruntConfigPath) err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-config %s --terragrunt-working-dir %s", tmpTerragruntGCSConfigPath, TEST_FIXTURE_GCS_NO_PREFIX), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) } func TestTerragruntNoWarningLocalPath(t *testing.T) { @@ -6681,8 +6693,8 @@ func TestRenderJsonDependentModulesTerraform(t *testing.T) { var dependentModules = renderedJson[config.MetadataDependentModules].([]interface{}) // check if value list contains app-v1 and app-v2 - assert.Contains(t, dependentModules, util.JoinPath(tmpEnvPath, TEST_FIXTURE_DESTROY_WARNING, "app-v1")) - assert.Contains(t, dependentModules, util.JoinPath(tmpEnvPath, TEST_FIXTURE_DESTROY_WARNING, "app-v2")) + require.Contains(t, dependentModules, util.JoinPath(tmpEnvPath, TEST_FIXTURE_DESTROY_WARNING, "app-v1")) + require.Contains(t, dependentModules, util.JoinPath(tmpEnvPath, TEST_FIXTURE_DESTROY_WARNING, "app-v2")) } func TestRenderJsonDisableDependentModulesTerraform(t *testing.T) { @@ -6702,7 +6714,7 @@ func TestRenderJsonDisableDependentModulesTerraform(t *testing.T) { require.NoError(t, json.Unmarshal(jsonBytes, &renderedJson)) _, found := renderedJson[config.MetadataDependentModules].([]interface{}) - assert.False(t, found) + require.False(t, found) } func TestRenderJsonDependentModulesMetadataTerraform(t *testing.T) { @@ -6724,8 +6736,8 @@ func TestRenderJsonDependentModulesMetadataTerraform(t *testing.T) { dependentModules := renderedJson[config.MetadataDependentModules]["value"].([]interface{}) // check if value list contains app-v1 and app-v2 - assert.Contains(t, dependentModules, util.JoinPath(tmpEnvPath, TEST_FIXTURE_DESTROY_WARNING, "app-v1")) - assert.Contains(t, dependentModules, util.JoinPath(tmpEnvPath, TEST_FIXTURE_DESTROY_WARNING, "app-v2")) + require.Contains(t, dependentModules, util.JoinPath(tmpEnvPath, TEST_FIXTURE_DESTROY_WARNING, "app-v1")) + require.Contains(t, dependentModules, util.JoinPath(tmpEnvPath, TEST_FIXTURE_DESTROY_WARNING, "app-v2")) } func TestTerragruntSkipConfirmExternalDependencies(t *testing.T) { @@ -6748,7 +6760,7 @@ func TestTerragruntSkipConfirmExternalDependencies(t *testing.T) { t.Cleanup(func() { os.RemoveAll(filepath.ToSlash("/tmp/external-46521694")) }) - assert.NoError(t, os.Mkdir(filepath.ToSlash("/tmp/external-46521694"), 0755)) + require.NoError(t, os.Mkdir(filepath.ToSlash("/tmp/external-46521694"), 0755)) output, err := exec.Command("git", "init", tmpEnvPath).CombinedOutput() if err != nil { @@ -6764,7 +6776,7 @@ func TestTerragruntSkipConfirmExternalDependencies(t *testing.T) { err = runTerragruntCommand(t, fmt.Sprintf("terragrunt destroy --terragrunt-working-dir %s", testPath), &stdout, &stderr) os.Stderr = oldStdout - assert.NoError(t, w.Close()) + require.NoError(t, w.Close()) capturedOutput := make(chan string) go func() { @@ -6817,15 +6829,15 @@ func TestTerragruntParallelStateInit(t *testing.T) { tmpEnvPath, err := os.MkdirTemp("", "terragrunt-test") if err != nil { - assert.NoError(t, err) + require.NoError(t, err) } for i := 0; i < 20; i++ { err := util.CopyFolderContents(TEST_FIXTURE_PARALLEL_STATE_INIT, tmpEnvPath, ".terragrunt-test", nil) - assert.NoError(t, err) + require.NoError(t, err) err = os.Rename( path.Join(tmpEnvPath, "template"), path.Join(tmpEnvPath, "app"+strconv.Itoa(i))) - assert.NoError(t, err) + require.NoError(t, err) } originalTerragruntConfigPath := util.JoinPath(TEST_FIXTURE_PARALLEL_STATE_INIT, "terragrunt.hcl") @@ -6842,15 +6854,15 @@ func TestTerragruntGCSParallelStateInit(t *testing.T) { tmpEnvPath, err := os.MkdirTemp("", "terragrunt-test") if err != nil { - assert.NoError(t, err) + require.NoError(t, err) } for i := 0; i < 20; i++ { err := util.CopyFolderContents(TEST_FIXTURE_GCS_PARALLEL_STATE_INIT, tmpEnvPath, ".terragrunt-test", nil) - assert.NoError(t, err) + require.NoError(t, err) err = os.Rename( path.Join(tmpEnvPath, "template"), path.Join(tmpEnvPath, "app"+strconv.Itoa(i))) - assert.NoError(t, err) + require.NoError(t, err) } tmpTerragruntConfigFile := util.JoinPath(tmpEnvPath, "terragrunt.hcl") @@ -6858,7 +6870,7 @@ func TestTerragruntGCSParallelStateInit(t *testing.T) { gcsBucketName := fmt.Sprintf("terragrunt-test-bucket-%s", strings.ToLower(uniqueId())) tmpTerragruntGCSConfigPath := createTmpTerragruntGCSConfig(t, TEST_FIXTURE_GCS_PARALLEL_STATE_INIT, project, TERRAFORM_REMOTE_STATE_GCP_REGION, gcsBucketName, config.DefaultTerragruntConfigPath) err = util.CopyFile(tmpTerragruntGCSConfigPath, tmpTerragruntConfigFile) - assert.NoError(t, err) + require.NoError(t, err) runTerragrunt(t, fmt.Sprintf("terragrunt run-all apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", tmpEnvPath)) } @@ -6880,20 +6892,20 @@ func TestTerragruntAssumeRole(t *testing.T) { // validate generated backend.tf backendFile := filepath.Join(testPath, "backend.tf") - assert.FileExists(t, backendFile) + require.FileExists(t, backendFile) content, err := files.ReadFileAsString(backendFile) - assert.NoError(t, err) + require.NoError(t, err) opts, err := options.NewTerragruntOptionsForTest(testPath) - assert.NoError(t, err) + require.NoError(t, err) identityARN, err := aws_helper.GetAWSIdentityArn(nil, opts) - assert.NoError(t, err) + require.NoError(t, err) - assert.Contains(t, content, "role_arn = \""+identityARN+"\"") - assert.Contains(t, content, "external_id = \"external_id_123\"") - assert.Contains(t, content, "session_name = \"session_name_example\"") + require.Contains(t, content, "role_arn = \""+identityARN+"\"") + require.Contains(t, content, "external_id = \"external_id_123\"") + require.Contains(t, content, "session_name = \"session_name_example\"") } func TestTerragruntUpdatePolicy(t *testing.T) { @@ -6907,7 +6919,7 @@ func TestTerragruntUpdatePolicy(t *testing.T) { lockTableName := fmt.Sprintf("terragrunt-test-locks-%s", strings.ToLower(uniqueId())) err := createS3BucketE(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) - assert.NoError(t, err) + require.NoError(t, err) defer deleteS3Bucket(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) defer cleanupTableForTest(t, lockTableName, TERRAFORM_REMOTE_STATE_S3_REGION) @@ -6916,13 +6928,13 @@ func TestTerragruntUpdatePolicy(t *testing.T) { // check that there is no policy on created bucket _, err = bucketPolicy(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) - assert.Error(t, err) + require.Error(t, err) runTerragrunt(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-config %s --terragrunt-working-dir %s", tmpTerragruntConfigPath, rootPath)) // check that policy is created _, err = bucketPolicy(t, TERRAFORM_REMOTE_STATE_S3_REGION, s3BucketName) - assert.NoError(t, err) + require.NoError(t, err) } func TestTerragruntDestroyGraph(t *testing.T) { @@ -6963,15 +6975,15 @@ func TestTerragruntDestroyGraph(t *testing.T) { tmpModulePath := util.JoinPath(tmpEnvPath, TEST_FIXTURE_GRAPH, testCase.path) stdout, stderr, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt graph destroy --terragrunt-non-interactive --terragrunt-working-dir %s --terragrunt-graph-root %s", tmpModulePath, tmpEnvPath)) - assert.NoError(t, err) + require.NoError(t, err) output := fmt.Sprintf("%v\n%v\n", stdout, stderr) for _, module := range testCase.expectedModules { - assert.Containsf(t, output, "/"+module+"\n", "Expected module %s to be in output", module) + require.Containsf(t, output, "/"+module+"\n", "Expected module %s to be in output", module) } for _, module := range testCase.notExpectedModules { - assert.NotContainsf(t, output, "Module "+tmpModulePath+"/"+module+"\n", "Expected module %s must not to be in output", module) + require.NotContainsf(t, output, "Module "+tmpModulePath+"/"+module+"\n", "Expected module %s must not to be in output", module) } }) } @@ -7010,15 +7022,15 @@ func TestTerragruntApplyGraph(t *testing.T) { tmpModulePath := util.JoinPath(tmpEnvPath, TEST_FIXTURE_GRAPH, testCase.path) stdout, stderr, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt graph apply --terragrunt-non-interactive --terragrunt-working-dir %s --terragrunt-graph-root %s", tmpModulePath, tmpEnvPath)) - assert.NoError(t, err) + require.NoError(t, err) output := fmt.Sprintf("%v\n%v\n", stdout, stderr) for _, module := range testCase.expectedModules { - assert.Containsf(t, output, "/"+module+"\n", "Expected module %s to be in output", module) + require.Containsf(t, output, "/"+module+"\n", "Expected module %s to be in output", module) } for _, module := range testCase.notExpectedModules { - assert.NotContainsf(t, output, "Module "+tmpModulePath+"/"+module+"\n", "Expected module %s must not to be in output", module) + require.NotContainsf(t, output, "Module "+tmpModulePath+"/"+module+"\n", "Expected module %s must not to be in output", module) } }) } @@ -7034,12 +7046,12 @@ func TestTerragruntGraphNonTerraformCommandExecution(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt graph render-json --terragrunt-non-interactive --terragrunt-working-dir %s --terragrunt-graph-root %s", tmpModulePath, tmpEnvPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) // check that terragrunt_rendered.json is created in mod1/mod2/mod3 for _, module := range []string{"services/eks-service-1", "eks"} { _, err = os.Stat(util.JoinPath(tmpEnvPath, TEST_FIXTURE_GRAPH, module, "terragrunt_rendered.json")) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -7054,21 +7066,21 @@ func TestTerragruntSkipDependenciesWithSkipFlag(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt run-all apply --no-color --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) output := fmt.Sprintf("%s %s", stderr.String(), stdout.String()) - assert.NotContains(t, output, "Error reading partial config for dependency") - assert.NotContains(t, output, "Call to function \"find_in_parent_folders\" failed") - assert.NotContains(t, output, "ParentFileNotFoundError") + require.NotContains(t, output, "Error reading partial config for dependency") + require.NotContains(t, output, "Call to function \"find_in_parent_folders\" failed") + require.NotContains(t, output, "ParentFileNotFoundError") - assert.Contains(t, output, "first/terragrunt.hcl due to skip = true") - assert.Contains(t, output, "second/terragrunt.hcl due to skip = true") + require.Contains(t, output, "first/terragrunt.hcl due to skip = true") + require.Contains(t, output, "second/terragrunt.hcl due to skip = true") // check that no test_file.txt was created in module directory _, err = os.Stat(util.JoinPath(tmpEnvPath, TEST_FIXTURE_SKIP_DEPENDENCIES, "first", "test_file.txt")) - assert.Error(t, err) + require.Error(t, err) _, err = os.Stat(util.JoinPath(tmpEnvPath, TEST_FIXTURE_SKIP_DEPENDENCIES, "second", "test_file.txt")) - assert.Error(t, err) + require.Error(t, err) } func TestTerragruntAssumeRoleDuration(t *testing.T) { @@ -7101,21 +7113,21 @@ func TestTerragruntAssumeRoleDuration(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) output := fmt.Sprintf("%s %s", stderr.String(), stdout.String()) - assert.Contains(t, output, "Apply complete! Resources: 1 added, 0 changed, 0 destroyed.") + require.Contains(t, output, "Apply complete! Resources: 1 added, 0 changed, 0 destroyed.") // run one more time to check that no init is performed stdout = bytes.Buffer{} stderr = bytes.Buffer{} err = runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) output = fmt.Sprintf("%s %s", stderr.String(), stdout.String()) - assert.NotContains(t, output, "Initializing the backend...") - assert.NotContains(t, output, "has been successfully initialized!") - assert.Contains(t, output, "no changes are needed.") + require.NotContains(t, output, "Initializing the backend...") + require.NotContains(t, output, "has been successfully initialized!") + require.Contains(t, output, "no changes are needed.") } func TestTerragruntAssumeRoleWebIdentityEnv(t *testing.T) { @@ -7149,10 +7161,10 @@ func TestTerragruntAssumeRoleWebIdentityEnv(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) output := fmt.Sprintf("%s %s", stderr.String(), stdout.String()) - assert.Contains(t, output, "Apply complete! Resources: 1 added, 0 changed, 0 destroyed.") + require.Contains(t, output, "Apply complete! Resources: 1 added, 0 changed, 0 destroyed.") } func TestTerragruntAssumeRoleWebIdentityFile(t *testing.T) { @@ -7182,10 +7194,10 @@ func TestTerragruntAssumeRoleWebIdentityFile(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt apply -auto-approve --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) output := fmt.Sprintf("%s %s", stderr.String(), stdout.String()) - assert.Contains(t, output, "Apply complete! Resources: 1 added, 0 changed, 0 destroyed.") + require.Contains(t, output, "Apply complete! Resources: 1 added, 0 changed, 0 destroyed.") } func prepareGraphFixture(t *testing.T) string { @@ -7198,7 +7210,7 @@ func prepareGraphFixture(t *testing.T) string { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt run-all apply --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) - assert.NoError(t, err) + require.NoError(t, err) return tmpEnvPath } @@ -7213,12 +7225,12 @@ func TestTerragruntInfoError(t *testing.T) { stderr := bytes.Buffer{} err := runTerragruntCommand(t, fmt.Sprintf("terragrunt terragrunt-info --terragrunt-non-interactive --terragrunt-working-dir %s", testPath), &stdout, &stderr) - assert.Error(t, err) + require.Error(t, err) // parse stdout json as TerragruntInfoGroup var output terragruntinfo.TerragruntInfoGroup err = json.Unmarshal(stdout.Bytes(), &output) - assert.NoError(t, err) + require.NoError(t, err) } func TestStorePlanFilesRunAllPlanApply(t *testing.T) { @@ -7234,14 +7246,14 @@ func TestStorePlanFilesRunAllPlanApply(t *testing.T) { _, output, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt run-all plan --terragrunt-non-interactive --terragrunt-log-level debug --terragrunt-working-dir %s --terragrunt-out-dir %s", testPath, tmpDir)) require.NoError(t, err) - assert.Contains(t, output, fmt.Sprintf("Using output file %s", tmpDir)) + require.Contains(t, output, fmt.Sprintf("Using output file %s", tmpDir)) // verify that tfplan files are created in the tmpDir, 2 files list, err := findFilesWithExtension(tmpDir, ".tfplan") require.NoError(t, err) - assert.Equal(t, 2, len(list)) + require.Len(t, list, 2) for _, file := range list { - assert.Equal(t, "tfplan.tfplan", filepath.Base(file)) + require.Equal(t, "tfplan.tfplan", filepath.Base(file)) } _, _, err = runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt run-all apply --terragrunt-non-interactive --terragrunt-log-level debug --terragrunt-working-dir %s --terragrunt-out-dir %s", testPath, tmpDir)) @@ -7266,22 +7278,22 @@ func TestStorePlanFilesRunAllDestroy(t *testing.T) { // remove all tfstate files from temp directory to prepare destroy list, err := findFilesWithExtension(tmpDir, ".tfplan") require.NoError(t, err) - assert.Equal(t, 2, len(list)) + require.Len(t, list, 2) for _, file := range list { - assert.Equal(t, "tfplan.tfplan", filepath.Base(file)) + require.Equal(t, "tfplan.tfplan", filepath.Base(file)) } // prepare destroy plan _, output, err := runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt run-all plan -destroy --terragrunt-non-interactive --terragrunt-log-level debug --terragrunt-working-dir %s --terragrunt-out-dir %s", testPath, tmpDir)) require.NoError(t, err) - assert.Contains(t, output, fmt.Sprintf("Using output file %s", tmpDir)) + require.Contains(t, output, fmt.Sprintf("Using output file %s", tmpDir)) // verify that tfplan files are created in the tmpDir, 2 files list, err = findFilesWithExtension(tmpDir, ".tfplan") require.NoError(t, err) - assert.Equal(t, 2, len(list)) + require.Len(t, list, 2) for _, file := range list { - assert.Equal(t, "tfplan.tfplan", filepath.Base(file)) + require.Equal(t, "tfplan.tfplan", filepath.Base(file)) } _, _, err = runTerragruntCommandWithOutput(t, fmt.Sprintf("terragrunt run-all apply --terragrunt-non-interactive --terragrunt-log-level debug --terragrunt-working-dir %s --terragrunt-out-dir %s", testPath, tmpDir)) @@ -7299,19 +7311,19 @@ func TestPlanJsonFilesRunAll(t *testing.T) { // verify that was generated json files with plan data list, err := findFilesWithExtension(tmpDir, ".json") require.NoError(t, err) - assert.Equal(t, 2, len(list)) + require.Len(t, list, 2) for _, file := range list { - assert.Equal(t, "tfplan.json", filepath.Base(file)) + require.Equal(t, "tfplan.json", filepath.Base(file)) // verify that file is not empty content, err := os.ReadFile(file) require.NoError(t, err) - assert.NotEmpty(t, content) + require.NotEmpty(t, content) // check that produced json is valid and can be unmarshalled var plan map[string]interface{} err = json.Unmarshal(content, &plan) require.NoError(t, err) // check that plan is not empty - assert.NotEmpty(t, plan) + require.NotEmpty(t, plan) } } @@ -7332,21 +7344,21 @@ func TestPlanJsonPlanBinaryRunAll(t *testing.T) { // verify that was generated json files with plan data list, err := findFilesWithExtension(tmpDir, ".json") require.NoError(t, err) - assert.Equal(t, 2, len(list)) + require.Len(t, list, 2) for _, file := range list { - assert.Equal(t, "tfplan.json", filepath.Base(file)) + require.Equal(t, "tfplan.json", filepath.Base(file)) // verify that file is not empty content, err := os.ReadFile(file) require.NoError(t, err) - assert.NotEmpty(t, content) + require.NotEmpty(t, content) } // verify that was generated binary plan files list, err = findFilesWithExtension(tmpDir, ".tfplan") require.NoError(t, err) - assert.Equal(t, 2, len(list)) + require.Len(t, list, 2) for _, file := range list { - assert.Equal(t, "tfplan.tfplan", filepath.Base(file)) + require.Equal(t, "tfplan.tfplan", filepath.Base(file)) } } @@ -7375,7 +7387,7 @@ func TestTerragruntRunAllPlanAndShow(t *testing.T) { require.NoError(t, err) // Verify that output contains the plan and not just the actual state output - assert.Contains(t, stdout, "No changes. Your infrastructure matches the configuration.") + require.Contains(t, stdout, "No changes. Your infrastructure matches the configuration.") } func TestTerragruntLogSopsErrors(t *testing.T) { @@ -7410,7 +7422,7 @@ func TestGetRepoRootCaching(t *testing.T) { output := fmt.Sprintf("%s %s", stdout, stderr) count := strings.Count(output, "git show-toplevel result") - assert.Equal(t, 1, count) + require.Equal(t, 1, count) } func validateOutput(t *testing.T, outputs map[string]TerraformOutput, key string, value interface{}) { diff --git a/tflint/tflint_test.go b/tflint/tflint_test.go index 1b39a6b81..bbced9b56 100644 --- a/tflint/tflint_test.go +++ b/tflint/tflint_test.go @@ -3,7 +3,7 @@ package tflint import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestInputsToTflintVar(t *testing.T) { @@ -34,7 +34,7 @@ func TestInputsToTflintVar(t *testing.T) { for _, testCase := range testCases { actual, err := inputsToTflintVar(testCase.inputs) - assert.NoError(t, err) - assert.ElementsMatch(t, testCase.expected, actual) + require.NoError(t, err) + require.ElementsMatch(t, testCase.expected, actual) } } diff --git a/util/collections_test.go b/util/collections_test.go index 7db6f5716..e0ce13724 100644 --- a/util/collections_test.go +++ b/util/collections_test.go @@ -3,7 +3,7 @@ package util import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMatchesAny(t *testing.T) { @@ -33,7 +33,7 @@ func TestMatchesAny(t *testing.T) { for _, testCase := range testCases { actual := MatchesAny(testCase.list, testCase.element) - assert.Equal(t, testCase.expected, actual, "For list %v and element %s", testCase.list, testCase.element) + require.Equal(t, testCase.expected, actual, "For list %v and element %s", testCase.list, testCase.element) } } @@ -55,7 +55,7 @@ func TestListContainsElement(t *testing.T) { for _, testCase := range testCases { actual := ListContainsElement(testCase.list, testCase.element) - assert.Equal(t, testCase.expected, actual, "For list %v and element %s", testCase.list, testCase.element) + require.Equal(t, testCase.expected, actual, "For list %v and element %s", testCase.list, testCase.element) } } @@ -79,7 +79,7 @@ func TestListEquals(t *testing.T) { } for _, testCase := range testCases { actual := ListEquals(testCase.a, testCase.b) - assert.Equal(t, testCase.expected, actual, "For list %v and list %v", testCase.a, testCase.b) + require.Equal(t, testCase.expected, actual, "For list %v and list %v", testCase.a, testCase.b) } } @@ -116,7 +116,7 @@ func TestListContainsSublist(t *testing.T) { for _, testCase := range testCases { actual := ListContainsSublist(testCase.list, testCase.sublist) - assert.Equal(t, testCase.expected, actual, "For list %v and sublist %v", testCase.list, testCase.sublist) + require.Equal(t, testCase.expected, actual, "For list %v and sublist %v", testCase.list, testCase.sublist) } } @@ -143,7 +143,7 @@ func TestListHasPrefix(t *testing.T) { } for _, testCase := range testCases { actual := ListHasPrefix(testCase.list, testCase.prefix) - assert.Equal(t, testCase.expected, actual, "For list %v and prefix %v", testCase.list, testCase.prefix) + require.Equal(t, testCase.expected, actual, "For list %v and prefix %v", testCase.list, testCase.prefix) } } @@ -166,7 +166,7 @@ func TestRemoveElementFromList(t *testing.T) { for _, testCase := range testCases { actual := RemoveElementFromList(testCase.list, testCase.element) - assert.Equal(t, testCase.expected, actual, "For list %v and element %s", testCase.list, testCase.element) + require.Equal(t, testCase.expected, actual, "For list %v and element %s", testCase.list, testCase.element) } } @@ -192,7 +192,7 @@ func TestRemoveDuplicatesFromList(t *testing.T) { if testCase.reverse { f = RemoveDuplicatesFromListKeepLast[[]string] } - assert.Equal(t, f(testCase.list), testCase.expected, "For list %v", testCase.list) + require.Equal(t, testCase.expected, f(testCase.list), "For list %v", testCase.list) t.Logf("%v passed", testCase.list) } } @@ -210,7 +210,7 @@ func TestCommaSeparatedStrings(t *testing.T) { } for _, testCase := range testCases { - assert.Equal(t, CommaSeparatedStrings(testCase.list), testCase.expected, "For list %v", testCase.list) + require.Equal(t, testCase.expected, CommaSeparatedStrings(testCase.list), "For list %v", testCase.list) t.Logf("%v passed", testCase.list) } } @@ -231,7 +231,7 @@ func TestStringListInsert(t *testing.T) { } for _, testCase := range testCases { - assert.Equal(t, testCase.expected, StringListInsert(testCase.list, testCase.element, testCase.index), "For list %v", testCase.list) + require.Equal(t, testCase.expected, StringListInsert(testCase.list, testCase.element, testCase.index), "For list %v", testCase.list) t.Logf("%v passed", testCase.list) } } diff --git a/util/datetime.go b/util/datetime.go index 5a4226d6f..8f2a3e8c3 100644 --- a/util/datetime.go +++ b/util/datetime.go @@ -9,7 +9,8 @@ import ( func ParseTimestamp(ts string) (time.Time, error) { t, err := time.Parse(time.RFC3339, ts) if err != nil { - switch err := err.(type) { + // TODO: Remove this lint suppression + switch err := err.(type) { //nolint:errorlint case *time.ParseError: // If err is a time.ParseError then its string representation is not // appropriate since it relies on details of Go's strange date format diff --git a/util/datetime_test.go b/util/datetime_test.go index ea4aa07fe..928bb5d31 100644 --- a/util/datetime_test.go +++ b/util/datetime_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParseTimestamp(t *testing.T) { @@ -30,12 +30,12 @@ func TestParseTimestamp(t *testing.T) { actual, err := ParseTimestamp(testCase.arg) if testCase.err != "" { - assert.EqualError(t, err, testCase.err) + require.EqualError(t, err, testCase.err) } else { - assert.NoError(t, err) + require.NoError(t, err) } - assert.Equal(t, testCase.value, actual) + require.Equal(t, testCase.value, actual) }) } } diff --git a/util/file.go b/util/file.go index 634ea40a5..b3f11ca46 100644 --- a/util/file.go +++ b/util/file.go @@ -4,6 +4,7 @@ import ( "bytes" "crypto/sha256" "encoding/gob" + goErrors "errors" "io" "os" "path/filepath" @@ -233,7 +234,7 @@ func listContainsElementWithPrefix(list []string, elementPrefix string) bool { func expandGlobPath(source, absoluteGlobPath string) ([]string, error) { includeExpandedGlobs := []string{} absoluteExpandGlob, err := zglob.Glob(absoluteGlobPath) - if err != nil && err != os.ErrNotExist { + if err != nil && !goErrors.Is(err, os.ErrNotExist) { // we ignore not exist error as we only care about the globs that exist in the src dir return nil, errors.WithStackTrace(err) } @@ -516,7 +517,7 @@ func (manifest *fileManifest) clean(manifestPath string) error { var manifestEntry fileManifestEntry err = decoder.Decode(&manifestEntry) if err != nil { - if err == io.EOF { + if goErrors.Is(err, io.EOF) { break } else { return err diff --git a/util/file_test.go b/util/file_test.go index 2e032c435..2fe123f2d 100644 --- a/util/file_test.go +++ b/util/file_test.go @@ -35,7 +35,7 @@ func TestGetPathRelativeTo(t *testing.T) { for _, testCase := range testCases { actual, err := GetPathRelativeTo(testCase.path, testCase.basePath) - assert.Nil(t, err, "Unexpected error for path %s and basePath %s: %v", testCase.path, testCase.basePath, err) + require.NoError(t, err) assert.Equal(t, testCase.expected, actual, "For path %s and basePath %s", testCase.path, testCase.basePath) } } @@ -64,7 +64,7 @@ func TestCanonicalPath(t *testing.T) { for _, testCase := range testCases { actual, err := CanonicalPath(testCase.path, testCase.basePath) - assert.Nil(t, err, "Unexpected error for path %s and basePath %s: %v", testCase.path, testCase.basePath, err) + require.NoError(t, err) assert.Equal(t, testCase.expected, actual, "For path %s and basePath %s", testCase.path, testCase.basePath) } } @@ -76,7 +76,7 @@ func TestGlobCanonicalPath(t *testing.T) { expectedHelper := func(path string) string { basePath, err := filepath.Abs(basePath) - assert.NoError(t, err) + require.NoError(t, err) return filepath.ToSlash(filepath.Join(basePath, path)) } @@ -102,7 +102,7 @@ func TestGlobCanonicalPath(t *testing.T) { return testCase.expected[i] < testCase.expected[j] }) - assert.Nil(t, err, "Unexpected error for paths %s and basePath %s: %v", testCase.paths, basePath, err) + require.NoError(t, err) assert.Equal(t, testCase.expected, actual, "For path %s and basePath %s", testCase.paths, basePath) } } @@ -180,7 +180,7 @@ func TestFileManifest(t *testing.T) { for _, file := range []string{"file1", "file2"} { // create temp files in the dir f, err := os.CreateTemp(dir, file) - assert.NoError(t, err, f.Close()) + require.NoError(t, err) testfiles = append(testfiles, f.Name()) } // will later test if the file already doesn't exist @@ -188,11 +188,11 @@ func TestFileManifest(t *testing.T) { // create a manifest manifest := newFileManifest(dir, ".terragrunt-test-manifest") - require.Nil(t, manifest.Create()) + require.NoError(t, manifest.Create()) // check the file manifest has been created require.FileExists(t, filepath.Join(manifest.ManifestFolder, manifest.ManifestFile)) for _, file := range testfiles { - assert.NoError(t, manifest.AddFile(file)) + require.NoError(t, manifest.AddFile(file)) } // check for a non-existent directory as well assert.NoError(t, manifest.AddDirectory(path.Join(dir, "ephemeral-directory-that-doesnt-exist"))) @@ -200,7 +200,7 @@ func TestFileManifest(t *testing.T) { require.NoError(t, manifest.Clean()) // test if the files have been deleted for _, file := range testfiles { - assert.Equal(t, FileExists(file), false) + require.False(t, FileExists(file)) } } @@ -333,7 +333,7 @@ func TestEmptyDir(t *testing.T) { } for _, testCase := range testCases { emptyValue, err := IsDirectoryEmpty(testCase.path) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, testCase.expectEmpty, emptyValue, "For path %s", testCase.path) } diff --git a/util/jsons_test.go b/util/jsons_test.go index fb24fdd43..7c4ca10aa 100644 --- a/util/jsons_test.go +++ b/util/jsons_test.go @@ -3,7 +3,7 @@ package util import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAsTerraformEnvVarJsonValue(t *testing.T) { @@ -19,7 +19,7 @@ func TestAsTerraformEnvVarJsonValue(t *testing.T) { for _, testCase := range testCases { actual, err := AsTerraformEnvVarJsonValue(testCase.value) - assert.NoError(t, err) - assert.Equal(t, testCase.expected, actual) + require.NoError(t, err) + require.Equal(t, testCase.expected, actual) } } diff --git a/util/prefix-writer_test.go b/util/prefix-writer_test.go index f0c510ef4..23351504e 100644 --- a/util/prefix-writer_test.go +++ b/util/prefix-writer_test.go @@ -5,7 +5,7 @@ import ( "errors" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPrefixWriter(t *testing.T) { @@ -44,10 +44,10 @@ func TestPrefixWriter(t *testing.T) { pw := PrefixedWriter(&b, testCase.prefix) for _, input := range testCase.values { written, err := pw.Write([]byte(input)) - assert.NoError(t, err) - assert.Equal(t, written, len(input)) + require.NoError(t, err) + require.Len(t, input, written) } - assert.Equal(t, testCase.expected, b.String()) + require.Equal(t, testCase.expected, b.String()) } } @@ -72,8 +72,8 @@ func TestPrefixWriterFail(t *testing.T) { pw := PrefixedWriter(&FailingWriter{}, testCase.prefix) for _, input := range testCase.values { written, err := pw.Write([]byte(input)) - assert.Error(t, err) - assert.Equal(t, written, 0) + require.Error(t, err) + require.Empty(t, written) } } } diff --git a/util/reflect.go b/util/reflect.go index 119cbc093..a1373021a 100644 --- a/util/reflect.go +++ b/util/reflect.go @@ -39,7 +39,7 @@ func MustWalkTerraformOutput(value interface{}, path ...string) interface{} { found := value for _, p := range path { v := reflect.ValueOf(found) - switch reflect.TypeOf(found).Kind() { + switch reflect.TypeOf(found).Kind() { //nolint:exhaustive case reflect.Map: if !v.MapIndex(reflect.ValueOf(p)).IsValid() { return nil diff --git a/util/retry.go b/util/retry.go index 94c326fb6..01c8c945c 100644 --- a/util/retry.go +++ b/util/retry.go @@ -2,6 +2,7 @@ package util import ( "context" + goErrors "errors" "fmt" "time" @@ -22,7 +23,8 @@ func DoWithRetry(ctx context.Context, actionDescription string, maxRetries int, return nil } - if _, isFatalErr := err.(FatalError); isFatalErr { + var fatalErr FatalError + if ok := goErrors.As(err, &fatalErr); ok { return err } diff --git a/util/shell.go b/util/shell.go index b528ac6f2..c01ce5f1e 100644 --- a/util/shell.go +++ b/util/shell.go @@ -1,6 +1,7 @@ package util import ( + goErrors "errors" "fmt" "os/exec" "syscall" @@ -17,7 +18,8 @@ func IsCommandExecutable(command string, args ...string) bool { cmd.Stderr = nil if err := cmd.Run(); err != nil { - if exitErr, ok := err.(*exec.ExitError); ok { + var exitErr *exec.ExitError + if ok := goErrors.As(err, &exitErr); ok { return exitErr.ExitCode() == 0 } return false @@ -42,13 +44,15 @@ func GetExitCode(err error) (int, error) { return exiterr.ExitStatus() } - if exiterr, ok := errors.Unwrap(err).(*exec.ExitError); ok { + var exiterr *exec.ExitError + if ok := goErrors.As(err, &exiterr); ok { status := exiterr.Sys().(syscall.WaitStatus) return status.ExitStatus(), nil } - if exiterr, ok := errors.Unwrap(err).(*multierror.Error); ok { - for _, err := range exiterr.Errors { + var multiErr *multierror.Error + if ok := goErrors.As(err, &multiErr); ok { + for _, err := range multiErr.Errors { exitCode, exitCodeErr := GetExitCode(err) if exitCodeErr == nil { return exitCode, nil