Skip to content

Commit

Permalink
Merge pull request #43 from rerorero/fix-ptr-in-struct
Browse files Browse the repository at this point in the history
Avoid nil reference when struct has gen.PtrOf field
  • Loading branch information
untoldwind authored Oct 20, 2018
2 parents 0bdcb15 + 49faad1 commit 55d63c2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
6 changes: 5 additions & 1 deletion gen/struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ func Struct(rt reflect.Type, gens map[string]gopter.Gen) gopter.Gen {
if !ok {
return gopter.NewEmptyResult(rt)
}
result.Elem().FieldByIndex(field.Index).Set(reflect.ValueOf(value))
if value == nil {
result.Elem().FieldByIndex(field.Index).Set(reflect.Zero(field.Type))
} else {
result.Elem().FieldByIndex(field.Index).Set(reflect.ValueOf(value))
}
}

return gopter.NewGenResult(reflect.Indirect(result).Interface(), gopter.NoShrinker)
Expand Down
4 changes: 3 additions & 1 deletion gen/struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type testStruct struct {
Value2 int64
Value3 []int8
Value4 string
Value5 *string
}

func TestStruct(t *testing.T) {
Expand All @@ -21,6 +22,7 @@ func TestStruct(t *testing.T) {
"Value2": gen.Int64(),
"Value3": gen.SliceOf(gen.Int8()),
"NotThere": gen.AnyString(),
"Value5": gen.PtrOf(gen.Const("v5")),
})
for i := 0; i < 100; i++ {
value, ok := structGen.Sample()
Expand All @@ -29,7 +31,7 @@ func TestStruct(t *testing.T) {
t.Errorf("Invalid value: %#v", value)
}
v, ok := value.(testStruct)
if !ok || v.Value1 == "" || v.Value3 == nil || v.Value4 != "" {
if !ok || v.Value1 == "" || v.Value3 == nil || v.Value4 != "" || !(v.Value5 == nil || *v.Value5 == "v5"){
t.Errorf("Invalid value: %#v", value)
}
}
Expand Down

0 comments on commit 55d63c2

Please sign in to comment.