From 49faad16722caa9ecf846aca700cc6fddc6a190d Mon Sep 17 00:00:00 2001 From: rerorero Date: Thu, 18 Oct 2018 20:24:15 +0900 Subject: [PATCH] Avoid nil reference when struct has gen.PtrOf field --- gen/struct.go | 6 +++++- gen/struct_test.go | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/gen/struct.go b/gen/struct.go index d57a829..0f5b09a 100644 --- a/gen/struct.go +++ b/gen/struct.go @@ -29,7 +29,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) diff --git a/gen/struct_test.go b/gen/struct_test.go index 62ea546..1ae85aa 100644 --- a/gen/struct_test.go +++ b/gen/struct_test.go @@ -13,6 +13,7 @@ type testStruct struct { Value2 int64 Value3 []int8 Value4 string + Value5 *string } func TestStruct(t *testing.T) { @@ -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() @@ -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) } }