From 5265e7c1ebcb49a480590d9418e41fb64c246ed6 Mon Sep 17 00:00:00 2001 From: mcorbin Date: Thu, 8 Mar 2018 19:16:22 +0100 Subject: [PATCH] Test if the Metric field is nil when converting to protobuf --- marshal.go | 22 ++++++++++++---------- marshal_test.go | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/marshal.go b/marshal.go index c6cfddc..259875b 100644 --- a/marshal.go +++ b/marshal.go @@ -54,16 +54,18 @@ func EventToProtocolBuffer(event *Event) (*proto.Event, error) { e.Ttl = pb.Float32(event.Ttl) } - switch reflect.TypeOf(event.Metric).Kind() { - case reflect.Int, reflect.Int32, reflect.Int64: - e.MetricSint64 = pb.Int64((reflect.ValueOf(event.Metric).Int())) - case reflect.Float32: - e.MetricD = pb.Float64((reflect.ValueOf(event.Metric).Float())) - case reflect.Float64: - e.MetricD = pb.Float64((reflect.ValueOf(event.Metric).Float())) - default: - return nil, fmt.Errorf("Metric of invalid type (type %v)", - reflect.TypeOf(event.Metric).Kind()) + if event.Metric != nil { + switch reflect.TypeOf(event.Metric).Kind() { + case reflect.Int, reflect.Int32, reflect.Int64: + e.MetricSint64 = pb.Int64((reflect.ValueOf(event.Metric).Int())) + case reflect.Float32: + e.MetricD = pb.Float64((reflect.ValueOf(event.Metric).Float())) + case reflect.Float64: + e.MetricD = pb.Float64((reflect.ValueOf(event.Metric).Float())) + default: + return nil, fmt.Errorf("Metric of invalid type (type %v)", + reflect.TypeOf(event.Metric).Kind()) + } } return &e, nil } diff --git a/marshal_test.go b/marshal_test.go index 5382007..d4681f8 100644 --- a/marshal_test.go +++ b/marshal_test.go @@ -233,6 +233,26 @@ func TestEventToProtocolBuffer(t *testing.T) { if !pb.Equal(protoRes, &protoTest) { t.Error("Error during event to protobuf conversion") } + + // Event without metrics + event = Event{ + Host: "baz", + Service: "foobar", + Time: time.Unix(100, 123456789), + } + protoRes, error = EventToProtocolBuffer(&event) + if error != nil { + t.Error("Error during EventToProtocolBuffer") + } + protoTest = proto.Event{ + Host: pb.String("baz"), + Service: pb.String("foobar"), + Time: pb.Int64(100), + TimeMicros: pb.Int64(100123456), + } + if !pb.Equal(protoRes, &protoTest) { + t.Error("Error during event to protobuf conversion") + } } func compareEvents(e1 *Event, e2 *Event, t *testing.T) {