json_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package websocket
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "io"
  9. "reflect"
  10. "testing"
  11. )
  12. func TestJSON(t *testing.T) {
  13. var buf bytes.Buffer
  14. c := fakeNetConn{&buf, &buf}
  15. wc := newConn(c, true, 1024, 1024)
  16. rc := newConn(c, false, 1024, 1024)
  17. var actual, expect struct {
  18. A int
  19. B string
  20. }
  21. expect.A = 1
  22. expect.B = "hello"
  23. if err := wc.WriteJSON(&expect); err != nil {
  24. t.Fatal("write", err)
  25. }
  26. if err := rc.ReadJSON(&actual); err != nil {
  27. t.Fatal("read", err)
  28. }
  29. if !reflect.DeepEqual(&actual, &expect) {
  30. t.Fatal("equal", actual, expect)
  31. }
  32. }
  33. func TestPartialJSONRead(t *testing.T) {
  34. var buf bytes.Buffer
  35. c := fakeNetConn{&buf, &buf}
  36. wc := newConn(c, true, 1024, 1024)
  37. rc := newConn(c, false, 1024, 1024)
  38. var v struct {
  39. A int
  40. B string
  41. }
  42. v.A = 1
  43. v.B = "hello"
  44. messageCount := 0
  45. // Partial JSON values.
  46. data, err := json.Marshal(v)
  47. if err != nil {
  48. t.Fatal(err)
  49. }
  50. for i := len(data) - 1; i >= 0; i-- {
  51. if err := wc.WriteMessage(TextMessage, data[:i]); err != nil {
  52. t.Fatal(err)
  53. }
  54. messageCount++
  55. }
  56. // Whitespace.
  57. if err := wc.WriteMessage(TextMessage, []byte(" ")); err != nil {
  58. t.Fatal(err)
  59. }
  60. messageCount++
  61. // Close.
  62. if err := wc.WriteMessage(CloseMessage, FormatCloseMessage(CloseNormalClosure, "")); err != nil {
  63. t.Fatal(err)
  64. }
  65. for i := 0; i < messageCount; i++ {
  66. err := rc.ReadJSON(&v)
  67. if err != io.ErrUnexpectedEOF {
  68. t.Error("read", i, err)
  69. }
  70. }
  71. err = rc.ReadJSON(&v)
  72. if _, ok := err.(*CloseError); !ok {
  73. t.Error("final", err)
  74. }
  75. }
  76. func TestDeprecatedJSON(t *testing.T) {
  77. var buf bytes.Buffer
  78. c := fakeNetConn{&buf, &buf}
  79. wc := newConn(c, true, 1024, 1024)
  80. rc := newConn(c, false, 1024, 1024)
  81. var actual, expect struct {
  82. A int
  83. B string
  84. }
  85. expect.A = 1
  86. expect.B = "hello"
  87. if err := WriteJSON(wc, &expect); err != nil {
  88. t.Fatal("write", err)
  89. }
  90. if err := ReadJSON(rc, &actual); err != nil {
  91. t.Fatal("read", err)
  92. }
  93. if !reflect.DeepEqual(&actual, &expect) {
  94. t.Fatal("equal", actual, expect)
  95. }
  96. }