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