Skip to content
This repository has been archived by the owner on Dec 8, 2022. It is now read-only.

feat: oneof support for some pointer types. #162

Merged
merged 2 commits into from
Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions example_with_tags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ type SomeStructWithTags struct {
NumU16 uint16 `faker:"oneof: 13, 14"`
NumU8 uint8 `faker:"oneof: 15, 16"`
NumU uint `faker:"oneof: 17, 18"`
PtrNumU *uint `faker:"oneof: 19, 20"`
}

func Example_withTags() {
Expand Down Expand Up @@ -132,6 +133,7 @@ func Example_withTags() {
NumU16: 13
NumU8: 15
NumU: 17
PtrNumU: 19
Skip:
}
*/
Expand Down
7 changes: 6 additions & 1 deletion faker.go
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,12 @@ func setDataWithTag(v reflect.Value, tag string) error {
switch v.Kind() {
case reflect.Ptr:
if _, exist := mapperTag[tag]; !exist {
return fmt.Errorf(ErrTagNotSupported, tag)
newv := reflect.New(v.Type().Elem())
if err := setDataWithTag(newv, tag); err != nil {
return err
}
v.Set(newv)
return nil
}
if _, def := defaultTag[tag]; !def {
res, err := mapperTag[tag](v)
Expand Down
33 changes: 33 additions & 0 deletions faker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1657,6 +1657,39 @@ func TestOneOfTag__GoodInputs(t *testing.T) {
}
})

type CustomTypeLotsOfPtrNumbers struct {
Age1 *int64 `faker:"oneof: 1, 2"`
Age2 *int32 `faker:"oneof: 3, 5"`
Age3 *int16 `faker:"oneof: 8, 3"`
Age4 *int8 `faker:"oneof: 7, 9"`
Age5 *int `faker:"oneof: 6, 2"`
Age6 *uint64 `faker:"oneof: 2, 4"`
Age7 *uint32 `faker:"oneof: 6, 8"`
Age8 *uint16 `faker:"oneof: 9, 6"`
Age9 *uint8 `faker:"oneof: 3, 5"`
Age0 *uint `faker:"oneof: 1, 4"`
}

t.Run("Should support all the ptr number types", func(t *testing.T) {
a := CustomTypeLotsOfPtrNumbers{}
err := FakeData(&a)
if err != nil {
t.Errorf("expected no error but got %v", err)
}
val := reflect.ValueOf(a)

for i := 0; i < val.Type().NumField(); i++ {
if val.Field(i).IsZero() {
t.Errorf("%s: expected non-nil but got %v", val.Type().Field(i).Name, val.Field(i).Interface())
continue
}
strVal := fmt.Sprintf("%d", val.Field(i).Elem().Interface())
if len(strVal) != 1 {
t.Errorf("%s: expected [0,9] but got %s", val.Type().Field(i).Name, strVal)
}
}

})
}

func TestOneOfTag__BadInputsForFloats(t *testing.T) {
Expand Down