Skip to content

Commit

Permalink
FFM-2514 add function to convert various types to string
Browse files Browse the repository at this point in the history
  • Loading branch information
jcox250 committed Apr 7, 2022
1 parent 842ac1a commit 19426ae
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 1 deletion.
31 changes: 30 additions & 1 deletion analyticsservice/analytics.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"strconv"
"sync"
"time"

Expand Down Expand Up @@ -116,6 +117,34 @@ func (as *AnalyticsService) listener() {
}
}

func convertInterfaceToString(i interface{}) string {
if i == nil {
return "nil"
}

switch v := i.(type) {
case string:
return v
case int:
return strconv.Itoa(v)
case int64:
return strconv.FormatInt(v, 10)
case float64:
return fmt.Sprintf("%v", v)
case float32:
return fmt.Sprintf("%v", v)
case bool:
val := "false"
if v {
val = "true"
}
return val
default:
// As a last resort
return fmt.Sprintf("%v", v)
}
}

func (as *AnalyticsService) sendDataAndResetCache(ctx context.Context) {
as.mx.Lock()
// copy cache to send to server
Expand All @@ -136,7 +165,7 @@ func (as *AnalyticsService) sendDataAndResetCache(ctx context.Context) {
if analytic.target.Attributes != nil {
targetAttributes = make([]metricsclient.KeyValue, 0, len(*analytic.target.Attributes))
for key, value := range *analytic.target.Attributes {
v, _ := value.(string)
v := convertInterfaceToString(value)
kv := metricsclient.KeyValue{
Key: key,
Value: v,
Expand Down
54 changes: 54 additions & 0 deletions analyticsservice/analytics_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package analyticsservice

import "testing"

func Test_convertInterfaceToString(t *testing.T) {
testCases := map[string]struct {
input interface{}
expected string
}{
"Given I input a string": {
input: "123",
expected: "123",
},
"Given I input a bool with the value false": {
input: false,
expected: "false",
},
"Given I input a bool with the value true": {
input: true,
expected: "true",
},
"Given I input an int64": {
input: int64(123),
expected: "123",
},
"Given I input an int": {
input: 123,
expected: "123",
},
"Given I input a float64": {
input: float64(2.5),
expected: "2.5",
},
"Given I input a float32": {
input: float32(2.5),
expected: "2.5",
},
"Given I input a nil value": {
input: nil,
expected: "nil",
},
}

for desc, tc := range testCases {
tc := tc
t.Run(desc, func(t *testing.T) {

actual := convertInterfaceToString(tc.input)
if actual != tc.expected {
t.Errorf("(%s): expected %s, actual %s", desc, tc.expected, actual)
}
})
}
}

0 comments on commit 19426ae

Please sign in to comment.