Skip to content

Commit

Permalink
fix: tests and fix for faking data for slice of structs with slice_le…
Browse files Browse the repository at this point in the history
…n specified (#19)

* tests and fix for faking data for slice of structs

* add city for 3 Southerberry Drive address
  • Loading branch information
cwinters8 authored Feb 7, 2024
1 parent 29e74ae commit 3032a45
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
12 changes: 12 additions & 0 deletions faker.go
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,18 @@ func userDefinedArray(v reflect.Value, tag string, opt options.Options) error {
tag = findSliceLenReg.ReplaceAllString(tag, "")
array := reflect.MakeSlice(v.Type(), sliceLen, sliceLen)
for i := 0; i < array.Len(); i++ {
k := v.Type().Elem().Kind()
if k == reflect.Pointer || k == reflect.Struct {
res, err := getFakedValue(array.Index(i).Interface(), &opt)
if err != nil {
return err
}
if res.Kind() == reflect.Invalid {
return fmt.Errorf("got invalid reflect value")
}
array.Index(i).Set(res)
continue
}
if tag == "" {
res, err := getValueWithNoTag(v.Type().Elem(), opt)
if err != nil {
Expand Down
33 changes: 33 additions & 0 deletions faker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,39 @@ func TestSliceLen(t *testing.T) {
}
}

func TestSliceOfStructPointersLen(t *testing.T) {
type Child struct {
ID int
Value string
}
type Parent struct {
Children []*Child `faker:"slice_len=3"`
}
var p Parent
if err := FakeData(&p); err != nil {
t.Fatalf("failed to generate fake data: %s", err.Error())
}
if len(p.Children) != 3 {
t.Errorf("wrong slice length based on slice_len tag, got %d, wanted 3", len(p.Children))
}
}
func TestSliceOfStructsLen(t *testing.T) {
type Child struct {
ID int
Value string
}
type Parent struct {
Children []Child `faker:"slice_len=5"`
}
var p Parent
if err := FakeData(&p); err != nil {
t.Fatalf("failed to generate fake data: %s", err.Error())
}
if len(p.Children) != 5 {
t.Errorf("wrong slice length based on slice_len tag, got %d, wanted 5", len(p.Children))
}
}

func TestWrongSliceLen(t *testing.T) {
type SomeStruct struct {
String []string `faker:"slice_len=bla"`
Expand Down
2 changes: 1 addition & 1 deletion misc/addresses-us-1000.min.json

Large diffs are not rendered by default.

0 comments on commit 3032a45

Please sign in to comment.