github.com/phobos182/packer@v0.2.3-0.20130819023704-c84d2aeffc68/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 TestClient_Start_Timeout(t *testing.T) { 41 config := &ClientConfig{ 42 Cmd: helperProcess("start-timeout"), 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_Stderr(t *testing.T) { 56 stderr := new(bytes.Buffer) 57 process := helperProcess("stderr") 58 c := NewClient(&ClientConfig{ 59 Cmd: process, 60 Stderr: stderr, 61 }) 62 defer c.Kill() 63 64 if _, err := c.Start(); err != nil { 65 t.Fatalf("err: %s", err) 66 } 67 68 for !c.Exited() { 69 time.Sleep(10 * time.Millisecond) 70 } 71 72 if !strings.Contains(stderr.String(), "HELLO\n") { 73 t.Fatalf("bad log data: '%s'", stderr.String()) 74 } 75 76 if !strings.Contains(stderr.String(), "WORLD\n") { 77 t.Fatalf("bad log data: '%s'", stderr.String()) 78 } 79 } 80 81 func TestClient_Stdin(t *testing.T) { 82 // Overwrite stdin for this test with a temporary file 83 tf, err := ioutil.TempFile("", "packer") 84 if err != nil { 85 t.Fatalf("err: %s", err) 86 } 87 defer os.Remove(tf.Name()) 88 defer tf.Close() 89 90 if _, err = tf.WriteString("hello"); err != nil { 91 t.Fatalf("error: %s", err) 92 } 93 94 if err = tf.Sync(); err != nil { 95 t.Fatalf("error: %s", err) 96 } 97 98 if _, err = tf.Seek(0, 0); err != nil { 99 t.Fatalf("error: %s", err) 100 } 101 102 oldStdin := os.Stdin 103 defer func() { os.Stdin = oldStdin }() 104 os.Stdin = tf 105 106 process := helperProcess("stdin") 107 c := NewClient(&ClientConfig{Cmd: process}) 108 defer c.Kill() 109 110 _, err = c.Start() 111 if err != nil { 112 t.Fatalf("error: %s", err) 113 } 114 115 for { 116 if c.Exited() { 117 break 118 } 119 120 time.Sleep(50 * time.Millisecond) 121 } 122 123 if !process.ProcessState.Success() { 124 t.Fatal("process didn't exit cleanly") 125 } 126 }