This repository has been archived by the owner on Dec 8, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 148
/
faker.go
946 lines (866 loc) · 26.6 KB
/
faker.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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
package faker
// Faker is a simple fake data generator for your own struct.
// Save your time, and Fake your data for your testing now.
import (
"errors"
"fmt"
"math/rand"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/bxcodec/faker/v3/support/slice"
)
var (
mu = &sync.Mutex{}
// Sets nil if the value type is struct or map and the size of it equals to zero.
shouldSetNil = false
//Sets random integer generation to zero for slice and maps
testRandZero = false
//Sets the default number of string when it is created randomly.
randomStringLen = 25
//Sets the boundary for random value generation. Boundaries can not exceed integer(4 byte...)
nBoundary = numberBoundary{start: 0, end: 100}
//Sets the random size for slices and maps.
randomSize = 100
// Sets the single fake data generator to generate unique values
generateUniqueValues = false
// Unique values are kept in memory so the generator retries if the value already exists
uniqueValues = map[string][]interface{}{}
lang = LangENG
)
type numberBoundary struct {
start int
end int
}
type langRuneBoundary struct {
start rune
end rune
}
// Language rune boundaries here
var (
// LangENG is for english language
LangENG = langRuneBoundary{65, 122}
// LangCHI is for chinese language
LangCHI = langRuneBoundary{19968, 40869}
// LangRUS is for russian language
LangRUS = langRuneBoundary{1025, 1105}
)
// Supported tags
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
maxRetry = 10000 // max number of retry for unique values
tagName = "faker"
keep = "keep"
unique = "unique"
ID = "uuid_digit"
HyphenatedID = "uuid_hyphenated"
EmailTag = "email"
MacAddressTag = "mac_address"
DomainNameTag = "domain_name"
UserNameTag = "username"
URLTag = "url"
IPV4Tag = "ipv4"
IPV6Tag = "ipv6"
PASSWORD = "password"
LATITUDE = "lat"
LONGITUDE = "long"
CreditCardNumber = "cc_number"
CreditCardType = "cc_type"
PhoneNumber = "phone_number"
TollFreeNumber = "toll_free_number"
E164PhoneNumberTag = "e_164_phone_number"
TitleMaleTag = "title_male"
TitleFemaleTag = "title_female"
FirstNameTag = "first_name"
FirstNameMaleTag = "first_name_male"
FirstNameFemaleTag = "first_name_female"
LastNameTag = "last_name"
NAME = "name"
UnixTimeTag = "unix_time"
DATE = "date"
TIME = "time"
MonthNameTag = "month_name"
YEAR = "year"
DayOfWeekTag = "day_of_week"
DayOfMonthTag = "day_of_month"
TIMESTAMP = "timestamp"
CENTURY = "century"
TIMEZONE = "timezone"
TimePeriodTag = "time_period"
WORD = "word"
SENTENCE = "sentence"
PARAGRAPH = "paragraph"
CurrencyTag = "currency"
AmountTag = "amount"
AmountWithCurrencyTag = "amount_with_currency"
SKIP = "-"
Length = "len"
Language = "lang"
BoundaryStart = "boundary_start"
BoundaryEnd = "boundary_end"
Equals = "="
comma = ","
)
var defaultTag = map[string]string{
EmailTag: EmailTag,
MacAddressTag: MacAddressTag,
DomainNameTag: DomainNameTag,
URLTag: URLTag,
UserNameTag: UserNameTag,
IPV4Tag: IPV4Tag,
IPV6Tag: IPV6Tag,
PASSWORD: PASSWORD,
CreditCardType: CreditCardType,
CreditCardNumber: CreditCardNumber,
LATITUDE: LATITUDE,
LONGITUDE: LONGITUDE,
PhoneNumber: PhoneNumber,
TollFreeNumber: TollFreeNumber,
E164PhoneNumberTag: E164PhoneNumberTag,
TitleMaleTag: TitleMaleTag,
TitleFemaleTag: TitleFemaleTag,
FirstNameTag: FirstNameTag,
FirstNameMaleTag: FirstNameMaleTag,
FirstNameFemaleTag: FirstNameFemaleTag,
LastNameTag: LastNameTag,
NAME: NAME,
UnixTimeTag: UnixTimeTag,
DATE: DATE,
TIME: TimeFormat,
MonthNameTag: MonthNameTag,
YEAR: YearFormat,
DayOfWeekTag: DayOfWeekTag,
DayOfMonthTag: DayOfMonthFormat,
TIMESTAMP: TIMESTAMP,
CENTURY: CENTURY,
TIMEZONE: TIMEZONE,
TimePeriodTag: TimePeriodFormat,
WORD: WORD,
SENTENCE: SENTENCE,
PARAGRAPH: PARAGRAPH,
CurrencyTag: CurrencyTag,
AmountTag: AmountTag,
AmountWithCurrencyTag: AmountWithCurrencyTag,
ID: ID,
HyphenatedID: HyphenatedID,
}
// TaggedFunction used as the standard layout function for tag providers in struct.
// This type also can be used for custom provider.
type TaggedFunction func(v reflect.Value) (interface{}, error)
var mapperTag = map[string]TaggedFunction{
EmailTag: GetNetworker().Email,
MacAddressTag: GetNetworker().MacAddress,
DomainNameTag: GetNetworker().DomainName,
URLTag: GetNetworker().URL,
UserNameTag: GetNetworker().UserName,
IPV4Tag: GetNetworker().IPv4,
IPV6Tag: GetNetworker().IPv6,
PASSWORD: GetNetworker().Password,
CreditCardType: GetPayment().CreditCardType,
CreditCardNumber: GetPayment().CreditCardNumber,
LATITUDE: GetAddress().Latitude,
LONGITUDE: GetAddress().Longitude,
PhoneNumber: GetPhoner().PhoneNumber,
TollFreeNumber: GetPhoner().TollFreePhoneNumber,
E164PhoneNumberTag: GetPhoner().E164PhoneNumber,
TitleMaleTag: GetPerson().TitleMale,
TitleFemaleTag: GetPerson().TitleFeMale,
FirstNameTag: GetPerson().FirstName,
FirstNameMaleTag: GetPerson().FirstNameMale,
FirstNameFemaleTag: GetPerson().FirstNameFemale,
LastNameTag: GetPerson().LastName,
NAME: GetPerson().Name,
UnixTimeTag: GetDateTimer().UnixTime,
DATE: GetDateTimer().Date,
TIME: GetDateTimer().Time,
MonthNameTag: GetDateTimer().MonthName,
YEAR: GetDateTimer().Year,
DayOfWeekTag: GetDateTimer().DayOfWeek,
DayOfMonthTag: GetDateTimer().DayOfMonth,
TIMESTAMP: GetDateTimer().Timestamp,
CENTURY: GetDateTimer().Century,
TIMEZONE: GetDateTimer().TimeZone,
TimePeriodTag: GetDateTimer().TimePeriod,
WORD: GetLorem().Word,
SENTENCE: GetLorem().Sentence,
PARAGRAPH: GetLorem().Paragraph,
CurrencyTag: GetPrice().Currency,
AmountTag: GetPrice().Amount,
AmountWithCurrencyTag: GetPrice().AmountWithCurrency,
ID: GetIdentifier().Digit,
HyphenatedID: GetIdentifier().Hyphenated,
}
// Generic Error Messages for tags
// ErrUnsupportedKindPtr: Error when get fake from ptr
// ErrUnsupportedKind: Error on passing unsupported kind
// ErrValueNotPtr: Error when value is not pointer
// ErrTagNotSupported: Error when tag is not supported
// ErrTagAlreadyExists: Error when tag exists and call AddProvider
// ErrMoreArguments: Error on passing more arguments
// ErrNotSupportedPointer: Error when passing unsupported pointer
var (
ErrUnsupportedKindPtr = "Unsupported kind: %s Change Without using * (pointer) in Field of %s"
ErrUnsupportedKind = "Unsupported kind: %s"
ErrValueNotPtr = "Not a pointer value"
ErrTagNotSupported = "Tag unsupported: %s"
ErrTagAlreadyExists = "Tag exists"
ErrMoreArguments = "Passed more arguments than is possible : (%d)"
ErrNotSupportedPointer = "Use sample:=new(%s)\n faker.FakeData(sample) instead"
ErrSmallerThanZero = "Size:%d is smaller than zero."
ErrSmallerThanOne = "Size:%d is smaller than one."
ErrUniqueFailure = "Failed to generate a unique value for field \"%s\""
ErrStartValueBiggerThanEnd = "Start value can not be bigger than end value."
ErrWrongFormattedTag = "Tag \"%s\" is not written properly"
ErrUnknownType = "Unknown Type"
ErrNotSupportedTypeForTag = "Type is not supported by tag."
)
// Compiled regexp
var (
findLangReg *regexp.Regexp
findLenReg *regexp.Regexp
)
func init() {
rand.Seed(time.Now().UnixNano())
findLangReg, _ = regexp.Compile("lang=[a-z]{3}")
findLenReg, _ = regexp.Compile(`len=\d+`)
}
// ResetUnique is used to forget generated unique values.
// Call this when you're done generating a dataset.
func ResetUnique() {
uniqueValues = map[string][]interface{}{}
}
// SetGenerateUniqueValues allows to set the single fake data generator functions to generate unique data.
func SetGenerateUniqueValues(unique bool) {
generateUniqueValues = unique
}
// SetNilIfLenIsZero allows to set nil for the slice and maps, if size is 0.
func SetNilIfLenIsZero(setNil bool) {
shouldSetNil = setNil
}
// SetRandomStringLength sets a length for random string generation
func SetRandomStringLength(size int) error {
if size < 0 {
return fmt.Errorf(ErrSmallerThanZero, size)
}
randomStringLen = size
return nil
}
// SetStringLang sets language of random string generation (LangENG, LangCHI, LangRUS)
func SetStringLang(l langRuneBoundary) {
lang = l
}
// SetRandomMapAndSliceSize sets the size for maps and slices for random generation.
func SetRandomMapAndSliceSize(size int) error {
if size < 1 {
return fmt.Errorf(ErrSmallerThanOne, size)
}
randomSize = size
return nil
}
// SetRandomNumberBoundaries sets boundary for random number generation
func SetRandomNumberBoundaries(start, end int) error {
if start > end {
return errors.New(ErrStartValueBiggerThanEnd)
}
nBoundary = numberBoundary{start: start, end: end}
return nil
}
// FakeData is the main function. Will generate a fake data based on your struct. You can use this for automation testing, or anything that need automated data.
// You don't need to Create your own data for your testing.
func FakeData(a interface{}) error {
reflectType := reflect.TypeOf(a)
if reflectType.Kind() != reflect.Ptr {
return errors.New(ErrValueNotPtr)
}
if reflect.ValueOf(a).IsNil() {
return fmt.Errorf(ErrNotSupportedPointer, reflectType.Elem().String())
}
rval := reflect.ValueOf(a)
finalValue, err := getValue(a)
if err != nil {
return err
}
rval.Elem().Set(finalValue.Elem().Convert(reflectType.Elem()))
return nil
}
// AddProvider extend faker with tag to generate fake data with specified custom algorithm
// Example:
// type Gondoruwo struct {
// Name string
// Locatadata int
// }
//
// type Sample struct {
// ID int64 `faker:"customIdFaker"`
// Gondoruwo Gondoruwo `faker:"gondoruwo"`
// Danger string `faker:"danger"`
// }
//
// func CustomGenerator() {
// // explicit
// faker.AddProvider("customIdFaker", func(v reflect.Value) (interface{}, error) {
// return int64(43), nil
// })
// // functional
// faker.AddProvider("danger", func() faker.TaggedFunction {
// return func(v reflect.Value) (interface{}, error) {
// return "danger-ranger", nil
// }
// }())
// faker.AddProvider("gondoruwo", func(v reflect.Value) (interface{}, error) {
// obj := Gondoruwo{
// Name: "Power",
// Locatadata: 324,
// }
// return obj, nil
// })
// }
//
// func main() {
// CustomGenerator()
// var sample Sample
// faker.FakeData(&sample)
// fmt.Printf("%+v", sample)
// }
//
// Will print
// {ID:43 Gondoruwo:{Name:Power Locatadata:324} Danger:danger-ranger}
// Notes: when using a custom provider make sure to return the same type as the field
func AddProvider(tag string, provider TaggedFunction) error {
if _, ok := mapperTag[tag]; ok {
return errors.New(ErrTagAlreadyExists)
}
mapperTag[tag] = provider
return nil
}
func getValue(a interface{}) (reflect.Value, error) {
t := reflect.TypeOf(a)
if t == nil {
return reflect.Value{}, fmt.Errorf("interface{} not allowed")
}
k := t.Kind()
switch k {
case reflect.Ptr:
v := reflect.New(t.Elem())
var val reflect.Value
var err error
if a != reflect.Zero(reflect.TypeOf(a)).Interface() {
val, err = getValue(reflect.ValueOf(a).Elem().Interface())
if err != nil {
return reflect.Value{}, err
}
} else {
val, err = getValue(v.Elem().Interface())
if err != nil {
return reflect.Value{}, err
}
}
v.Elem().Set(val.Convert(t.Elem()))
return v, nil
case reflect.Struct:
switch t.String() {
case "time.Time":
ft := time.Now().Add(time.Duration(rand.Int63()))
return reflect.ValueOf(ft), nil
default:
originalDataVal := reflect.ValueOf(a)
v := reflect.New(t).Elem()
retry := 0 // error if cannot generate unique value after maxRetry tries
for i := 0; i < v.NumField(); i++ {
if !v.Field(i).CanSet() {
continue // to avoid panic to set on unexported field in struct
}
tags := decodeTags(t, i)
switch {
case tags.keepOriginal:
zero, err := isZero(reflect.ValueOf(a).Field(i))
if err != nil {
return reflect.Value{}, err
}
if zero {
err := setDataWithTag(v.Field(i).Addr(), tags.fieldType)
if err != nil {
return reflect.Value{}, err
}
continue
}
v.Field(i).Set(reflect.ValueOf(a).Field(i))
case tags.fieldType == "":
val, err := getValue(v.Field(i).Interface())
if err != nil {
return reflect.Value{}, err
}
val = val.Convert(v.Field(i).Type())
v.Field(i).Set(val)
case tags.fieldType == SKIP:
item := originalDataVal.Field(i).Interface()
if v.CanSet() && item != nil {
v.Field(i).Set(reflect.ValueOf(item))
}
default:
err := setDataWithTag(v.Field(i).Addr(), tags.fieldType)
if err != nil {
return reflect.Value{}, err
}
}
if tags.unique {
if retry >= maxRetry {
return reflect.Value{}, fmt.Errorf(ErrUniqueFailure, reflect.TypeOf(a).Field(i).Name)
}
value := v.Field(i).Interface()
if slice.ContainsValue(uniqueValues[tags.fieldType], value) { // Retry if unique value already found
i--
retry++
continue
}
retry = 0
uniqueValues[tags.fieldType] = append(uniqueValues[tags.fieldType], value)
} else {
retry = 0
}
}
return v, nil
}
case reflect.String:
res := randomString(randomStringLen, &lang)
return reflect.ValueOf(res), nil
case reflect.Array, reflect.Slice:
len := randomSliceAndMapSize()
if shouldSetNil && len == 0 {
return reflect.Zero(t), nil
}
v := reflect.MakeSlice(t, len, len)
for i := 0; i < v.Len(); i++ {
val, err := getValue(v.Index(i).Interface())
if err != nil {
return reflect.Value{}, err
}
val = val.Convert(v.Index(i).Type())
v.Index(i).Set(val)
}
return v, nil
case reflect.Int:
return reflect.ValueOf(randomInteger()), nil
case reflect.Int8:
return reflect.ValueOf(int8(randomInteger())), nil
case reflect.Int16:
return reflect.ValueOf(int16(randomInteger())), nil
case reflect.Int32:
return reflect.ValueOf(int32(randomInteger())), nil
case reflect.Int64:
return reflect.ValueOf(int64(randomInteger())), nil
case reflect.Float32:
return reflect.ValueOf(rand.Float32()), nil
case reflect.Float64:
return reflect.ValueOf(rand.Float64()), nil
case reflect.Bool:
val := rand.Intn(2) > 0
return reflect.ValueOf(val), nil
case reflect.Uint:
return reflect.ValueOf(uint(randomInteger())), nil
case reflect.Uint8:
return reflect.ValueOf(uint8(randomInteger())), nil
case reflect.Uint16:
return reflect.ValueOf(uint16(randomInteger())), nil
case reflect.Uint32:
return reflect.ValueOf(uint32(randomInteger())), nil
case reflect.Uint64:
return reflect.ValueOf(uint64(randomInteger())), nil
case reflect.Map:
len := randomSliceAndMapSize()
if shouldSetNil && len == 0 {
return reflect.Zero(t), nil
}
v := reflect.MakeMap(t)
for i := 0; i < len; i++ {
keyInstance := reflect.New(t.Key()).Elem().Interface()
key, err := getValue(keyInstance)
if err != nil {
return reflect.Value{}, err
}
valueInstance := reflect.New(t.Elem()).Elem().Interface()
val, err := getValue(valueInstance)
if err != nil {
return reflect.Value{}, err
}
v.SetMapIndex(key, val)
}
return v, nil
default:
err := fmt.Errorf("no support for kind %+v", t)
return reflect.Value{}, err
}
}
func isZero(field reflect.Value) (bool, error) {
if field.Kind() == reflect.Map {
return field.Len() == 0, nil
}
for _, kind := range []reflect.Kind{reflect.Struct, reflect.Slice, reflect.Array} {
if kind == field.Kind() {
return false, fmt.Errorf("keep not allowed on struct")
}
}
return reflect.Zero(field.Type()).Interface() == field.Interface(), nil
}
func decodeTags(typ reflect.Type, i int) structTag {
tags := strings.Split(typ.Field(i).Tag.Get(tagName), ",")
keepOriginal := false
uni := false
res := make([]string, 0)
for _, tag := range tags {
if tag == keep {
keepOriginal = true
continue
} else if tag == unique {
uni = true
continue
}
res = append(res, tag)
}
return structTag{
fieldType: strings.Join(res, ","),
unique: uni,
keepOriginal: keepOriginal,
}
}
type structTag struct {
fieldType string
unique bool
keepOriginal bool
}
func setDataWithTag(v reflect.Value, tag string) error {
if v.Kind() != reflect.Ptr {
return errors.New(ErrValueNotPtr)
}
v = reflect.Indirect(v)
switch v.Kind() {
case reflect.Ptr:
if _, exist := mapperTag[tag]; !exist {
return fmt.Errorf(ErrTagNotSupported, tag)
}
if _, def := defaultTag[tag]; !def {
res, err := mapperTag[tag](v)
if err != nil {
return err
}
v.Set(reflect.ValueOf(res))
return nil
}
t := v.Type()
newv := reflect.New(t.Elem())
res, err := mapperTag[tag](newv.Elem())
if err != nil {
return err
}
rval := reflect.ValueOf(res)
newv.Elem().Set(rval)
v.Set(newv)
return nil
case reflect.String:
return userDefinedString(v, tag)
case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Uint, reflect.Uint8,
reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
return userDefinedNumber(v, tag)
case reflect.Slice, reflect.Array:
return userDefinedArray(v, tag)
case reflect.Map:
return userDefinedMap(v, tag)
default:
if _, exist := mapperTag[tag]; !exist {
return fmt.Errorf(ErrTagNotSupported, tag)
}
res, err := mapperTag[tag](v)
if err != nil {
return err
}
v.Set(reflect.ValueOf(res))
}
return nil
}
func userDefinedMap(v reflect.Value, tag string) error {
if tagFunc, ok := mapperTag[tag]; ok {
res, err := tagFunc(v)
if err != nil {
return err
}
v.Set(reflect.ValueOf(res))
return nil
}
len := randomSliceAndMapSize()
if shouldSetNil && len == 0 {
v.Set(reflect.Zero(v.Type()))
return nil
}
definedMap := reflect.MakeMap(v.Type())
for i := 0; i < len; i++ {
key, err := getValueWithTag(v.Type().Key(), tag)
if err != nil {
return err
}
val, err := getValueWithTag(v.Type().Elem(), tag)
if err != nil {
return err
}
definedMap.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(val))
}
v.Set(definedMap)
return nil
}
func getValueWithTag(t reflect.Type, tag string) (interface{}, error) {
switch t.Kind() {
case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Uint, reflect.Uint8,
reflect.Uint16, reflect.Uint32, reflect.Uint64:
res, err := extractNumberFromTag(tag, t)
if err != nil {
return nil, err
}
return res, nil
case reflect.String:
res, err := extractStringFromTag(tag)
if err != nil {
return nil, err
}
return res, nil
default:
return 0, errors.New(ErrUnknownType)
}
}
func userDefinedArray(v reflect.Value, tag string) error {
len := randomSliceAndMapSize()
if shouldSetNil && len == 0 {
v.Set(reflect.Zero(v.Type()))
return nil
}
array := reflect.MakeSlice(v.Type(), len, len)
for i := 0; i < len; i++ {
res, err := getValueWithTag(v.Type().Elem(), tag)
if err != nil {
return err
}
array.Index(i).Set(reflect.ValueOf(res))
}
v.Set(array)
return nil
}
func userDefinedString(v reflect.Value, tag string) error {
var res interface{}
var err error
if tagFunc, ok := mapperTag[tag]; ok {
res, err = tagFunc(v)
if err != nil {
return err
}
} else {
res, err = extractStringFromTag(tag)
if err != nil {
return err
}
}
if res == nil {
return fmt.Errorf(ErrTagNotSupported, tag)
}
val, _ := res.(string)
v.SetString(val)
return nil
}
func userDefinedNumber(v reflect.Value, tag string) error {
var res interface{}
var err error
if tagFunc, ok := mapperTag[tag]; ok {
res, err = tagFunc(v)
if err != nil {
return err
}
} else {
res, err = extractNumberFromTag(tag, v.Type())
if err != nil {
return err
}
}
if res == nil {
return fmt.Errorf(ErrTagNotSupported, tag)
}
v.Set(reflect.ValueOf(res))
return nil
}
func extractStringFromTag(tag string) (interface{}, error) {
var err error
strlen := randomStringLen
strlng := &lang
if !strings.Contains(tag, Length) && !strings.Contains(tag, Language) {
return nil, fmt.Errorf(ErrTagNotSupported, tag)
}
if strings.Contains(tag, Length) {
lenParts := strings.SplitN(findLenReg.FindString(tag), Equals, -1)
if len(lenParts) != 2 {
return nil, fmt.Errorf(ErrWrongFormattedTag, tag)
}
strlen, _ = strconv.Atoi(lenParts[1])
}
if strings.Contains(tag, Language) {
strlng, err = extractLangFromTag(tag)
if err != nil {
return nil, fmt.Errorf(ErrWrongFormattedTag, tag)
}
}
res := randomString(strlen, strlng)
return res, nil
}
func extractLangFromTag(tag string) (*langRuneBoundary, error) {
text := findLangReg.FindString(tag)
texts := strings.SplitN(text, Equals, -1)
if len(texts) != 2 {
return nil, fmt.Errorf(ErrWrongFormattedTag, text)
}
switch strings.ToLower(texts[1]) {
case "eng":
return &LangENG, nil
case "rus":
return &LangRUS, nil
case "chi":
return &LangCHI, nil
default:
return &LangENG, nil
}
}
func extractNumberFromTag(tag string, t reflect.Type) (interface{}, error) {
if !strings.Contains(tag, BoundaryStart) || !strings.Contains(tag, BoundaryEnd) {
return nil, fmt.Errorf(ErrTagNotSupported, tag)
}
valuesStr := strings.SplitN(tag, comma, -1)
if len(valuesStr) != 2 {
return nil, fmt.Errorf(ErrWrongFormattedTag, tag)
}
startBoundary, err := extractNumberFromText(valuesStr[0])
if err != nil {
return nil, err
}
endBoundary, err := extractNumberFromText(valuesStr[1])
if err != nil {
return nil, err
}
boundary := numberBoundary{start: startBoundary, end: endBoundary}
switch t.Kind() {
case reflect.Uint:
return uint(randomIntegerWithBoundary(boundary)), nil
case reflect.Uint8:
return uint8(randomIntegerWithBoundary(boundary)), nil
case reflect.Uint16:
return uint16(randomIntegerWithBoundary(boundary)), nil
case reflect.Uint32:
return uint32(randomIntegerWithBoundary(boundary)), nil
case reflect.Uint64:
return uint64(randomIntegerWithBoundary(boundary)), nil
case reflect.Int:
return randomIntegerWithBoundary(boundary), nil
case reflect.Int8:
return int8(randomIntegerWithBoundary(boundary)), nil
case reflect.Int16:
return int16(randomIntegerWithBoundary(boundary)), nil
case reflect.Int32:
return int32(randomIntegerWithBoundary(boundary)), nil
case reflect.Int64:
return int64(randomIntegerWithBoundary(boundary)), nil
default:
return nil, errors.New(ErrNotSupportedTypeForTag)
}
}
func extractNumberFromText(text string) (int, error) {
text = strings.TrimSpace(text)
texts := strings.SplitN(text, Equals, -1)
if len(texts) != 2 {
return 0, fmt.Errorf(ErrWrongFormattedTag, text)
}
return strconv.Atoi(texts[1])
}
func randomString(n int, lang *langRuneBoundary) string {
b := make([]rune, 0)
for i := 0; i < n; {
randRune := rune(rand.Intn(int(lang.end-lang.start)) + int(lang.start))
b = append(b, randRune)
i++
}
return string(b)
}
// randomIntegerWithBoundary returns a random integer between input start and end boundary. [start, end)
func randomIntegerWithBoundary(boundary numberBoundary) int {
return rand.Intn(boundary.end-boundary.start) + boundary.start
}
// randomInteger returns a random integer between start and end boundary. [start, end)
func randomInteger() int {
return rand.Intn(nBoundary.end-nBoundary.start) + nBoundary.start
}
// randomSliceAndMapSize returns a random integer between [0,randomSliceAndMapSize). If the testRandZero is set, returns 0
// Written for test purposes for shouldSetNil
func randomSliceAndMapSize() int {
if testRandZero {
return 0
}
return rand.Intn(randomSize)
}
func randomElementFromSliceString(s []string) string {
return s[rand.Int()%len(s)]
}
func randomStringNumber(n int) string {
b := make([]byte, n)
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(numberBytes) {
b[i] = numberBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// RandomInt Get three parameters , only first mandatory and the rest are optional
// If only set one parameter : This means the minimum number of digits and the total number
// If only set two parameters : First this is min digit and second max digit and the total number the difference between them
// If only three parameters: the third argument set Max count Digit
func RandomInt(parameters ...int) (p []int, err error) {
switch len(parameters) {
case 1:
minCount := parameters[0]
p = rand.Perm(minCount)
for i := range p {
p[i] += minCount
}
case 2:
minDigit, maxDigit := parameters[0], parameters[1]
p = rand.Perm(maxDigit - minDigit + 1)
for i := range p {
p[i] += minDigit
}
default:
err = fmt.Errorf(ErrMoreArguments, len(parameters))
}
return p, err
}
func generateUnique(dataType string, fn func() interface{}) (interface{}, error) {
for i := 0; i < maxRetry; i++ {
value := fn()
if !slice.ContainsValue(uniqueValues[dataType], value) { // Retry if unique value already found
uniqueValues[dataType] = append(uniqueValues[dataType], value)
return value, nil
}
}
return reflect.Value{}, fmt.Errorf(ErrUniqueFailure, dataType)
}
func singleFakeData(dataType string, fn func() interface{}) interface{} {
if generateUniqueValues {
v, err := generateUnique(dataType, fn)
if err != nil {
panic(err)
}
return v
}
return fn()
}