streamformatter_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package streamformatter
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "reflect"
  6. "testing"
  7. "github.com/docker/docker/pkg/jsonmessage"
  8. )
  9. func TestFormatStream(t *testing.T) {
  10. sf := NewStreamFormatter(true)
  11. res := sf.FormatStream("stream")
  12. if string(res) != `{"stream":"stream"}`+"\r\n" {
  13. t.Fatalf("%q", res)
  14. }
  15. }
  16. func TestFormatStatus(t *testing.T) {
  17. sf := NewStreamFormatter(true)
  18. res := sf.FormatStatus("ID", "%s%d", "a", 1)
  19. if string(res) != `{"status":"a1","id":"ID"}`+"\r\n" {
  20. t.Fatalf("%q", res)
  21. }
  22. }
  23. func TestFormatSimpleError(t *testing.T) {
  24. sf := NewStreamFormatter(true)
  25. res := sf.FormatError(errors.New("Error for formatter"))
  26. if string(res) != `{"errorDetail":{"message":"Error for formatter"},"error":"Error for formatter"}`+"\r\n" {
  27. t.Fatalf("%q", res)
  28. }
  29. }
  30. func TestFormatJSONError(t *testing.T) {
  31. sf := NewStreamFormatter(true)
  32. err := &jsonmessage.JSONError{Code: 50, Message: "Json error"}
  33. res := sf.FormatError(err)
  34. if string(res) != `{"errorDetail":{"code":50,"message":"Json error"},"error":"Json error"}`+"\r\n" {
  35. t.Fatalf("%q", res)
  36. }
  37. }
  38. func TestFormatProgress(t *testing.T) {
  39. sf := NewStreamFormatter(true)
  40. progress := &jsonmessage.JSONProgress{
  41. Current: 15,
  42. Total: 30,
  43. Start: 1,
  44. }
  45. res := sf.FormatProgress("id", "action", progress)
  46. msg := &jsonmessage.JSONMessage{}
  47. if err := json.Unmarshal(res, msg); err != nil {
  48. t.Fatal(err)
  49. }
  50. if msg.ID != "id" {
  51. t.Fatalf("ID must be 'id', got: %s", msg.ID)
  52. }
  53. if msg.Status != "action" {
  54. t.Fatalf("Status must be 'action', got: %s", msg.Status)
  55. }
  56. if msg.ProgressMessage != progress.String() {
  57. t.Fatalf("ProgressMessage must be %s, got: %s", progress.String(), msg.ProgressMessage)
  58. }
  59. if !reflect.DeepEqual(msg.Progress, progress) {
  60. t.Fatal("Original progress not equals progress from FormatProgress")
  61. }
  62. }