json_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package json_util
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "testing"
  6. )
  7. func TestRawMessage_MarshalEmptyIsNull(t *testing.T) {
  8. var m RawMessage
  9. out, err := m.MarshalJSON()
  10. if err != nil {
  11. t.Fatalf("MarshalJSON on empty returned error: %v", err)
  12. }
  13. if !bytes.Equal(out, []byte("null")) {
  14. t.Fatalf("empty RawMessage marshaled to %q, want %q", out, "null")
  15. }
  16. }
  17. func TestRawMessage_MarshalPassthrough(t *testing.T) {
  18. payload := []byte(`{"a":1}`)
  19. m := RawMessage(payload)
  20. out, err := m.MarshalJSON()
  21. if err != nil {
  22. t.Fatalf("MarshalJSON returned error: %v", err)
  23. }
  24. if !bytes.Equal(out, payload) {
  25. t.Fatalf("MarshalJSON = %q, want %q", out, payload)
  26. }
  27. }
  28. func TestRawMessage_UnmarshalCopiesData(t *testing.T) {
  29. var m RawMessage
  30. src := []byte(`{"k":"v"}`)
  31. if err := m.UnmarshalJSON(src); err != nil {
  32. t.Fatalf("UnmarshalJSON returned error: %v", err)
  33. }
  34. if !bytes.Equal(m, src) {
  35. t.Fatalf("UnmarshalJSON stored %q, want %q", []byte(m), src)
  36. }
  37. src[0] = 'X'
  38. if m[0] == 'X' {
  39. t.Fatal("UnmarshalJSON kept a reference to the caller's buffer; expected a copy")
  40. }
  41. }
  42. func TestRawMessage_UnmarshalNilReceiverErrors(t *testing.T) {
  43. var m *RawMessage
  44. if err := m.UnmarshalJSON([]byte("123")); err == nil {
  45. t.Fatal("expected error for nil receiver")
  46. }
  47. }
  48. func TestRawMessage_RoundTripInsideStruct(t *testing.T) {
  49. type wrapper struct {
  50. Body RawMessage `json:"body"`
  51. }
  52. in := wrapper{Body: RawMessage(`{"x":42}`)}
  53. encoded, err := json.Marshal(in)
  54. if err != nil {
  55. t.Fatalf("json.Marshal returned error: %v", err)
  56. }
  57. want := `{"body":{"x":42}}`
  58. if string(encoded) != want {
  59. t.Fatalf("Marshal = %s, want %s", encoded, want)
  60. }
  61. var out wrapper
  62. if err := json.Unmarshal(encoded, &out); err != nil {
  63. t.Fatalf("json.Unmarshal returned error: %v", err)
  64. }
  65. if string(out.Body) != `{"x":42}` {
  66. t.Fatalf("round-trip Body = %s, want %s", out.Body, `{"x":42}`)
  67. }
  68. }