github.com/damirazo/docker@v1.9.0/pkg/streamformatter/streamformatter_test.go (about) 1 package streamformatter 2 3 import ( 4 "encoding/json" 5 "errors" 6 "reflect" 7 "testing" 8 9 "github.com/docker/docker/pkg/jsonmessage" 10 ) 11 12 func TestFormatStream(t *testing.T) { 13 sf := NewStreamFormatter() 14 res := sf.FormatStream("stream") 15 if string(res) != "stream"+"\r" { 16 t.Fatalf("%q", res) 17 } 18 } 19 20 func TestFormatJSONStatus(t *testing.T) { 21 sf := NewStreamFormatter() 22 res := sf.FormatStatus("ID", "%s%d", "a", 1) 23 if string(res) != "a1\r\n" { 24 t.Fatalf("%q", res) 25 } 26 } 27 28 func TestFormatSimpleError(t *testing.T) { 29 sf := NewStreamFormatter() 30 res := sf.FormatError(errors.New("Error for formatter")) 31 if string(res) != "Error: Error for formatter\r\n" { 32 t.Fatalf("%q", res) 33 } 34 } 35 36 func TestJSONFormatStream(t *testing.T) { 37 sf := NewJSONStreamFormatter() 38 res := sf.FormatStream("stream") 39 if string(res) != `{"stream":"stream"}`+"\r\n" { 40 t.Fatalf("%q", res) 41 } 42 } 43 44 func TestJSONFormatStatus(t *testing.T) { 45 sf := NewJSONStreamFormatter() 46 res := sf.FormatStatus("ID", "%s%d", "a", 1) 47 if string(res) != `{"status":"a1","id":"ID"}`+"\r\n" { 48 t.Fatalf("%q", res) 49 } 50 } 51 52 func TestJSONFormatSimpleError(t *testing.T) { 53 sf := NewJSONStreamFormatter() 54 res := sf.FormatError(errors.New("Error for formatter")) 55 if string(res) != `{"errorDetail":{"message":"Error for formatter"},"error":"Error for formatter"}`+"\r\n" { 56 t.Fatalf("%q", res) 57 } 58 } 59 60 func TestJSONFormatJSONError(t *testing.T) { 61 sf := NewJSONStreamFormatter() 62 err := &jsonmessage.JSONError{Code: 50, Message: "Json error"} 63 res := sf.FormatError(err) 64 if string(res) != `{"errorDetail":{"code":50,"message":"Json error"},"error":"Json error"}`+"\r\n" { 65 t.Fatalf("%q", res) 66 } 67 } 68 69 func TestJSONFormatProgress(t *testing.T) { 70 sf := NewJSONStreamFormatter() 71 progress := &jsonmessage.JSONProgress{ 72 Current: 15, 73 Total: 30, 74 Start: 1, 75 } 76 res := sf.FormatProgress("id", "action", progress) 77 msg := &jsonmessage.JSONMessage{} 78 if err := json.Unmarshal(res, msg); err != nil { 79 t.Fatal(err) 80 } 81 if msg.ID != "id" { 82 t.Fatalf("ID must be 'id', got: %s", msg.ID) 83 } 84 if msg.Status != "action" { 85 t.Fatalf("Status must be 'action', got: %s", msg.Status) 86 } 87 if msg.ProgressMessage != progress.String() { 88 t.Fatalf("ProgressMessage must be %s, got: %s", progress.String(), msg.ProgressMessage) 89 } 90 if !reflect.DeepEqual(msg.Progress, progress) { 91 t.Fatal("Original progress not equals progress from FormatProgress") 92 } 93 }