github.com/ggriffiths/terraform@v0.9.0-beta1.0.20170222213024-79c4935604cb/builtin/provisioners/local-exec/resource_provisioner_test.go (about) 1 package localexec 2 3 import ( 4 "io/ioutil" 5 "log" 6 "os" 7 "strings" 8 "testing" 9 "time" 10 11 "github.com/hashicorp/terraform/config" 12 "github.com/hashicorp/terraform/terraform" 13 ) 14 15 func TestResourceProvider_Apply(t *testing.T) { 16 defer os.Remove("test_out") 17 c := testConfig(t, map[string]interface{}{ 18 "command": "echo foo > test_out", 19 }) 20 21 output := new(terraform.MockUIOutput) 22 p := Provisioner() 23 if err := p.Apply(output, nil, c); err != nil { 24 t.Fatalf("err: %v", err) 25 } 26 27 // Check the file 28 raw, err := ioutil.ReadFile("test_out") 29 if err != nil { 30 t.Fatalf("err: %v", err) 31 } 32 33 actual := strings.TrimSpace(string(raw)) 34 expected := "foo" 35 if actual != expected { 36 t.Fatalf("bad: %#v", actual) 37 } 38 } 39 40 func TestResourceProvider_stop(t *testing.T) { 41 c := testConfig(t, map[string]interface{}{ 42 // bash/zsh/ksh will exec a single command in the same process. This 43 // makes certain there's a subprocess in the shell. 44 "command": "sleep 30; sleep 30", 45 }) 46 47 output := new(terraform.MockUIOutput) 48 p := Provisioner() 49 50 var err error 51 doneCh := make(chan struct{}) 52 go func() { 53 defer close(doneCh) 54 err = p.Apply(output, nil, c) 55 }() 56 57 select { 58 case <-doneCh: 59 t.Fatal("should not finish quickly") 60 case <-time.After(50 * time.Millisecond): 61 } 62 63 // Stop it 64 p.Stop() 65 66 select { 67 case <-doneCh: 68 case <-time.After(500 * time.Millisecond): 69 log.Fatal("should finish") 70 } 71 } 72 73 func TestResourceProvider_Validate_good(t *testing.T) { 74 c := testConfig(t, map[string]interface{}{ 75 "command": "echo foo", 76 }) 77 p := Provisioner() 78 warn, errs := p.Validate(c) 79 if len(warn) > 0 { 80 t.Fatalf("Warnings: %v", warn) 81 } 82 if len(errs) > 0 { 83 t.Fatalf("Errors: %v", errs) 84 } 85 } 86 87 func TestResourceProvider_Validate_missing(t *testing.T) { 88 c := testConfig(t, map[string]interface{}{}) 89 p := Provisioner() 90 warn, errs := p.Validate(c) 91 if len(warn) > 0 { 92 t.Fatalf("Warnings: %v", warn) 93 } 94 if len(errs) == 0 { 95 t.Fatalf("Should have errors") 96 } 97 } 98 99 func testConfig( 100 t *testing.T, 101 c map[string]interface{}) *terraform.ResourceConfig { 102 r, err := config.NewRawConfig(c) 103 if err != nil { 104 t.Fatalf("bad: %s", err) 105 } 106 107 return terraform.NewResourceConfig(r) 108 }