json_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2016 Google Inc. 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 uuid
  5. import (
  6. "encoding/json"
  7. "reflect"
  8. "testing"
  9. )
  10. var testUUID = Must(Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479"))
  11. func TestJSON(t *testing.T) {
  12. type S struct {
  13. ID1 UUID
  14. ID2 UUID
  15. }
  16. s1 := S{ID1: testUUID}
  17. data, err := json.Marshal(&s1)
  18. if err != nil {
  19. t.Fatal(err)
  20. }
  21. var s2 S
  22. if err := json.Unmarshal(data, &s2); err != nil {
  23. t.Fatal(err)
  24. }
  25. if !reflect.DeepEqual(&s1, &s2) {
  26. t.Errorf("got %#v, want %#v", s2, s1)
  27. }
  28. }
  29. func BenchmarkUUID_MarshalJSON(b *testing.B) {
  30. x := &struct {
  31. UUID UUID `json:"uuid"`
  32. }{}
  33. var err error
  34. x.UUID, err = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
  35. if err != nil {
  36. b.Fatal(err)
  37. }
  38. for i := 0; i < b.N; i++ {
  39. js, err := json.Marshal(x)
  40. if err != nil {
  41. b.Fatalf("marshal json: %#v (%v)", js, err)
  42. }
  43. }
  44. }
  45. func BenchmarkUUID_UnmarshalJSON(b *testing.B) {
  46. js := []byte(`{"uuid":"f47ac10b-58cc-0372-8567-0e02b2c3d479"}`)
  47. var x *struct {
  48. UUID UUID `json:"uuid"`
  49. }
  50. for i := 0; i < b.N; i++ {
  51. err := json.Unmarshal(js, &x)
  52. if err != nil {
  53. b.Fatalf("marshal json: %#v (%v)", js, err)
  54. }
  55. }
  56. }