streamformatter_test.go 1.7 KB

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