query_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package json_test
  2. import (
  3. "context"
  4. "reflect"
  5. "testing"
  6. "github.com/goccy/go-json"
  7. )
  8. type queryTestX struct {
  9. XA int
  10. XB string
  11. XC *queryTestY
  12. XD bool
  13. XE float32
  14. }
  15. type queryTestY struct {
  16. YA int
  17. YB string
  18. YC *queryTestZ
  19. YD bool
  20. YE float32
  21. }
  22. type queryTestZ struct {
  23. ZA string
  24. ZB bool
  25. ZC int
  26. }
  27. func (z *queryTestZ) MarshalJSON(ctx context.Context) ([]byte, error) {
  28. type _queryTestZ queryTestZ
  29. return json.MarshalContext(ctx, (*_queryTestZ)(z))
  30. }
  31. func TestFieldQuery(t *testing.T) {
  32. query, err := json.BuildFieldQuery(
  33. "XA",
  34. "XB",
  35. json.BuildSubFieldQuery("XC").Fields(
  36. "YA",
  37. "YB",
  38. json.BuildSubFieldQuery("YC").Fields(
  39. "ZA",
  40. "ZB",
  41. ),
  42. ),
  43. )
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. if !reflect.DeepEqual(query, &json.FieldQuery{
  48. Fields: []*json.FieldQuery{
  49. {
  50. Name: "XA",
  51. },
  52. {
  53. Name: "XB",
  54. },
  55. {
  56. Name: "XC",
  57. Fields: []*json.FieldQuery{
  58. {
  59. Name: "YA",
  60. },
  61. {
  62. Name: "YB",
  63. },
  64. {
  65. Name: "YC",
  66. Fields: []*json.FieldQuery{
  67. {
  68. Name: "ZA",
  69. },
  70. {
  71. Name: "ZB",
  72. },
  73. },
  74. },
  75. },
  76. },
  77. },
  78. }) {
  79. t.Fatal("cannot get query")
  80. }
  81. queryStr, err := query.QueryString()
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. if queryStr != `["XA","XB",{"XC":["YA","YB",{"YC":["ZA","ZB"]}]}]` {
  86. t.Fatalf("failed to create query string. %s", queryStr)
  87. }
  88. ctx := json.SetFieldQueryToContext(context.Background(), query)
  89. b, err := json.MarshalContext(ctx, &queryTestX{
  90. XA: 1,
  91. XB: "xb",
  92. XC: &queryTestY{
  93. YA: 2,
  94. YB: "yb",
  95. YC: &queryTestZ{
  96. ZA: "za",
  97. ZB: true,
  98. ZC: 3,
  99. },
  100. YD: true,
  101. YE: 4,
  102. },
  103. XD: true,
  104. XE: 5,
  105. })
  106. if err != nil {
  107. t.Fatal(err)
  108. }
  109. expected := `{"XA":1,"XB":"xb","XC":{"YA":2,"YB":"yb","YC":{"ZA":"za","ZB":true}}}`
  110. got := string(b)
  111. if expected != got {
  112. t.Fatalf("failed to encode with field query: expected %q but got %q", expected, got)
  113. }
  114. }