forked from brianvoe/gofakeit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstruct.go
619 lines (530 loc) · 13.9 KB
/
struct.go
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
package gofakeit
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
// Struct fills in exported fields of a struct with random data
// based on the value of `fake` tag of exported fields
// or with the result of a call to the Fake() method
// if the field type implements `Fakeable`.
// Use `fake:"skip"` to explicitly skip an element.
// All built-in types are supported, with templating support
// for string types.
func Struct(v any) error { return structFunc(GlobalFaker, v) }
// Struct fills in exported fields of a struct with random data
// based on the value of `fake` tag of exported fields.
// Use `fake:"skip"` to explicitly skip an element.
// All built-in types are supported, with templating support
// for string types.
func (f *Faker) Struct(v any) error { return structFunc(f, v) }
func structFunc(f *Faker, v any) error {
return r(f, reflect.TypeOf(v), reflect.ValueOf(v), "", 0)
}
func r(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error {
// Handle special types
if t.PkgPath() == "encoding/json" {
// encoding/json has two special types:
// - RawMessage
// - Number
switch t.Name() {
case "RawMessage":
return rJsonRawMessage(f, t, v, tag, size)
case "Number":
return rJsonNumber(f, t, v, tag, size)
default:
return errors.New("unknown encoding/json type: " + t.Name())
}
}
// Handle generic types
switch t.Kind() {
case reflect.Ptr:
return rPointer(f, t, v, tag, size)
case reflect.Struct:
return rStruct(f, t, v, tag)
case reflect.String:
return rString(f, t, v, tag)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return rUint(f, t, v, tag)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return rInt(f, t, v, tag)
case reflect.Float32, reflect.Float64:
return rFloat(f, t, v, tag)
case reflect.Bool:
return rBool(f, t, v, tag)
case reflect.Array, reflect.Slice:
return rSlice(f, t, v, tag, size)
case reflect.Map:
return rMap(f, t, v, tag, size)
}
return nil
}
func rCustom(f *Faker, t reflect.Type, v reflect.Value, tag string) error {
// If tag is empty return error
if tag == "" {
return errors.New("tag is empty")
}
fName, fParams := parseNameAndParamsFromTag(tag)
info := GetFuncLookup(fName)
// Check to see if it's a replaceable lookup function
if info == nil {
return fmt.Errorf("function %q not found", tag)
}
// Parse map params
mapParams, err := parseMapParams(info, fParams)
if err != nil {
return err
}
// Call function
fValue, err := info.Generate(f, mapParams, info)
if err != nil {
return err
}
// Create new element of expected type
field := reflect.New(reflect.TypeOf(fValue))
field.Elem().Set(reflect.ValueOf(fValue))
// Check if element is pointer if so
// grab the underlying value
fieldElem := field.Elem()
if fieldElem.Kind() == reflect.Ptr {
fieldElem = fieldElem.Elem()
}
// Check if field kind is the same as the expected type
if fieldElem.Kind() != v.Kind() {
// return error saying the field and kinds that do not match
return errors.New("field kind " + fieldElem.Kind().String() + " does not match expected kind " + v.Kind().String())
}
// Set the value
v.Set(fieldElem.Convert(v.Type()))
// If a function is called to set the struct
// stop from going through sub fields
return nil
}
func rStruct(f *Faker, t reflect.Type, v reflect.Value, tag string) error {
// Check if tag exists, if so run custom function
if t.Name() != "" && tag != "" {
return rCustom(f, t, v, tag)
}
// Check if struct is fakeable
if isFakeable(t) {
value, err := callFake(f, v, reflect.Struct)
if err != nil {
return err
}
v.Set(reflect.ValueOf(value))
return nil
}
// Loop through all the fields of the struct
n := t.NumField()
for i := 0; i < n; i++ {
elementT := t.Field(i)
elementV := v.Field(i)
fakeTag, ok := elementT.Tag.Lookup("fake")
// Check whether or not to skip this field
if ok && fakeTag == "skip" || fakeTag == "-" {
// Do nothing, skip it
continue
}
// Check to make sure you can set it or that it's an embedded(anonymous) field
if !elementV.CanSet() && !elementT.Anonymous {
continue
}
// Check if reflect type is of values we can specifically set
elemStr := elementT.Type.String()
switch elemStr {
case "time.Time", "*time.Time":
// Check if element is a pointer
elemV := elementV
if elemStr == "*time.Time" {
elemV = reflect.New(elementT.Type.Elem()).Elem()
}
// Run rTime on the element
err := rTime(f, elementT, elemV, fakeTag)
if err != nil {
return err
}
if elemStr == "*time.Time" {
elementV.Set(elemV.Addr())
}
continue
}
// Check if fakesize is set
size := -1 // Set to -1 to indicate fakesize was not set
fs, ok := elementT.Tag.Lookup("fakesize")
if ok {
var err error
// Check if size has params separated by ,
if strings.Contains(fs, ",") {
sizeSplit := strings.SplitN(fs, ",", 2)
if len(sizeSplit) == 2 {
var sizeMin int
var sizeMax int
sizeMin, err = strconv.Atoi(sizeSplit[0])
if err != nil {
return err
}
sizeMax, err = strconv.Atoi(sizeSplit[1])
if err != nil {
return err
}
size = f.IntN(sizeMax-sizeMin+1) + sizeMin
}
} else {
size, err = strconv.Atoi(fs)
if err != nil {
return err
}
}
}
// Recursively call r() to fill in the struct
err := r(f, elementT.Type, elementV, fakeTag, size)
if err != nil {
return err
}
}
return nil
}
func rPointer(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error {
elemT := t.Elem()
if v.IsNil() {
nv := reflect.New(elemT).Elem()
err := r(f, elemT, nv, tag, size)
if err != nil {
return err
}
v.Set(nv.Addr())
} else {
err := r(f, elemT, v.Elem(), tag, size)
if err != nil {
return err
}
}
return nil
}
func rSlice(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error {
// If you cant even set it dont even try
if !v.CanSet() {
return errors.New("cannot set slice")
}
// Check if tag exists, if so run custom function
if t.Name() != "" && tag != "" {
// Check to see if custom function works if not continue to normal loop of values
err := rCustom(f, t, v, tag)
if err == nil {
return nil
}
} else if isFakeable(t) {
value, err := callFake(f, v, reflect.Slice, reflect.Array)
if err != nil {
return err
}
v.Set(reflect.ValueOf(value))
return nil
}
// Grab original size to use if needed for sub arrays
ogSize := size
// If the value has a len and is less than the size
// use that instead of the requested size
elemLen := v.Len()
if elemLen == 0 && size == -1 {
size = number(f, 1, 10)
} else if elemLen != 0 && (size == -1 || elemLen < size) {
size = elemLen
}
// Get the element type
elemT := t.Elem()
// Loop through the elements length and set based upon the index
for i := 0; i < size; i++ {
nv := reflect.New(elemT)
err := r(f, elemT, nv.Elem(), tag, ogSize)
if err != nil {
return err
}
// If values are already set fill them up, otherwise append
if elemLen != 0 {
v.Index(i).Set(reflect.Indirect(nv))
} else {
v.Set(reflect.Append(reflect.Indirect(v), reflect.Indirect(nv)))
}
}
return nil
}
func rMap(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error {
// If you cant even set it dont even try
if !v.CanSet() {
return errors.New("cannot set slice")
}
// Check if tag exists, if so run custom function
if tag != "" {
return rCustom(f, t, v, tag)
} else if size > 0 {
// NOOP
} else if isFakeable(t) {
value, err := callFake(f, v, reflect.Map)
if err != nil {
return err
}
v.Set(reflect.ValueOf(value))
return nil
}
// Set a size
newSize := size
if newSize == -1 {
newSize = number(f, 1, 10)
}
// Create new map based upon map key value type
mapType := reflect.MapOf(t.Key(), t.Elem())
newMap := reflect.MakeMap(mapType)
for i := 0; i < newSize; i++ {
// Create new key
mapIndex := reflect.New(t.Key())
err := r(f, t.Key(), mapIndex.Elem(), "", -1)
if err != nil {
return err
}
// Create new value
mapValue := reflect.New(t.Elem())
err = r(f, t.Elem(), mapValue.Elem(), "", -1)
if err != nil {
return err
}
newMap.SetMapIndex(mapIndex.Elem(), mapValue.Elem())
}
// Set newMap into struct field
if t.Kind() == reflect.Ptr {
v.Set(newMap.Elem())
} else {
v.Set(newMap)
}
return nil
}
func rString(f *Faker, t reflect.Type, v reflect.Value, tag string) error {
if tag != "" {
genStr, err := generate(f, tag)
if err != nil {
return err
}
v.SetString(genStr)
} else if isFakeable(t) {
value, err := callFake(f, v, reflect.String)
if err != nil {
return err
}
valueStr, ok := value.(string)
if !ok {
return errors.New("call to Fake method did not return a string")
}
v.SetString(valueStr)
} else {
genStr, err := generate(f, strings.Repeat("?", number(f, 4, 10)))
if err != nil {
return err
}
v.SetString(genStr)
}
return nil
}
func rInt(f *Faker, t reflect.Type, v reflect.Value, tag string) error {
if tag != "" {
genStr, err := generate(f, tag)
if err != nil {
return err
}
i, err := strconv.ParseInt(genStr, 10, 64)
if err != nil {
return err
}
v.SetInt(i)
} else if isFakeable(t) {
value, err := callFake(f, v, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64)
if err != nil {
return err
}
switch i := value.(type) {
case int:
v.SetInt(int64(i))
case int8:
v.SetInt(int64(i))
case int16:
v.SetInt(int64(i))
case int32:
v.SetInt(int64(i))
case int64:
v.SetInt(int64(i))
default:
return errors.New("call to Fake method did not return an integer")
}
} else {
// If no tag or error converting to int, set with random value
switch t.Kind() {
case reflect.Int:
v.SetInt(int64Func(f))
case reflect.Int8:
v.SetInt(int64(int8Func(f)))
case reflect.Int16:
v.SetInt(int64(int16Func(f)))
case reflect.Int32:
v.SetInt(int64(int32Func(f)))
case reflect.Int64:
v.SetInt(int64Func(f))
}
}
return nil
}
func rUint(f *Faker, t reflect.Type, v reflect.Value, tag string) error {
if tag != "" {
genStr, err := generate(f, tag)
if err != nil {
return err
}
u, err := strconv.ParseUint(genStr, 10, 64)
if err != nil {
return err
}
v.SetUint(u)
} else if isFakeable(t) {
value, err := callFake(f, v, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64)
if err != nil {
return err
}
switch i := value.(type) {
case uint:
v.SetUint(uint64(i))
case uint8:
v.SetUint(uint64(i))
case uint16:
v.SetUint(uint64(i))
case uint32:
v.SetUint(uint64(i))
case uint64:
v.SetUint(uint64(i))
default:
return errors.New("call to Fake method did not return an unsigned integer")
}
} else {
// If no tag or error converting to uint, set with random value
switch t.Kind() {
case reflect.Uint:
v.SetUint(f.Uint64())
case reflect.Uint8:
v.SetUint(uint64(uint8Func(f)))
case reflect.Uint16:
v.SetUint(uint64(uint16Func(f)))
case reflect.Uint32:
v.SetUint(uint64(uint32Func(f)))
case reflect.Uint64:
v.SetUint(f.Uint64())
}
}
return nil
}
func rFloat(f *Faker, t reflect.Type, v reflect.Value, tag string) error {
if tag != "" {
genStr, err := generate(f, tag)
if err != nil {
return err
}
f, err := strconv.ParseFloat(genStr, 64)
if err != nil {
return err
}
v.SetFloat(f)
} else if isFakeable(t) {
value, err := callFake(f, v, reflect.Float32, reflect.Float64)
if err != nil {
return err
}
switch i := value.(type) {
case float32:
v.SetFloat(float64(i))
case float64:
v.SetFloat(float64(i))
default:
return errors.New("call to Fake method did not return a float")
}
} else {
// If no tag or error converting to float, set with random value
switch t.Kind() {
case reflect.Float64:
v.SetFloat(float64Func(f))
case reflect.Float32:
v.SetFloat(float64(float32Func(f)))
}
}
return nil
}
func rBool(f *Faker, t reflect.Type, v reflect.Value, tag string) error {
if tag != "" {
genStr, err := generate(f, tag)
if err != nil {
return err
}
b, err := strconv.ParseBool(genStr)
if err != nil {
return err
}
v.SetBool(b)
} else if isFakeable(t) {
value, err := callFake(f, v, reflect.Bool)
if err != nil {
return err
}
switch i := value.(type) {
case bool:
v.SetBool(bool(i))
default:
return errors.New("call to Fake method did not return a boolean")
}
} else {
// If no tag or error converting to boolean, set with random value
v.SetBool(boolFunc(f))
}
return nil
}
// rTime will set a time.Time field the best it can from either the default date tag or from the generate tag
func rTime(f *Faker, t reflect.StructField, v reflect.Value, tag string) error {
if tag != "" {
// Generate time
timeOutput, err := generate(f, tag)
if err != nil {
return err
}
// Check to see if timeOutput has monotonic clock reading
// if so, remove it. This is because time.Parse() does not
// support parsing the monotonic clock reading
if strings.Contains(timeOutput, " m=") {
timeOutput = strings.Split(timeOutput, " m=")[0]
}
// Check to see if they are passing in a format to parse the time
timeFormat, timeFormatOK := t.Tag.Lookup("format")
if timeFormatOK {
timeFormat = javaDateFormatToGolangDateFormat(timeFormat)
} else {
// If tag == "{date}" use time.RFC3339
// They are attempting to use the default date lookup
if tag == "{date}" {
timeFormat = time.RFC3339
} else {
// Default format of time.Now().String()
timeFormat = "2006-01-02 15:04:05.999999999 -0700 MST"
}
}
// If output is larger than format cut the output
// This helps us avoid errors from time.Parse
if len(timeOutput) > len(timeFormat) {
timeOutput = timeOutput[:len(timeFormat)]
}
// Attempt to parse the time
timeStruct, err := time.Parse(timeFormat, timeOutput)
if err != nil {
return err
}
v.Set(reflect.ValueOf(timeStruct))
return nil
}
v.Set(reflect.ValueOf(date(f)))
return nil
}