96 lines
2.6 KiB
Go
96 lines
2.6 KiB
Go
package device
|
|
|
|
import (
|
|
"encoding/json"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"src.dualinventive.com/go/dinet/rpc"
|
|
)
|
|
|
|
func newTestFieldResultValueItem(val interface{}) *rpc.ResultValueItem {
|
|
data, err := json.Marshal(val)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
jsonData := json.RawMessage(data)
|
|
return &rpc.ResultValueItem{
|
|
Value: &jsonData,
|
|
}
|
|
}
|
|
|
|
func TestFieldInfoParse(t *testing.T) {
|
|
testcases := []struct {
|
|
name string
|
|
tType string
|
|
val interface{}
|
|
parsedVal interface{}
|
|
valid bool
|
|
}{
|
|
{name: "enum", tType: "enum", val: 4.0, parsedVal: 4, valid: true},
|
|
{name: "enum-invalid", tType: "enum", val: "hi", parsedVal: nil, valid: false},
|
|
{name: "number", tType: "number", val: 4.0, parsedVal: 4.0, valid: true},
|
|
{name: "number-invalid", tType: "number", val: "hi", parsedVal: nil, valid: false},
|
|
{name: "boolean-bool", tType: "bool", val: true, parsedVal: true, valid: true},
|
|
{name: "boolean-float", tType: "bool", val: 1.0, parsedVal: true, valid: false},
|
|
{name: "boolean-invalid", tType: "bool", val: "hi", parsedVal: nil, valid: false},
|
|
{name: "gps",
|
|
tType: "gps",
|
|
val: &rpc.GPSSensorData{
|
|
HDOP: 15.199999809265137,
|
|
Latitude: 51.587375000000002,
|
|
Longitude: 5.1980194444444443},
|
|
parsedVal: nil,
|
|
valid: true},
|
|
{name: "gps-invalid", tType: "gps", val: "hi", parsedVal: nil, valid: false},
|
|
{name: "struct",
|
|
tType: "struct",
|
|
val: map[string]interface{}{
|
|
"x": 20.0,
|
|
"y": 30.0,
|
|
"z": 100.0,
|
|
},
|
|
parsedVal: nil,
|
|
valid: true},
|
|
}
|
|
for _, tc := range testcases {
|
|
tc := tc
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
fi := FieldInfo{Label: "sensor_mylabel", Type: tc.tType}
|
|
fields, err := fi.Parse(newTestFieldResultValueItem(tc.val))
|
|
if !tc.valid {
|
|
assert.Equal(t, ErrInvalidType, err)
|
|
assert.Nil(t, fields)
|
|
return
|
|
}
|
|
switch tc.tType {
|
|
case "gps":
|
|
assert.Equal(t, map[string]interface{}{
|
|
"sensor_mylabel_hdop": 15.199999809265137,
|
|
"sensor_mylabel_latitude": 51.587375000000002,
|
|
"sensor_mylabel_longitude": 5.1980194444444443,
|
|
}, fields)
|
|
return
|
|
case "struct":
|
|
assert.Equal(t, map[string]interface{}{
|
|
"sensor_mylabel_x": 20.0,
|
|
"sensor_mylabel_y": 30.0,
|
|
"sensor_mylabel_z": 100.0,
|
|
}, fields)
|
|
return
|
|
default:
|
|
assert.Equal(t, map[string]interface{}{"sensor_mylabel": tc.parsedVal}, fields)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestFieldInfoInvalidType(t *testing.T) {
|
|
fi := FieldInfo{
|
|
Label: "sensor_hi",
|
|
Type: "mytype",
|
|
}
|
|
_, err := fi.Parse(newTestFieldResultValueItem(1337))
|
|
assert.Equal(t, ErrInvalidType, err)
|
|
}
|