github.com/supr/packer@v0.3.10-0.20131015195147-7b09e24ac3c1/packer/plugin/client_test.go (about) 1 package plugin 2 3 import ( 4 "bytes" 5 "io/ioutil" 6 "os" 7 "strings" 8 "testing" 9 "time" 10 ) 11 12 func TestClient(t *testing.T) { 13 process := helperProcess("mock") 14 c := NewClient(&ClientConfig{Cmd: process}) 15 defer c.Kill() 16 17 // Test that it parses the proper address 18 addr, err := c.Start() 19 if err != nil { 20 t.Fatalf("err should be nil, got %s", err) 21 } 22 23 if addr != ":1234" { 24 t.Fatalf("incorrect addr %s", addr) 25 } 26 27 // Test that it exits properly if killed 28 c.Kill() 29 30 if process.ProcessState == nil { 31 t.Fatal("should have process state") 32 } 33 34 // Test that it knows it is exited 35 if !c.Exited() { 36 t.Fatal("should say client has exited") 37 } 38 } 39 40 func TestClientStart_badVersion(t *testing.T) { 41 config := &ClientConfig{ 42 Cmd: helperProcess("bad-version"), 43 StartTimeout: 50 * time.Millisecond, 44 } 45 46 c := NewClient(config) 47 defer c.Kill() 48 49 _, err := c.Start() 50 if err == nil { 51 t.Fatal("err should not be nil") 52 } 53 } 54 55 func TestClient_Start_Timeout(t *testing.T) { 56 config := &ClientConfig{ 57 Cmd: helperProcess("start-timeout"), 58 StartTimeout: 50 * time.Millisecond, 59 } 60 61 c := NewClient(config) 62 defer c.Kill() 63 64 _, err := c.Start() 65 if err == nil { 66 t.Fatal("err should not be nil") 67 } 68 } 69 70 func TestClient_Stderr(t *testing.T) { 71 stderr := new(bytes.Buffer) 72 process := helperProcess("stderr") 73 c := NewClient(&ClientConfig{ 74 Cmd: process, 75 Stderr: stderr, 76 }) 77 defer c.Kill() 78 79 if _, err := c.Start(); err != nil { 80 t.Fatalf("err: %s", err) 81 } 82 83 for !c.Exited() { 84 time.Sleep(10 * time.Millisecond) 85 } 86 87 if !strings.Contains(stderr.String(), "HELLO\n") { 88 t.Fatalf("bad log data: '%s'", stderr.String()) 89 } 90 91 if !strings.Contains(stderr.String(), "WORLD\n") { 92 t.Fatalf("bad log data: '%s'", stderr.String()) 93 } 94 } 95 96 func TestClient_Stdin(t *testing.T) { 97 // Overwrite stdin for this test with a temporary file 98 tf, err := ioutil.TempFile("", "packer") 99 if err != nil { 100 t.Fatalf("err: %s", err) 101 } 102 defer os.Remove(tf.Name()) 103 defer tf.Close() 104 105 if _, err = tf.WriteString("hello"); err != nil { 106 t.Fatalf("error: %s", err) 107 } 108 109 if err = tf.Sync(); err != nil { 110 t.Fatalf("error: %s", err) 111 } 112 113 if _, err = tf.Seek(0, 0); err != nil { 114 t.Fatalf("error: %s", err) 115 } 116 117 oldStdin := os.Stdin 118 defer func() { os.Stdin = oldStdin }() 119 os.Stdin = tf 120 121 process := helperProcess("stdin") 122 c := NewClient(&ClientConfig{Cmd: process}) 123 defer c.Kill() 124 125 _, err = c.Start() 126 if err != nil { 127 t.Fatalf("error: %s", err) 128 } 129 130 for { 131 if c.Exited() { 132 break 133 } 134 135 time.Sleep(50 * time.Millisecond) 136 } 137 138 if !process.ProcessState.Success() { 139 t.Fatal("process didn't exit cleanly") 140 } 141 }