File: fields_test.go

package info (click to toggle)
golang-google-cloud 0.56.0-6
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 22,456 kB
  • sloc: sh: 191; ansic: 75; awk: 64; makefile: 51; asm: 46; python: 21
file content (553 lines) | stat: -rw-r--r-- 13,151 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// Copyright 2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package fields

import (
	"encoding/json"
	"errors"
	"fmt"
	"reflect"
	"testing"
	"time"

	"cloud.google.com/go/internal/testutil"
	"github.com/google/go-cmp/cmp"
)

type embed1 struct {
	Em1    int
	Dup    int // annihilates with embed2.Dup
	Shadow int
	embed3
}

type embed2 struct {
	Dup int
	embed3
	embed4
}

type embed3 struct {
	Em3 int // annihilated because embed3 is in both embed1 and embed2
	embed5
}

type embed4 struct {
	Em4     int
	Dup     int // annihilation of Dup in embed1, embed2 hides this Dup
	*embed1     // ignored because it occurs at a higher level
}

type embed5 struct {
	x int
}

type Anonymous int

type S1 struct {
	Exported   int
	unexported int
	Shadow     int // shadows S1.Shadow
	embed1
	*embed2
	Anonymous
}

type Time struct {
	time.Time
}

var intType = reflect.TypeOf(int(0))

func field(name string, tval interface{}, index ...int) *Field {
	return &Field{
		Name:      name,
		Type:      reflect.TypeOf(tval),
		Index:     index,
		ParsedTag: []string(nil),
	}
}

func tfield(name string, tval interface{}, index ...int) *Field {
	return &Field{
		Name:        name,
		Type:        reflect.TypeOf(tval),
		Index:       index,
		NameFromTag: true,
		ParsedTag:   []string(nil),
	}
}

func TestFieldsNoTags(t *testing.T) {
	c := NewCache(nil, nil, nil)
	got, err := c.Fields(reflect.TypeOf(S1{}))
	if err != nil {
		t.Fatal(err)
	}
	want := []*Field{
		field("Exported", int(0), 0),
		field("Shadow", int(0), 2),
		field("Em1", int(0), 3, 0),
		field("Em4", int(0), 4, 2, 0),
		field("Anonymous", Anonymous(0), 5),
	}
	for _, f := range want {
		f.ParsedTag = nil
	}
	if msg, ok := compareFields(got, want); !ok {
		t.Error(msg)
	}
}

func TestAgainstJSONEncodingNoTags(t *testing.T) {
	// Demonstrates that this package produces the same set of fields as encoding/json.
	s1 := S1{
		Exported:   1,
		unexported: 2,
		Shadow:     3,
		embed1: embed1{
			Em1:    4,
			Dup:    5,
			Shadow: 6,
			embed3: embed3{
				Em3:    7,
				embed5: embed5{x: 8},
			},
		},
		embed2: &embed2{
			Dup: 9,
			embed3: embed3{
				Em3:    10,
				embed5: embed5{x: 11},
			},
			embed4: embed4{
				Em4:    12,
				Dup:    13,
				embed1: &embed1{Em1: 14},
			},
		},
		Anonymous: Anonymous(15),
	}
	var want S1
	want.embed2 = &embed2{} // need this because reflection won't create it
	jsonRoundTrip(t, s1, &want)
	var got S1
	got.embed2 = &embed2{}
	fields, err := NewCache(nil, nil, nil).Fields(reflect.TypeOf(got))
	if err != nil {
		t.Fatal(err)
	}
	setFields(fields, &got, s1)
	if !testutil.Equal(got, want,
		cmp.AllowUnexported(S1{}, embed1{}, embed2{}, embed3{}, embed4{}, embed5{})) {
		t.Errorf("got\n%+v\nwant\n%+v", got, want)
	}
}

// Tests use of LeafTypes parameter to NewCache
func TestAgainstJSONEncodingEmbeddedTime(t *testing.T) {
	timeLeafFn := func(t reflect.Type) bool {
		return t == reflect.TypeOf(time.Time{})
	}
	// Demonstrates that this package can produce the same set of
	// fields as encoding/json for a struct with an embedded time.Time.
	now := time.Now().UTC()
	myt := Time{
		now,
	}
	var want Time
	jsonRoundTrip(t, myt, &want)
	var got Time
	fields, err := NewCache(nil, nil, timeLeafFn).Fields(reflect.TypeOf(got))
	if err != nil {
		t.Fatal(err)
	}
	setFields(fields, &got, myt)
	if !testutil.Equal(got, want) {
		t.Errorf("got\n%+v\nwant\n%+v", got, want)
	}
}

type S2 struct {
	NoTag     int
	XXX       int           `json:"tag"` // tag name takes precedence
	Anonymous `json:"anon"` // anonymous non-structs also get their name from the tag
	Embed     `json:"em"`   // embedded structs with tags become fields
	Tag       int
	YYY       int `json:"Tag"` // tag takes precedence over untagged field of the same name
	Empty     int `json:""`    // empty tag is noop
	tEmbed1
	tEmbed2
}

type Embed struct {
	Em int
}

type tEmbed1 struct {
	Dup int
	X   int `json:"Dup2"`
}

type tEmbed2 struct {
	Y int `json:"Dup"`  // takes precedence over tEmbed1.Dup because it is tagged
	Z int `json:"Dup2"` // same name as tEmbed1.X and both tagged, so ignored
}

func jsonTagParser(t reflect.StructTag) (name string, keep bool, other interface{}, err error) {
	return ParseStandardTag("json", t)
}

func validateFunc(t reflect.Type) (err error) {
	if t.Kind() != reflect.Struct {
		return errors.New("non-struct type used")
	}

	for i := 0; i < t.NumField(); i++ {
		if t.Field(i).Type.Kind() == reflect.Slice {
			return fmt.Errorf("slice field found at field %s on struct %s", t.Field(i).Name, t.Name())
		}
	}

	return nil
}

func TestFieldsWithTags(t *testing.T) {
	got, err := NewCache(jsonTagParser, nil, nil).Fields(reflect.TypeOf(S2{}))
	if err != nil {
		t.Fatal(err)
	}
	want := []*Field{
		field("NoTag", int(0), 0),
		tfield("tag", int(0), 1),
		tfield("anon", Anonymous(0), 2),
		tfield("em", Embed{}, 4),
		tfield("Tag", int(0), 6),
		field("Empty", int(0), 7),
		tfield("Dup", int(0), 8, 0),
	}
	if msg, ok := compareFields(got, want); !ok {
		t.Error(msg)
	}
}

func TestAgainstJSONEncodingWithTags(t *testing.T) {
	// Demonstrates that this package produces the same set of fields as encoding/json.
	s2 := S2{
		NoTag:     1,
		XXX:       2,
		Anonymous: 3,
		Embed: Embed{
			Em: 4,
		},
		tEmbed1: tEmbed1{
			Dup: 5,
			X:   6,
		},
		tEmbed2: tEmbed2{
			Y: 7,
			Z: 8,
		},
	}
	var want S2
	jsonRoundTrip(t, s2, &want)
	var got S2
	fields, err := NewCache(jsonTagParser, nil, nil).Fields(reflect.TypeOf(got))
	if err != nil {
		t.Fatal(err)
	}
	setFields(fields, &got, s2)
	if !testutil.Equal(got, want, cmp.AllowUnexported(S2{})) {
		t.Errorf("got\n%+v\nwant\n%+v", got, want)
	}
}

func TestUnexportedAnonymousNonStruct(t *testing.T) {
	// An unexported anonymous non-struct field should not be recorded.
	// This is currently a bug in encoding/json.
	// https://github.com/golang/go/issues/18009
	type S struct{}

	got, err := NewCache(jsonTagParser, nil, nil).Fields(reflect.TypeOf(S{}))
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 0 {
		t.Errorf("got %d fields, want 0", len(got))
	}
}

func TestUnexportedAnonymousStruct(t *testing.T) {
	// An unexported anonymous struct with a tag is ignored.
	// This is currently a bug in encoding/json.
	// https://github.com/golang/go/issues/18009
	type (
		s1 struct{ X int }
		S2 struct {
			s1 `json:"Y"`
		}
	)
	got, err := NewCache(jsonTagParser, nil, nil).Fields(reflect.TypeOf(S2{}))
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 0 {
		t.Errorf("got %d fields, want 0", len(got))
	}
}

func TestDominantField(t *testing.T) {
	// With fields sorted by index length and then by tag presence,
	// the dominant field is always the first. Make sure all error
	// cases are caught.
	for _, test := range []struct {
		fields []Field
		wantOK bool
	}{
		// A single field is OK.
		{[]Field{{Index: []int{0}}}, true},
		{[]Field{{Index: []int{0}, NameFromTag: true}}, true},
		// A single field at top level is OK.
		{[]Field{{Index: []int{0}}, {Index: []int{1, 0}}}, true},
		{[]Field{{Index: []int{0}}, {Index: []int{1, 0}, NameFromTag: true}}, true},
		{[]Field{{Index: []int{0}, NameFromTag: true}, {Index: []int{1, 0}, NameFromTag: true}}, true},
		// A single tagged field is OK.
		{[]Field{{Index: []int{0}, NameFromTag: true}, {Index: []int{1}}}, true},
		// Two untagged fields at the same level is an error.
		{[]Field{{Index: []int{0}}, {Index: []int{1}}}, false},
		// Two tagged fields at the same level is an error.
		{[]Field{{Index: []int{0}, NameFromTag: true}, {Index: []int{1}, NameFromTag: true}}, false},
	} {
		_, gotOK := dominantField(test.fields)
		if gotOK != test.wantOK {
			t.Errorf("%v: got %t, want %t", test.fields, gotOK, test.wantOK)
		}
	}
}

func TestIgnore(t *testing.T) {
	type S struct {
		X int `json:"-"`
	}
	got, err := NewCache(jsonTagParser, nil, nil).Fields(reflect.TypeOf(S{}))
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 0 {
		t.Errorf("got %d fields, want 0", len(got))
	}
}

func TestParsedTag(t *testing.T) {
	type S struct {
		X int `json:"name,omitempty"`
	}
	got, err := NewCache(jsonTagParser, nil, nil).Fields(reflect.TypeOf(S{}))
	if err != nil {
		t.Fatal(err)
	}
	want := []*Field{
		{Name: "name", NameFromTag: true, Type: intType,
			Index: []int{0}, ParsedTag: []string{"omitempty"}},
	}
	if msg, ok := compareFields(got, want); !ok {
		t.Error(msg)
	}
}

func TestValidateFunc(t *testing.T) {
	type MyInvalidStruct struct {
		A string
		B []int
	}

	_, err := NewCache(nil, validateFunc, nil).Fields(reflect.TypeOf(MyInvalidStruct{}))
	if err == nil {
		t.Fatal("expected error, got nil")
	}

	type MyValidStruct struct {
		A string
		B int
	}
	_, err = NewCache(nil, validateFunc, nil).Fields(reflect.TypeOf(MyValidStruct{}))
	if err != nil {
		t.Fatalf("expected nil, got error: %s\n", err)
	}
}

func compareFields(got []Field, want []*Field) (msg string, ok bool) {
	if len(got) != len(want) {
		return fmt.Sprintf("got %d fields, want %d", len(got), len(want)), false
	}
	for i, g := range got {
		w := *want[i]
		if !fieldsEqual(&g, &w) {
			return fmt.Sprintf("got\n%+v\nwant\n%+v", g, w), false
		}
	}
	return "", true
}

// Need this because Field contains a function, which cannot be compared even
// by testutil.Equal.
func fieldsEqual(f1, f2 *Field) bool {
	if f1 == nil || f2 == nil {
		return f1 == f2
	}
	return f1.Name == f2.Name &&
		f1.NameFromTag == f2.NameFromTag &&
		f1.Type == f2.Type &&
		testutil.Equal(f1.ParsedTag, f2.ParsedTag)
}

// Set the fields of dst from those of src.
// dst must be a pointer to a struct value.
// src must be a struct value.
func setFields(fields []Field, dst, src interface{}) {
	vsrc := reflect.ValueOf(src)
	vdst := reflect.ValueOf(dst).Elem()
	for _, f := range fields {
		fdst := vdst.FieldByIndex(f.Index)
		fsrc := vsrc.FieldByIndex(f.Index)
		fdst.Set(fsrc)
	}
}

func jsonRoundTrip(t *testing.T, in, out interface{}) {
	bytes, err := json.Marshal(in)
	if err != nil {
		t.Fatal(err)
	}
	if err := json.Unmarshal(bytes, out); err != nil {
		t.Fatal(err)
	}
}

type S3 struct {
	S4
	Abc        int
	AbC        int
	Tag        int
	X          int `json:"Tag"`
	unexported int
}

type S4 struct {
	ABc int
	Y   int `json:"Abc"` // ignored because of top-level Abc
}

func TestMatchingField(t *testing.T) {
	fields, err := NewCache(jsonTagParser, nil, nil).Fields(reflect.TypeOf(S3{}))
	if err != nil {
		t.Fatal(err)
	}
	for _, test := range []struct {
		name string
		want *Field
	}{
		// Exact match wins.
		{"Abc", field("Abc", int(0), 1)},
		{"AbC", field("AbC", int(0), 2)},
		{"ABc", field("ABc", int(0), 0, 0)},
		// If there are multiple matches but no exact match or tag,
		// the first field wins, lexicographically by index.
		// Here, "ABc" is at a deeper embedding level, but since S4 appears
		// first in S3, its index precedes the other fields of S3.
		{"abc", field("ABc", int(0), 0, 0)},
		// Tag name takes precedence over untagged field of the same name.
		{"Tag", tfield("Tag", int(0), 4)},
		// Unexported fields disappear.
		{"unexported", nil},
		// Untagged embedded structs disappear.
		{"S4", nil},
	} {
		if got := fields.Match(test.name); !fieldsEqual(got, test.want) {
			t.Errorf("match %q:\ngot  %+v\nwant %+v", test.name, got, test.want)
		}
	}
}

func TestAgainstJSONMatchingField(t *testing.T) {
	s3 := S3{
		S4:         S4{ABc: 1, Y: 2},
		Abc:        3,
		AbC:        4,
		Tag:        5,
		X:          6,
		unexported: 7,
	}
	var want S3
	jsonRoundTrip(t, s3, &want)
	v := reflect.ValueOf(want)
	fields, err := NewCache(jsonTagParser, nil, nil).Fields(reflect.TypeOf(S3{}))
	if err != nil {
		t.Fatal(err)
	}
	for _, test := range []struct {
		name string
		got  int
	}{
		{"Abc", 3},
		{"AbC", 4},
		{"ABc", 1},
		{"abc", 1},
		{"Tag", 6},
	} {
		f := fields.Match(test.name)
		if f == nil {
			t.Fatalf("%s: no match", test.name)
		}
		w := v.FieldByIndex(f.Index).Interface()
		if test.got != w {
			t.Errorf("%s: got %d, want %d", test.name, test.got, w)
		}
	}
}

func TestTagErrors(t *testing.T) {
	called := false
	c := NewCache(func(t reflect.StructTag) (string, bool, interface{}, error) {
		called = true
		s := t.Get("f")
		if s == "bad" {
			return "", false, nil, errors.New("error")
		}
		return s, true, nil, nil
	}, nil, nil)

	type T struct {
		X int `f:"ok"`
		Y int `f:"bad"`
	}

	_, err := c.Fields(reflect.TypeOf(T{}))
	if !called {
		t.Fatal("tag parser not called")
	}
	if err == nil {
		t.Error("want error, got nil")
	}
	// Second time, we should cache the error.
	called = false
	_, err = c.Fields(reflect.TypeOf(T{}))
	if called {
		t.Fatal("tag parser called on second time")
	}
	if err == nil {
		t.Error("want error, got nil")
	}
}