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