shelly-prometheus-exporter/mqtt_test.go

76 lines
2.3 KiB
Go

package main
import (
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
)
type fakeMsg struct {
topic string
payload string
}
func (m fakeMsg) Duplicate() bool { return false }
func (m fakeMsg) Qos() byte { return 0 }
func (m fakeMsg) Retained() bool { return false }
func (m fakeMsg) Topic() string { return m.topic }
func (m fakeMsg) MessageID() uint16 { return 0 }
func (m fakeMsg) Payload() []byte { return []byte(m.payload) }
func (m fakeMsg) Ack() {}
func gauge(t *testing.T, name string, labels ...string) float64 {
t.Helper()
if name == "shelly_online" {
return testutil.ToFloat64(onlineGauge.WithLabelValues(labels...))
}
for _, m := range mappings {
if testutil.CollectAndCount(m.Gauge, name) > 0 {
return testutil.ToFloat64(m.Gauge.WithLabelValues(labels...))
}
}
t.Fatalf("metric %s not found", name)
return 0
}
func TestHandleMessage(t *testing.T) {
const dev = "shellyplussmoke-halle-2"
for _, m := range []fakeMsg{
{dev + "/online", "false"},
{dev + "/status/cloud", `{"connected":true}`},
{dev + "/status/mqtt", `{"connected":true}`},
{dev + "/status/smoke:0", `{"id":0,"alarm":false, "mute":false}`},
{dev + "/status/devicepower:0", `{"id": 0,"battery":{"V":2.98, "percent":95}}`},
} {
handleMessage(nil, m)
}
checks := []struct {
name string
labels []string
want float64
}{
{"shelly_online", []string{dev}, 0},
{"shelly_cloud_connected", []string{dev}, 1},
{"shelly_mqtt_connected", []string{dev}, 1},
{"shelly_smoke_alarm", []string{dev, "0"}, 0},
{"shelly_smoke_mute", []string{dev, "0"}, 0},
{"shelly_battery_voltage_volts", []string{dev, "0"}, 2.98},
{"shelly_battery_percent", []string{dev, "0"}, 95},
}
for _, c := range checks {
if got := gauge(t, c.name, c.labels...); got != c.want {
t.Errorf("%s = %v, want %v", c.name, got, c.want)
}
}
// A NotifyStatus event only updates the fields it contains.
handleMessage(nil, fakeMsg{dev + "/events/rpc",
`{"src":"x","method":"NotifyStatus","params":{"ts":1.5,"smoke:0":{"alarm":true}}}`})
if got := gauge(t, "shelly_smoke_alarm", dev, "0"); got != 1 {
t.Errorf("alarm after event = %v, want 1", got)
}
if got := gauge(t, "shelly_battery_percent", dev, "0"); got != 95 {
t.Errorf("battery changed by unrelated event: %v", got)
}
}