forked from bxcodec/faker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
faker_test.go
1998 lines (1738 loc) · 49.8 KB
/
faker_test.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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package faker
import (
"fmt"
"math/rand"
"reflect"
"strings"
"testing"
"time"
"unicode/utf8"
)
const (
someStructLen = 2
someStructBoundaryStart = 5
someStructBoundaryEnd = 10
someStructWithLenAndLangENG = 5
someStructWithLenAndLangCHI = 10
someStructWithLenAndLangRUS = 15
)
var (
langCorrectTagsMap = map[string]langRuneBoundary{"lang=eng": LangENG, "lang=chi": LangCHI, "lang=rus": LangRUS}
langUncorrectTags = [3]string{"lang=", "lang", "lng=eng"}
lenCorrectTags = [3]string{"len=4", "len=5", "len=10"}
lenUncorrectTags = [6]string{"len=b", "ln=10", "length=25", "lang=b", "ln=10", "lang=8d,,len=eng"}
sliceLenCorrectTags = [4]string{"slice_len=0", "slice_len=4", "slice_len=5", "slice_len=10"}
sliceLenIncorrectTags = [3]string{"slice_len=b", "slice_len=-1", "slice_len=-10"}
)
type SomeInt32 int32
type TArray [16]byte
type SomeStruct struct {
Inta int
Int8 int8
Int16 int16
Int32 int32
Int64 int64
Float32 float32
Float64 float64
UInta uint
UInt8 uint8
UInt16 uint16
UInt32 uint32
UInt64 uint64
Latitude float32 `faker:"lat"`
LATITUDE float64 `faker:"lat"`
Long float32 `faker:"long"`
LONG float64 `faker:"long"`
StringValue string
CreditCardType string `faker:"cc_type"`
CreditCardNumber string `faker:"cc_number"`
Email string `faker:"email"`
IPV4 string `faker:"ipv4"`
IPV6 string `faker:"ipv6"`
Bool bool
SString []string
SInt []int
SInt8 []int8
SInt16 []int16
SInt32 []int32
SInt64 []int64
SFloat32 []float32
SFloat64 []float64
SBool []bool
Struct AStruct
TArray TArray
Time time.Time
Stime []time.Time
Currency string `faker:"currency"`
Amount float64 `faker:"amount"`
AmountWithCurrency string `faker:"amount_with_currency"`
ID string `faker:"uuid_digit"`
HyphenatedID string `faker:"uuid_hyphenated"`
MapStringString map[string]string
MapStringStruct map[string]AStruct
MapStringStructPointer map[string]*AStruct
SomeInt32s []SomeInt32
}
type SomeStructWithLen struct {
Inta int `faker:"boundary_start=5, boundary_end=10"`
Int8 int8 `faker:"boundary_start=5, boundary_end=10"`
Int16 int16 `faker:"boundary_start=5, boundary_end=10"`
Int32 int32 `faker:"boundary_start=5, boundary_end=10"`
Int64 int64 `faker:"boundary_start=5, boundary_end=10"`
UInta uint `faker:"boundary_start=5, boundary_end=10"`
UInt8 uint8 `faker:"boundary_start=5, boundary_end=10"`
UInt16 uint16 `faker:"boundary_start=5, boundary_end=10"`
UInt32 uint32 `faker:"boundary_start=5, boundary_end=10"`
UInt64 uint64 `faker:"boundary_start=5, boundary_end=10"`
ASString []string `faker:"len=2"`
SString string `faker:"len=2"`
MSString map[string]string `faker:"len=2"`
MIint map[int]int `faker:"boundary_start=5, boundary_end=10"`
}
type SomeStructWithLang struct {
ValueENG string `faker:"lang=eng"`
ValueCHI string `faker:"lang=chi"`
ValueRUS string `faker:"lang=rus"`
ValueWithUndefinedLang string `faker:"lang=und"`
}
type SomeStructWithLenAndLang struct {
ValueENG string `faker:"len=5, lang=eng"`
ValueCHI string ` faker:"len=10, lang=chi"`
ValueRUS string ` faker:"len=15, lang=rus"`
}
func (s SomeStruct) String() string {
return fmt.Sprintf(`{
Inta: %v
Int8: %v
Int16: %v
Int32: %v
Int64: %v
Float32: %v
Float64: %v
UInta: %v
UInt8: %v
UInt16: %v
UInt32: %v
UInt64: %v
Latitude: %v
LATITUDE: %v
Long: %v
LONG: %v
StringValue: %v
CreditCardType: %v
CreditCardNumber: %v
Email: %v
IPV4: %v
IPV6: %v
Bool: %v
SString: %v
SInt: %v
SInt8: %v
SInt16: %v
SInt32: %v
SInt64: %v
SFloat32: %v
SFloat64:%v
SBool: %v
Struct: %v
Time: %v
Stime: %v
Currency: %v
Amount: %v
AmountWithCurrency: %v
ID: %v
HyphenatedID: %v
MapStringString: %v
MapStringStruct: %v
MapStringStructPointer: %v
}`, s.Inta, s.Int8, s.Int16, s.Int32,
s.Int64, s.Float32, s.Float64, s.UInta,
s.UInt8, s.UInt16, s.UInt32, s.UInt64,
s.Latitude, s.LATITUDE, s.Long, s.LONG,
s.StringValue, s.CreditCardType, s.CreditCardNumber,
s.Email, s.IPV4, s.IPV6, s.Bool, s.SString, s.SInt,
s.SInt8, s.SInt16, s.SInt32, s.SInt64, s.SFloat32, s.SFloat64,
s.SBool, s.Struct, s.Time, s.Stime, s.Currency, s.Amount,
s.AmountWithCurrency, s.ID, s.HyphenatedID, s.MapStringString,
s.MapStringStruct, s.MapStringStructPointer)
}
type AStruct struct {
Number int64
Height int64
AnotherStruct CStruct
}
type BStruct struct {
Image string
}
type CStruct struct {
BStruct
Name string
}
type TaggedStruct struct {
Latitude float32 `faker:"lat"`
Longitude float32 `faker:"long"`
CreditCardNumber string `faker:"cc_number"`
CreditCardType string `faker:"cc_type"`
Email string `faker:"email"`
DomainName string `faker:"domain_name"`
IPV4 string `faker:"ipv4"`
IPV6 string `faker:"ipv6"`
Password string `faker:"password"`
Jwt string `faker:"jwt"`
PhoneNumber string `faker:"phone_number"`
MacAddress string `faker:"mac_address"`
URL string `faker:"url"`
UserName string `faker:"username"`
TollFreeNumber string `faker:"toll_free_number"`
E164PhoneNumber string `faker:"e_164_phone_number"`
TitleMale string `faker:"title_male"`
TitleFemale string `faker:"title_female"`
FirstName string `faker:"first_name"`
FirstNameMale string `faker:"first_name_male"`
FirstNameFemale string `faker:"first_name_female"`
LastName string `faker:"last_name"`
Name string `faker:"name"`
UnixTime int64 `faker:"unix_time"`
Date string `faker:"date"`
Time string `faker:"time"`
MonthName string `faker:"month_name"`
Year string `faker:"year"`
DayOfWeek string `faker:"day_of_week"`
DayOfMonth string `faker:"day_of_month"`
Timestamp string `faker:"timestamp"`
Century string `faker:"century"`
TimeZone string `faker:"timezone"`
TimePeriod string `faker:"time_period"`
Word string `faker:"word"`
Sentence string `faker:"sentence"`
Paragraph string `faker:"paragraph"`
Currency string `faker:"currency"`
Amount float32 `faker:"amount"`
AmountWithCurrency string `faker:"amount_with_currency"`
ID string `faker:"uuid_digit"`
HyphenatedID string `faker:"uuid_hyphenated"`
}
func (t TaggedStruct) String() string {
return fmt.Sprintf(`{
Latitude: %f,
Long: %f,
CreditCardNumber: %s,
CreditCardType: %s,
Email: %s,
DomainName: %s,
IPV4: %s,
IPV6: %s,
Password: %s,
Jwt: %s,
PhoneNumber: %s,
MacAddress: %s,
URL: %s,
UserName: %s,
TollFreeNumber: %s,
E164PhoneNumber: %s,
TitleMale: %s,
TitleFemale: %s,
FirstName: %s,
FirstNameMale: %s,
FirstNameFemale: %s,
LastName: %s,
Name: %s,
UnixTime: %d,
Date: %s,
Time: %s,
MonthName: %s,
Year: %s,
DayOfWeek: %s,
DayOfMonth: %s,
Timestamp: %s,
Century: %s,
TimeZone: %s,
TimePeriod: %s,
Word: %s,
Sentence: %s,
Paragraph: %s,
Currency: %s,
Amount: %f,
AmountWithCurrency: %s,
HyphenatedID: %s,
ID: %s,
}`, t.Latitude, t.Longitude, t.CreditCardNumber,
t.CreditCardType, t.Email, t.DomainName, t.IPV4,
t.IPV6, t.Password, t.Jwt, t.PhoneNumber, t.MacAddress,
t.URL, t.UserName, t.TollFreeNumber,
t.E164PhoneNumber, t.TitleMale, t.TitleFemale,
t.FirstName, t.FirstNameMale, t.FirstNameFemale, t.LastName,
t.Name, t.UnixTime, t.Date,
t.Time, t.MonthName, t.Year, t.DayOfWeek,
t.DayOfMonth, t.Timestamp, t.Century, t.TimeZone,
t.TimePeriod, t.Word, t.Sentence, t.Paragraph,
t.Currency, t.Amount, t.AmountWithCurrency,
t.HyphenatedID, t.ID,
)
}
type NotTaggedStruct struct {
Latitude float32
Long float32
CreditCardType string
CreditCardNumber string
Email string
IPV4 string
IPV6 string
}
func TestFakerData(t *testing.T) {
var a SomeStruct
err := FakeData(&a, true)
if err != nil {
t.Error("Expected NoError")
}
fmt.Println("SomeStruct:")
fmt.Printf("%+v\n", a)
var b TaggedStruct
err = FakeData(&b, true)
if err != nil {
t.Error("Expected NoError, but Got Err: ", err)
}
fmt.Println("TaggedStruct:")
fmt.Printf("%+v\n", b)
// Example Result :
// {Int:8906957488773767119 Int8:6 Int16:14 Int32:391219825 Int64:2374447092794071106 String:poraKzAxVbWVkMkpcZCcWlYMd Bool:false SString:[MehdV aVotHsi] SInt:[528955241289647236 7620047312653801973 2774096449863851732] SInt8:[122 -92 -92] SInt16:[15679 -19444 -30246] SInt32:[1146660378 946021799 852909987] SInt64:[6079203475736033758 6913211867841842836 3269201978513619428] SFloat32:[0.019562425 0.12729558 0.36450312] SFloat64:[0.7825838989890364 0.9732903338838912 0.8316541489234004] SBool:[true false true] Struct:{Number:7693944638490551161 Height:6513508020379591917}}
}
func TestCustomFakerOnUnsupportedMapStringInterface(t *testing.T) {
type Sample struct {
Map map[string]interface{} `faker:"custom"`
}
err := AddProvider("custom", func(v reflect.Value) (interface{}, error) {
return map[string]interface{}{"foo": "bar"}, nil
})
if err != nil {
t.Error("Expected NoError, but Got Err", err)
}
var sample = new(Sample)
err = FakeData(sample, true)
if err != nil {
t.Error("Expected NoError, but Got Err:", err)
}
actual, ok := sample.Map["foo"]
if !ok {
t.Error("map key not set by custom faker")
}
if actual != "bar" {
t.Error("map value not set by custom faker")
}
}
func TestUnsuportedMapStringInterface(t *testing.T) {
type Sample struct {
Map map[string]interface{}
}
var sample = new(Sample)
if err := FakeData(sample, true); err == nil {
t.Error("Expected Error. But got nil")
}
}
func TestSetDataIfArgumentNotPtr(t *testing.T) {
temp := struct{}{}
if "Not a pointer value" != FakeData(temp, true).Error() {
t.Error("Expected in arguments not ptr")
}
}
func TestSetDataIfArgumentNotHaveReflect(t *testing.T) {
temp := func() {}
if err := FakeData(temp, true); err == nil {
t.Error("Exptected error but got nil")
}
}
func TestSetDataErrorDataParseTagStringType(t *testing.T) {
temp := &struct {
Test string `faker:"test"`
}{}
fmt.Printf("%+v ", temp)
if err := FakeData(temp, true); err == nil {
t.Error("Exptected error Unsupported tag, but got nil")
}
}
func TestSetDataErrorDataParseTagIntType(t *testing.T) {
temp := &struct {
Test int `faker:"test"`
}{}
if err := FakeData(temp, true); err == nil {
t.Error("Expected error Unsupported tag, but got nil")
}
}
func TestSetRandomStringLength(t *testing.T) {
someStruct := SomeStruct{}
if err := SetRandomStringLength(-1); err == nil {
t.Error("Random string len must not accept lower than 0 as a size")
}
strLen := 5
if err := SetRandomStringLength(strLen); err != nil {
t.Error("SetRandomStringLength method is corrupted.")
}
if err := FakeData(&someStruct, true); err != nil {
t.Error("Fake data generation has failed")
}
if utfLen(someStruct.StringValue) > strLen {
t.Error("SetRandomStringLength did not work.")
}
}
func TestSetStringLang(t *testing.T) {
someStruct := SomeStruct{}
SetStringLang(LangENG)
if err := FakeData(&someStruct, true); err != nil {
t.Error("Fake data generation has failed")
}
}
func TestSetRandomNumberBoundaries(t *testing.T) {
someStruct := SomeStruct{}
if err := SetRandomNumberBoundaries(10, 0); err == nil {
t.Error("Start must be smaller than end value")
}
boundary := numberBoundary{start: 10, end: 90}
if err := SetRandomNumberBoundaries(boundary.start, boundary.end); err != nil {
t.Error("SetRandomNumberBoundaries method is corrupted.")
}
if err := FakeData(&someStruct, true); err != nil {
t.Error("Fake data generation has failed")
}
if someStruct.Inta >= boundary.end || someStruct.Inta < boundary.start {
t.Errorf("%d must be between [%d,%d)", someStruct.Inta, boundary.start, boundary.end)
}
}
func TestSetRandomMapAndSliceSize(t *testing.T) {
someStruct := SomeStruct{}
if err := SetRandomMapAndSliceSize(-1); err == nil {
t.Error("Random Map and Slice must not accept lower than 0 as a size")
}
size := 5
if err := SetRandomMapAndSliceSize(size); err != nil {
t.Error("SetRandomMapAndSliceSize method is corrupted.")
}
if err := FakeData(&someStruct, true); err != nil {
t.Error("Fake data generation has failed")
}
if len(someStruct.MapStringStruct) > size || len(someStruct.SBool) > size {
t.Error("SetRandomMapAndSliceSize did not work.")
}
}
func TestSetNilIfLenIsZero(t *testing.T) {
someStruct := SomeStruct{}
SetNilIfLenIsZero(true)
testRandZero = true
if err := FakeData(&someStruct, true); err != nil {
t.Error("Fake data generation has failed")
}
if someStruct.MapStringString != nil && someStruct.MapStringStruct != nil &&
someStruct.MapStringStructPointer != nil {
t.Error("Map has to be nil")
}
if someStruct.Stime != nil && someStruct.SBool != nil {
t.Error("Array has to be nil")
}
testRandZero = false
}
func TestBoundaryAndLen(t *testing.T) {
iterate := 10
someStruct := SomeStructWithLen{}
for i := 0; i < iterate; i++ {
if err := FakeData(&someStruct, true); err != nil {
t.Error(err)
}
if err := validateRange(int(someStruct.Int8)); err != nil {
t.Error(err)
}
if err := validateRange(int(someStruct.Int16)); err != nil {
t.Error(err)
}
if err := validateRange(int(someStruct.Int32)); err != nil {
t.Error(err)
}
if err := validateRange(someStruct.Inta); err != nil {
t.Error(err)
}
if err := validateRange(int(someStruct.Int64)); err != nil {
t.Error(err)
}
if err := validateRange(int(someStruct.UInt8)); err != nil {
t.Error(err)
}
if err := validateRange(int(someStruct.UInt16)); err != nil {
t.Error(err)
}
if err := validateRange(int(someStruct.UInt32)); err != nil {
t.Error(err)
}
if err := validateRange(int(someStruct.UInta)); err != nil {
t.Error(err)
}
if err := validateRange(int(someStruct.UInt64)); err != nil {
t.Error(err)
}
if err := validateLen(someStruct.SString); err != nil {
t.Error(err)
}
for _, str := range someStruct.ASString {
if err := validateLen(str); err != nil {
t.Error(err)
}
}
for k, v := range someStruct.MSString {
if err := validateLen(k); err != nil {
t.Error(err)
}
if err := validateLen(v); err != nil {
t.Error(err)
}
}
for k, v := range someStruct.MIint {
if err := validateRange(k); err != nil {
t.Error(err)
}
if err := validateRange(v); err != nil {
t.Error(err)
}
}
}
}
func TestWrongBoundaryAndLen(t *testing.T) {
type SomeStruct struct {
Value int `faker:"boundary_start=a, boundary_end=b"`
}
s := SomeStruct{}
if err := FakeData(&s, true); err == nil {
t.Error(err)
}
}
func TestLang(t *testing.T) {
someStruct := SomeStructWithLang{}
if err := FakeData(&someStruct, true); err != nil {
t.Error("Fake data generation has failed")
}
var err error
err = isStringLangCorrect(someStruct.ValueENG, LangENG)
if err != nil {
t.Error(err.Error())
}
err = isStringLangCorrect(someStruct.ValueRUS, LangRUS)
if err != nil {
t.Error(err.Error())
}
err = isStringLangCorrect(someStruct.ValueCHI, LangCHI)
if err != nil {
t.Error(err.Error())
}
err = isStringLangCorrect(someStruct.ValueWithUndefinedLang, LangENG)
if err != nil {
t.Error(err.Error())
}
}
func TestLangWithWrongLang(t *testing.T) {
type SomeStruct struct {
String string `faker:"lang=undefined"`
}
s := SomeStruct{}
err := FakeData(&s, true)
if err != nil {
t.Error(err.Error())
}
}
func TestExtractingLangFromTag(t *testing.T) {
var err error
var lng *langRuneBoundary
for k, v := range langCorrectTagsMap {
if lng, err = extractLangFromTag(k); err != nil {
t.Error(err.Error())
}
if !reflect.DeepEqual(v, *lng) {
t.Errorf("Got %v lang rune range, but expected %v", lng, k)
}
}
for _, tag := range langUncorrectTags {
if _, err := extractLangFromTag(tag); err == nil {
t.Error(err.Error())
}
}
}
func TestExtractingStringFromTag(t *testing.T) {
for _, tag := range lenCorrectTags {
if _, err := extractStringFromTag(tag); err != nil {
t.Error(err.Error())
}
}
for _, tag := range lenUncorrectTags {
if _, err := extractStringFromTag(tag); err == nil {
t.Error(err.Error())
}
}
}
func TestSliceLen(t *testing.T) {
type SomeStruct struct {
String1 []string `faker:"slice_len=0"`
String2 []string `faker:"slice_len=5"`
String3 []string `faker:"slice_len=10"`
}
var someStruct SomeStruct
if err := FakeData(&someStruct, true); err != nil {
t.Error("Fake data generation has failed")
}
if len(someStruct.String1) != 0 {
t.Errorf("Wrong slice length based on slice_len tag, got %d, wanted 0", len(someStruct.String1))
}
if len(someStruct.String2) != 5 {
t.Errorf("Wrong slice length based on slice_len tag, got %d, wanted 5", len(someStruct.String2))
}
if len(someStruct.String3) != 10 {
t.Errorf("Wrong slice length based on slice_len tag, got %d, wanted 10", len(someStruct.String3))
}
}
func TestWrongSliceLen(t *testing.T) {
type SomeStruct struct {
String []string `faker:"slice_len=bla"`
}
s := SomeStruct{}
err := FakeData(&s, true)
if err == nil {
t.Error("An error should be thrown for the wrong slice_len")
}
}
func TestExtractingSliceLenFromTag(t *testing.T) {
for _, tag := range sliceLenCorrectTags {
if _, err := extractSliceLengthFromTag(tag, true); err != nil {
t.Error(err.Error())
}
}
for _, tag := range sliceLenIncorrectTags {
if _, err := extractSliceLengthFromTag(tag, true); err == nil {
t.Errorf("Extracting should have thrown an error for tag %s", tag)
}
}
}
func TestLangWithLen(t *testing.T) {
someStruct := SomeStructWithLenAndLang{}
if err := FakeData(&someStruct, true); err != nil {
t.Error("Fake data generation has failed")
}
var err error
err = isStringLangCorrect(someStruct.ValueENG, LangENG)
if err != nil {
t.Error(err.Error())
}
engLen := utfLen(someStruct.ValueENG)
if engLen != someStructWithLenAndLangENG {
t.Errorf("Got %d, but expected to be %d as a string len", engLen, someStructWithLenAndLangENG)
}
err = isStringLangCorrect(someStruct.ValueRUS, LangRUS)
if err != nil {
t.Error(err.Error())
}
chiLen := utfLen(someStruct.ValueCHI)
if chiLen != someStructWithLenAndLangCHI {
t.Errorf("Got %d, but expected to be %d as a string len", chiLen, someStructWithLenAndLangCHI)
}
err = isStringLangCorrect(someStruct.ValueCHI, LangCHI)
if err != nil {
t.Error(err.Error())
}
rusLen := utfLen(someStruct.ValueRUS)
if rusLen != someStructWithLenAndLangRUS {
t.Errorf("Got %d, but expected to be %d as a string len", rusLen, someStructWithLenAndLangRUS)
}
}
func isStringLangCorrect(value string, lang langRuneBoundary) error {
for i := 0; i < len(value); {
r, size := utf8.DecodeLastRuneInString(value[i:])
if r < lang.start || r > lang.end {
return fmt.Errorf("Symbol is not in selected alphabet: start: %d, end: %d", lang.start, lang.end)
}
i += size
}
return nil
}
func TestExtractNumberFromTagFail(t *testing.T) {
notSupportedTypeStruct := &struct {
Test float32 `faker:"boundary_start=5, boundary_end=10"`
}{}
if err := FakeData(¬SupportedTypeStruct, true); err == nil {
t.Error(err)
}
notSupportedStruct := &struct {
Test int `faker:"boundary_start=5"`
}{}
if err := FakeData(¬SupportedStruct, true); err == nil {
t.Error(err)
}
wrongFormatStruct := &struct {
Test int `faker:"boundary_start=5 boundary_end=10"`
}{}
if err := FakeData(&wrongFormatStruct, true); err == nil {
t.Error(err)
}
startExtractionStruct := &struct {
Test int `faker:"boundary_start=asda, boundary_end=10"`
}{}
if err := FakeData(&startExtractionStruct, true); err == nil {
t.Error(err)
}
endExtractionStruct := &struct {
Test int `faker:"boundary_start=5, boundary_end=asda"`
}{}
if err := FakeData(&endExtractionStruct, true); err == nil {
t.Error(err)
}
wrongSplitFormatStruct := &struct {
Test int `faker:"boundary_start5, boundary_end=10"`
}{}
if err := FakeData(&wrongSplitFormatStruct, true); err == nil {
t.Error(err)
}
}
func TestUserDefinedStringFail(t *testing.T) {
wrongFormatStruct := &struct {
Test string `faker:"len=asd"`
}{}
if err := FakeData(&wrongFormatStruct, true); err == nil {
t.Error(err)
}
}
func validateLen(value string) error {
if len(value) != someStructLen {
return fmt.Errorf("Got %d, but expected to be %d as a string len", len(value), someStructLen)
}
return nil
}
func validateRange(value int) error {
if value < someStructBoundaryStart || value > someStructBoundaryEnd {
return fmt.Errorf("%d must be between %d and %d", value, someStructBoundaryStart,
someStructBoundaryEnd)
}
return nil
}
func TestSetDataWithTagIfFirstArgumentNotPtr(t *testing.T) {
temp := struct{}{}
if setDataWithTag(reflect.ValueOf(temp), "", true).Error() != "Not a pointer value" {
t.Error("Expected in arguments not ptr")
}
}
func BenchmarkFakerDataNOTTagged(b *testing.B) {
for i := 0; i < b.N; i++ {
a := NotTaggedStruct{}
err := FakeData(&a, true)
if err != nil {
b.Fatal(err)
}
}
}
func BenchmarkFakerDataTagged(b *testing.B) {
for i := 0; i < b.N; i++ {
a := TaggedStruct{}
err := FakeData(&a, true)
if err != nil {
b.Fatal(err)
}
}
}
func TestRandomIntOnlyFirstParameter(t *testing.T) {
r := rand.Intn(100)
res, _ := RandomInt(r)
if len(res) != r {
t.Error("It is expected that the refund amount is equal to the argument (RandomInt)")
}
}
func TestRandomIntOnlySecondParameters(t *testing.T) {
first := rand.Intn(50)
second := rand.Intn(100) + first
res, _ := RandomInt(first, second)
if len(res) != (second - first + 1) {
t.Error("It is expected that the refund amount is equal to the argument (RandomInt)")
}
}
func TestRandomIntOnlyError(t *testing.T) {
arguments := []int{1, 3, 4, 5, 6}
_, err := RandomInt(arguments...)
if err == nil && err.Error() == fmt.Errorf(ErrMoreArguments, len(arguments)).Error() {
t.Error("Expected error from function RandomInt")
}
}
type PointerStructA struct {
SomeStruct *SomeStruct
}
type PointerStructB struct {
PointA PointerStructA
}
type PointerC struct {
TaggedStruct *TaggedStruct
}
func TestStructPointer(t *testing.T) {
a := new(PointerStructB)
err := FakeData(a, true)
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
fmt.Printf(" A value: %+v , Somestruct Value: %+v ", a, a)
tagged := new(PointerC)
err = FakeData(tagged, true)
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
fmt.Printf(" tagged value: %+v , TaggedStruct Value: %+v ", a, a.PointA.SomeStruct)
}
type CustomString string
type CustomInt int
type CustomMap map[string]string
type CustomPointerStruct PointerStructB
type CustomTypeStruct struct {
CustomString CustomString
CustomInt CustomInt
CustomMap CustomMap
CustomPointerStruct CustomPointerStruct
}
func TestCustomType(t *testing.T) {
a := new(CustomTypeStruct)
err := FakeData(a, true)
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
fmt.Printf(" A value: %+v , Somestruct Value: %+v ", a, a)
}
type SampleStruct struct {
name string
Age int
}
func (s SampleStruct) GetName() string {
return s.name
}
func TestUnexportedFieldStruct(t *testing.T) {
// This test is to ensure that the faker won't panic if trying to fake data on struct that has unexported field
a := new(SampleStruct)
err := FakeData(a, true)
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
fmt.Printf(" A value: %+v , SampleStruct Value: %+v ", a, a)
}
func TestPointerToCustomScalar(t *testing.T) {
// This test is to ensure that the faker won't panic if trying to fake data on struct that has field
a := new(CustomInt)
err := FakeData(a, true)
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
fmt.Printf(" A value: %+v , Custom scalar Value: %+v ", a, a)
}
type PointerCustomIntStruct struct {
V *CustomInt
}
func TestPointerToCustomIntStruct(t *testing.T) {
// This test is to ensure that the faker won't panic if trying to fake data on struct that has field
a := new(PointerCustomIntStruct)
err := FakeData(a, true)
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
fmt.Printf(" A value: %+v , PointerCustomIntStruct scalar Value: %+v ", a, a)
}
func TestSkipField(t *testing.T) {
// This test is to ensure that the faker won't fill field with tag skip
a := struct {
ID int
ShouldBeSkipped int `faker:"-"`
ShouldBeSkippedFilled int `faker:"-"`
}{}
a.ShouldBeSkippedFilled = 10
err := FakeData(&a, true)
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
if a.ShouldBeSkipped != 0 {
t.Error("Expected that field will be skipped")
}
if a.ShouldBeSkippedFilled != 10 {
t.Error("Expected that field will be skipped")
}
}
type Student struct {
Name string
School School `faker:"custom-school"`
}
type School struct {
Location string
}
func TestExtend(t *testing.T) {
// This test is to ensure that faker can be extended new providers
t.Run("test-string", func(t *testing.T) {
a := struct {
ID string `faker:"test"`
}{}
err := AddProvider("test", func(v reflect.Value) (interface{}, error) {
return "test", nil
})
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
err = FakeData(&a, true)
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
if a.ID != "test" {
t.Error("ID should be equal test value")
}
})
t.Run("test-struct", func(t *testing.T) {
a := &Student{}
err := AddProvider("custom-school", func(v reflect.Value) (interface{}, error) {
sch := School{
Location: "North Kindom",