github.com/grbit/go-json@v0.11.0/query_test.go (about)

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