github.com/ld86/docker@v1.7.1-rc3/daemon/logger/copier_test.go (about) 1 package logger 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "errors" 7 "io" 8 "testing" 9 "time" 10 ) 11 12 type TestLoggerJSON struct { 13 *json.Encoder 14 } 15 16 func (l *TestLoggerJSON) Log(m *Message) error { return l.Encode(m) } 17 18 func (l *TestLoggerJSON) Close() error { return nil } 19 20 func (l *TestLoggerJSON) Name() string { return "json" } 21 22 func (l *TestLoggerJSON) GetReader() (io.Reader, error) { 23 return nil, errors.New("not used in the test") 24 } 25 26 type TestLoggerText struct { 27 *bytes.Buffer 28 } 29 30 func (l *TestLoggerText) Log(m *Message) error { 31 _, err := l.WriteString(m.ContainerID + " " + m.Source + " " + string(m.Line) + "\n") 32 return err 33 } 34 35 func (l *TestLoggerText) Close() error { return nil } 36 37 func (l *TestLoggerText) Name() string { return "text" } 38 39 func (l *TestLoggerText) GetReader() (io.Reader, error) { 40 return nil, errors.New("not used in the test") 41 } 42 43 func TestCopier(t *testing.T) { 44 stdoutLine := "Line that thinks that it is log line from docker stdout" 45 stderrLine := "Line that thinks that it is log line from docker stderr" 46 var stdout bytes.Buffer 47 var stderr bytes.Buffer 48 for i := 0; i < 30; i++ { 49 if _, err := stdout.WriteString(stdoutLine + "\n"); err != nil { 50 t.Fatal(err) 51 } 52 if _, err := stderr.WriteString(stderrLine + "\n"); err != nil { 53 t.Fatal(err) 54 } 55 } 56 57 var jsonBuf bytes.Buffer 58 59 jsonLog := &TestLoggerJSON{Encoder: json.NewEncoder(&jsonBuf)} 60 61 cid := "a7317399f3f857173c6179d44823594f8294678dea9999662e5c625b5a1c7657" 62 c, err := NewCopier(cid, 63 map[string]io.Reader{ 64 "stdout": &stdout, 65 "stderr": &stderr, 66 }, 67 jsonLog) 68 if err != nil { 69 t.Fatal(err) 70 } 71 c.Run() 72 wait := make(chan struct{}) 73 go func() { 74 c.Wait() 75 close(wait) 76 }() 77 select { 78 case <-time.After(1 * time.Second): 79 t.Fatal("Copier failed to do its work in 1 second") 80 case <-wait: 81 } 82 dec := json.NewDecoder(&jsonBuf) 83 for { 84 var msg Message 85 if err := dec.Decode(&msg); err != nil { 86 if err == io.EOF { 87 break 88 } 89 t.Fatal(err) 90 } 91 if msg.Source != "stdout" && msg.Source != "stderr" { 92 t.Fatalf("Wrong Source: %q, should be %q or %q", msg.Source, "stdout", "stderr") 93 } 94 if msg.ContainerID != cid { 95 t.Fatalf("Wrong ContainerID: %q, expected %q", msg.ContainerID, cid) 96 } 97 if msg.Source == "stdout" { 98 if string(msg.Line) != stdoutLine { 99 t.Fatalf("Wrong Line: %q, expected %q", msg.Line, stdoutLine) 100 } 101 } 102 if msg.Source == "stderr" { 103 if string(msg.Line) != stderrLine { 104 t.Fatalf("Wrong Line: %q, expected %q", msg.Line, stderrLine) 105 } 106 } 107 } 108 }