Skip to content

Commit

Permalink
Merge pull request #15 from mcorbin/event-marshal-metric-nil
Browse files Browse the repository at this point in the history
Test if the Metric field is nil when converting to protobuf
  • Loading branch information
mcorbin authored Mar 12, 2018
2 parents 0c727ec + 5265e7c commit ad675a6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
22 changes: 12 additions & 10 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
20 changes: 20 additions & 0 deletions marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit ad675a6

Please sign in to comment.