Skip to content

Commit

Permalink
add test to init views and arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
Uk1288 committed Apr 8, 2024
1 parent f052ba5 commit 4a102a4
Show file tree
Hide file tree
Showing 9 changed files with 414 additions and 50 deletions.
136 changes: 136 additions & 0 deletions internal/command/arguments/init_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

package arguments

import (
"flag"
"io"
"strings"
"testing"
"time"

"github.com/google/go-cmp/cmp"
)

func TestParseInit_basicValid(t *testing.T) {
testCases := map[string]struct {
args []string
want *Init
}{
"with default options": {
nil,
&Init{
FromModule: "",
Lockfile: "",
TestsDirectory: "tests",
ViewType: ViewHuman,
Backend: true,
Cloud: true,
Get: true,
ForceInitCopy: false,
StateLock: true,
StateLockTimeout: 0,
Reconfigure: false,
MigrateState: false,
Upgrade: false,
Json: false,
IgnoreRemoteVersion: false,
},
},
"setting multiple options": {
[]string{"-backend=false", "-force-copy=true",
"-from-module=./main-dir", "-json", "-get=false",
"-lock=false", "-lock-timeout=10s", "-reconfigure=true",
"-upgrade=true", "-lockfile=readonly",
"-ignore-remote-version=true", "-test-directory=./test-dir"},
&Init{
FromModule: "./main-dir",
Lockfile: "readonly",
TestsDirectory: "./test-dir",
ViewType: ViewJSON,
Backend: false,
Cloud: false,
Get: false,
ForceInitCopy: true,
StateLock: false,
StateLockTimeout: time.Duration(10) * time.Second,
Reconfigure: true,
MigrateState: false,
Upgrade: true,
Json: true,
IgnoreRemoteVersion: true,
},
},
"with cloud option": {
[]string{"-cloud=false"},
&Init{
FromModule: "",
Lockfile: "",
TestsDirectory: "tests",
ViewType: ViewHuman,
Backend: false,
Cloud: false,
Get: true,
ForceInitCopy: false,
StateLock: true,
StateLockTimeout: 0,
Reconfigure: false,
MigrateState: false,
Upgrade: false,
Json: false,
IgnoreRemoteVersion: false,
},
},
}

for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
cmdFlags := flag.NewFlagSet("init", flag.ContinueOnError)
cmdFlags.SetOutput(io.Discard)

got, diags := ParseInit(tc.args, cmdFlags)
if len(diags) > 0 {
t.Fatalf("unexpected diags: %v", diags)
}

if diff := cmp.Diff(tc.want, got); diff != "" {
t.Errorf("unexpected result\n%s", diff)
}
})
}
}

func TestParseInit_invalid(t *testing.T) {
testCases := map[string]struct {
args []string
wantErr string
}{
"with unsupported options": {
args: []string{"-raw"},
wantErr: "flag provided but not defined",
},
"with both -backend and -cloud options set": {
args: []string{"-backend=false", "-cloud=false"},
wantErr: "The -backend and -cloud options are aliases of one another and mutually-exclusive in their use",
},
}

for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
cmdFlags := flag.NewFlagSet("init", flag.ContinueOnError)
cmdFlags.SetOutput(io.Discard)

got, diags := ParseInit(tc.args, cmdFlags)
if len(diags) == 0 {
t.Fatal("expected diags but got none")
}
if got, want := diags.Err().Error(), tc.wantErr; !strings.Contains(got, want) {
t.Fatalf("wrong diags\n got: %s\nwant: %s", got, want)
}
if got.ViewType != ViewHuman {
t.Fatalf("wrong view type, got %#v, want %#v", got.ViewType, ViewHuman)
}
})
}
}
70 changes: 32 additions & 38 deletions internal/command/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,36 @@ func TestInit_multipleArgs(t *testing.T) {
}
}

func TestInit_migrateStateAndJSON(t *testing.T) {
// Create a temporary working directory that is empty
td := t.TempDir()
os.MkdirAll(td, 0755)
defer testChdir(t, td)()

ui := new(cli.MockUi)
view, done := testView(t)
c := &InitCommand{
Meta: Meta{
testingOverrides: metaOverridesForProvider(testProvider()),
Ui: ui,
View: view,
},
}

args := []string{
"-migrate-state=true",
"-json=true",
}
code := c.Run(args)
testOutput := done(t)
if code != 1 {
t.Fatalf("error, -migrate-state and -json should be exclusive: \n%s", testOutput.All())
}

// Check output
checkGoldenReference(t, testOutput, "init-migrate-state-with-json")
}

func TestInit_fromModule_cwdDest(t *testing.T) {
// Create a temporary working directory that is empty
td := t.TempDir()
Expand Down Expand Up @@ -205,10 +235,8 @@ func TestInit_json(t *testing.T) {
}

// Check output
output := done(t).All()
if !strings.Contains(output, "foo in foo") {
t.Fatalf("doesn't look like we installed module 'foo': %s", output)
}
output := done(t)
checkGoldenReference(t, output, "init-get")
}

func TestInit_getUpgradeModules(t *testing.T) {
Expand Down Expand Up @@ -2876,40 +2904,6 @@ hashicorp/test: no available releases match the given constraints 1.0.1,
}
}

func TestInit_jsonTestsWithProvider(t *testing.T) {
// Create a temporary working directory that is empty
td := t.TempDir()
testCopyDir(t, testFixturePath("init-with-tests-with-provider"), td)
defer testChdir(t, td)()

provider := applyFixtureProvider() // We just want the types from this provider.

providerSource, close := newMockProviderSource(t, map[string][]string{
"hashicorp/test": {"1.0.0"},
})
defer close()

ui := new(cli.MockUi)
view, done := testView(t)
c := &InitCommand{
Meta: Meta{
testingOverrides: metaOverridesForProvider(provider),
Ui: ui,
View: view,
ProviderSource: providerSource,
},
}

args := []string{"-json"}
code := c.Run(args)
testOutput := done(t)
if code == 0 {
t.Fatalf("expected failure but got: \n%s", testOutput.All())
}

checkGoldenReference(t, testOutput, "init-with-tests-with-provider")
}

func TestInit_testsWithModule(t *testing.T) {
// Create a temporary working directory that is empty
td := t.TempDir()
Expand Down
8 changes: 8 additions & 0 deletions internal/command/testdata/init-get/output.jsonlog
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{"@level":"info","@message":"Terraform 1.9.0-dev","@module":"terraform.ui","terraform":"1.9.0-dev","type":"version","ui":"1.2"}
{"@level":"info","@message":"Initializing the backend...","@module":"terraform.ui","type":"init_output"}
{"@level":"info","@message":"Initializing modules...","@module":"terraform.ui","type":"init_output"}
{"@level":"info","@message":"- foo in foo","@module":"terraform.ui","type":"log"}
{"@level":"info","@message":"Initializing provider plugins...","@module":"terraform.ui","type":"init_output"}
{"@level":"info","@message":"","@module":"terraform.ui","type":"init_output"}
{"@level":"info","@message":"Terraform has been successfully initialized!","@module":"terraform.ui","type":"init_output"}
{"@level":"info","@message":"You may now begin working with Terraform. Try running \"terraform plan\" to see\nany changes that are required for your infrastructure. All Terraform commands\nshould now work.\n\nIf you ever set or change modules or backend configuration for Terraform,\nrerun this command to reinitialize your working directory. If you forget, other\ncommands will detect it and remind you to do so if necessary.","@module":"terraform.ui","type":"init_output"}
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{"@level":"info","@message":"Terraform 1.9.0-dev","@module":"terraform.ui","terraform":"1.9.0-dev","type":"version","ui":"1.2"}
{"@level":"error","@message":"Error: The -migrate-state and -json options are mutually-exclusive","@module":"terraform.ui","diagnostic":{"severity":"error","summary":"The -migrate-state and -json options are mutually-exclusive","detail":"Terraform cannot ask for interactive approval when -json is set. To use the -migrate-state option, disable the -json option."},"type":"diagnostic"}

This file was deleted.

2 changes: 1 addition & 1 deletion internal/command/views/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func (v *InitJSON) Diagnostics(diags tfdiags.Diagnostics) {
}

func (v *InitJSON) Output(messageCode string, params ...any) {
current_timestamp := time.Now().Format(time.RFC3339)
current_timestamp := time.Now().UTC().Format(time.RFC3339)

json_data := map[string]string{
"@level": "info",
Expand Down
Loading

0 comments on commit 4a102a4

Please sign in to comment.