Skip to content

Commit

Permalink
fix: fake non_empty interface panic (#25)
Browse files Browse the repository at this point in the history
Co-authored-by: yangxu.09 <yangxu.09@bytedance.com>
  • Loading branch information
xuyang21 and yangxu.09 authored Jun 1, 2023
1 parent 5effebb commit 91fd09b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
15 changes: 11 additions & 4 deletions faker.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,9 @@ func FakeData(a interface{}, opt ...options.OptionFunc) error {
if err != nil {
return err
}

if finalValue.Kind() == reflect.Invalid {
return nil
}
rval.Elem().Set(finalValue.Elem().Convert(reflectType.Elem()))
return nil
}
Expand Down Expand Up @@ -383,7 +385,7 @@ func getFakedValue(a interface{}, opts *options.Options) (reflect.Value, error)
t := reflect.TypeOf(a)
if t == nil {
if opts.IgnoreInterface {
return reflect.New(reflect.TypeOf(reflect.Struct)), nil
return reflect.ValueOf(nil), nil
}
return reflect.Value{}, fmt.Errorf("interface{} not allowed")
}
Expand All @@ -409,6 +411,9 @@ func getFakedValue(a interface{}, opts *options.Options) (reflect.Value, error)
if err != nil {
return reflect.Value{}, err
}
if val.Kind() == reflect.Invalid {
return val, nil
}
v.Elem().Set(val.Convert(t.Elem()))
return v, nil
case reflect.Struct:
Expand Down Expand Up @@ -458,8 +463,10 @@ func getFakedValue(a interface{}, opts *options.Options) (reflect.Value, error)
if err != nil {
return reflect.Value{}, err
}
val = val.Convert(v.Field(i).Type())
v.Field(i).Set(val)
if val.Kind() != reflect.Invalid {
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 {
Expand Down
16 changes: 16 additions & 0 deletions faker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2456,3 +2456,19 @@ func TestFakeDate_ConcurrentSafe(t *testing.T) {
}
wg.Wait()
}

type StructWithInterface struct {
I Interface
}

type Interface interface {
test()
}

func TestNonEmptyInterface(t *testing.T) {
var s StructWithInterface
if err := FakeData(&s, options.WithIgnoreInterface(true)); err != nil {
t.Errorf("%+v", err)
t.FailNow()
}
}

0 comments on commit 91fd09b

Please sign in to comment.