Skip to content

Commit 3032a45

Browse files
authored
fix: tests and fix for faking data for slice of structs with slice_len specified (#19)
* tests and fix for faking data for slice of structs * add city for 3 Southerberry Drive address
1 parent 29e74ae commit 3032a45

File tree

3 files changed

+46
-1
lines changed

3 files changed

+46
-1
lines changed

faker.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -880,6 +880,18 @@ func userDefinedArray(v reflect.Value, tag string, opt options.Options) error {
880880
tag = findSliceLenReg.ReplaceAllString(tag, "")
881881
array := reflect.MakeSlice(v.Type(), sliceLen, sliceLen)
882882
for i := 0; i < array.Len(); i++ {
883+
k := v.Type().Elem().Kind()
884+
if k == reflect.Pointer || k == reflect.Struct {
885+
res, err := getFakedValue(array.Index(i).Interface(), &opt)
886+
if err != nil {
887+
return err
888+
}
889+
if res.Kind() == reflect.Invalid {
890+
return fmt.Errorf("got invalid reflect value")
891+
}
892+
array.Index(i).Set(res)
893+
continue
894+
}
883895
if tag == "" {
884896
res, err := getValueWithNoTag(v.Type().Elem(), opt)
885897
if err != nil {

faker_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -786,6 +786,39 @@ func TestSliceLen(t *testing.T) {
786786
}
787787
}
788788

789+
func TestSliceOfStructPointersLen(t *testing.T) {
790+
type Child struct {
791+
ID int
792+
Value string
793+
}
794+
type Parent struct {
795+
Children []*Child `faker:"slice_len=3"`
796+
}
797+
var p Parent
798+
if err := FakeData(&p); err != nil {
799+
t.Fatalf("failed to generate fake data: %s", err.Error())
800+
}
801+
if len(p.Children) != 3 {
802+
t.Errorf("wrong slice length based on slice_len tag, got %d, wanted 3", len(p.Children))
803+
}
804+
}
805+
func TestSliceOfStructsLen(t *testing.T) {
806+
type Child struct {
807+
ID int
808+
Value string
809+
}
810+
type Parent struct {
811+
Children []Child `faker:"slice_len=5"`
812+
}
813+
var p Parent
814+
if err := FakeData(&p); err != nil {
815+
t.Fatalf("failed to generate fake data: %s", err.Error())
816+
}
817+
if len(p.Children) != 5 {
818+
t.Errorf("wrong slice length based on slice_len tag, got %d, wanted 5", len(p.Children))
819+
}
820+
}
821+
789822
func TestWrongSliceLen(t *testing.T) {
790823
type SomeStruct struct {
791824
String []string `faker:"slice_len=bla"`

misc/addresses-us-1000.min.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)