github.com/opentofu/opentofu@v1.7.1/internal/command/state_pull_test.go (about) 1 // Copyright (c) The OpenTofu Authors 2 // SPDX-License-Identifier: MPL-2.0 3 // Copyright (c) 2023 HashiCorp, Inc. 4 // SPDX-License-Identifier: MPL-2.0 5 6 package command 7 8 import ( 9 "bytes" 10 "os" 11 "strings" 12 "testing" 13 14 "github.com/mitchellh/cli" 15 ) 16 17 func TestStatePull(t *testing.T) { 18 // Create a temporary working directory that is empty 19 td := t.TempDir() 20 testCopyDir(t, testFixturePath("state-pull-backend"), td) 21 defer testChdir(t, td)() 22 23 expected, err := os.ReadFile("local-state.tfstate") 24 if err != nil { 25 t.Fatalf("error reading state: %v", err) 26 } 27 28 p := testProvider() 29 ui := new(cli.MockUi) 30 c := &StatePullCommand{ 31 Meta: Meta{ 32 testingOverrides: metaOverridesForProvider(p), 33 Ui: ui, 34 }, 35 } 36 37 args := []string{} 38 if code := c.Run(args); code != 0 { 39 t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String()) 40 } 41 42 actual := ui.OutputWriter.Bytes() 43 if bytes.Equal(actual, expected) { 44 t.Fatalf("expected:\n%s\n\nto include: %q", actual, expected) 45 } 46 } 47 48 func TestStatePull_noState(t *testing.T) { 49 testCwd(t) 50 51 p := testProvider() 52 ui := cli.NewMockUi() 53 c := &StatePullCommand{ 54 Meta: Meta{ 55 testingOverrides: metaOverridesForProvider(p), 56 Ui: ui, 57 }, 58 } 59 60 args := []string{} 61 if code := c.Run(args); code != 0 { 62 t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String()) 63 } 64 65 actual := ui.OutputWriter.String() 66 if actual != "" { 67 t.Fatalf("bad: %s", actual) 68 } 69 } 70 71 func TestStatePull_checkRequiredVersion(t *testing.T) { 72 // Create a temporary working directory that is empty 73 td := t.TempDir() 74 testCopyDir(t, testFixturePath("command-check-required-version"), td) 75 defer testChdir(t, td)() 76 77 p := testProvider() 78 ui := cli.NewMockUi() 79 c := &StatePullCommand{ 80 Meta: Meta{ 81 testingOverrides: metaOverridesForProvider(p), 82 Ui: ui, 83 }, 84 } 85 86 args := []string{} 87 if code := c.Run(args); code != 1 { 88 t.Fatalf("got exit status %d; want 1\nstderr:\n%s\n\nstdout:\n%s", code, ui.ErrorWriter.String(), ui.OutputWriter.String()) 89 } 90 91 // Required version diags are correct 92 errStr := ui.ErrorWriter.String() 93 if !strings.Contains(errStr, `required_version = "~> 0.9.0"`) { 94 t.Fatalf("output should point to unmet version constraint, but is:\n\n%s", errStr) 95 } 96 if strings.Contains(errStr, `required_version = ">= 0.13.0"`) { 97 t.Fatalf("output should not point to met version constraint, but is:\n\n%s", errStr) 98 } 99 }