github.com/lamielle/terraform@v0.3.2-0.20141121070651-81f008ba53d5/command/apply_destroy_test.go (about) 1 package command 2 3 import ( 4 "os" 5 "strings" 6 "testing" 7 8 "github.com/hashicorp/terraform/terraform" 9 "github.com/mitchellh/cli" 10 ) 11 12 func TestApply_destroy(t *testing.T) { 13 originalState := &terraform.State{ 14 Modules: []*terraform.ModuleState{ 15 &terraform.ModuleState{ 16 Path: []string{"root"}, 17 Resources: map[string]*terraform.ResourceState{ 18 "test_instance.foo": &terraform.ResourceState{ 19 Type: "test_instance", 20 Primary: &terraform.InstanceState{ 21 ID: "bar", 22 }, 23 }, 24 }, 25 }, 26 }, 27 } 28 29 statePath := testStateFile(t, originalState) 30 31 p := testProvider() 32 ui := new(cli.MockUi) 33 c := &ApplyCommand{ 34 Destroy: true, 35 Meta: Meta{ 36 ContextOpts: testCtxConfig(p), 37 Ui: ui, 38 }, 39 } 40 41 // Run the apply command pointing to our existing state 42 args := []string{ 43 "-force", 44 "-state", statePath, 45 testFixturePath("apply"), 46 } 47 if code := c.Run(args); code != 0 { 48 t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String()) 49 } 50 51 // Verify a new state exists 52 if _, err := os.Stat(statePath); err != nil { 53 t.Fatalf("err: %s", err) 54 } 55 56 f, err := os.Open(statePath) 57 if err != nil { 58 t.Fatalf("err: %s", err) 59 } 60 defer f.Close() 61 62 state, err := terraform.ReadState(f) 63 if err != nil { 64 t.Fatalf("err: %s", err) 65 } 66 if state == nil { 67 t.Fatal("state should not be nil") 68 } 69 70 actualStr := strings.TrimSpace(state.String()) 71 expectedStr := strings.TrimSpace(testApplyDestroyStr) 72 if actualStr != expectedStr { 73 t.Fatalf("bad:\n\n%s\n\n%s", actualStr, expectedStr) 74 } 75 76 // Should have a backup file 77 f, err = os.Open(statePath + DefaultBackupExtention) 78 if err != nil { 79 t.Fatalf("err: %s", err) 80 } 81 82 backupState, err := terraform.ReadState(f) 83 f.Close() 84 if err != nil { 85 t.Fatalf("err: %s", err) 86 } 87 88 actualStr = strings.TrimSpace(backupState.String()) 89 expectedStr = strings.TrimSpace(originalState.String()) 90 if actualStr != expectedStr { 91 t.Fatalf("bad:\n\n%s\n\n%s", actualStr, expectedStr) 92 } 93 } 94 95 func TestApply_destroyPlan(t *testing.T) { 96 planPath := testPlanFile(t, &terraform.Plan{ 97 Module: testModule(t, "apply"), 98 }) 99 100 p := testProvider() 101 ui := new(cli.MockUi) 102 c := &ApplyCommand{ 103 Destroy: true, 104 Meta: Meta{ 105 ContextOpts: testCtxConfig(p), 106 Ui: ui, 107 }, 108 } 109 110 // Run the apply command pointing to our existing state 111 args := []string{ 112 planPath, 113 } 114 if code := c.Run(args); code != 1 { 115 t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String()) 116 } 117 } 118 119 const testApplyDestroyStr = ` 120 <no state> 121 `