From ae323d1690071945f10a5558289cfcc67303387e Mon Sep 17 00:00:00 2001 From: Cyrille Nofficial Date: Sat, 14 Dec 2019 10:41:57 +0100 Subject: [PATCH] [testtools] Add utility method to generate fake mqtt message --- testtools/testtools.go | 48 ++++++++++++++++++++++++++++++++++++- testtools/testtools_test.go | 12 +++++----- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/testtools/testtools.go b/testtools/testtools.go index 7c3b46c..6a5ac84 100644 --- a/testtools/testtools.go +++ b/testtools/testtools.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "github.com/cyrilix/robocar-base/mqttdevice" + mqtt "github.com/eclipse/paho.mqtt.golang" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/wait" "sync" @@ -53,8 +54,53 @@ func (f *FakePublisher) Publish(topic string, payload mqttdevice.MqttValue) { f.msg[topic] = payload } -func (f* FakePublisher) PublishedEvent(topic string) mqttdevice.MqttValue{ +func (f *FakePublisher) PublishedEvent(topic string) mqttdevice.MqttValue { f.muMsg.Lock() defer f.muMsg.Unlock() return f.msg[topic] } + +type fakeMessage struct { + qos byte + topic string + payload []byte + acked bool +} + +func (f *fakeMessage) Duplicate() bool { + return false +} + +func (f *fakeMessage) Qos() byte { + return f.qos +} + +func (f *fakeMessage) Retained() bool { + return false +} + +func (f *fakeMessage) Topic() string { + return f.topic +} + +func (f *fakeMessage) MessageID() uint16 { + return 1234 +} + +func (f *fakeMessage) Payload() []byte { + return f.payload +} + +func (f *fakeMessage) Ack() { + f.acked = true +} + +func NewFakeMessage(topic string, payload []byte) mqtt.Message { + return &fakeMessage{ + qos: 0, + topic: topic, + payload: payload, + acked: false, + } +} + diff --git a/testtools/testtools_test.go b/testtools/testtools_test.go index e95c6aa..c129908 100644 --- a/testtools/testtools_test.go +++ b/testtools/testtools_test.go @@ -9,16 +9,16 @@ func TestFakePublisher_Publish(t *testing.T) { p := NewFakePublisher() cases := []struct { - topic string + topic string topicPublished string - value mqttdevice.MqttValue - expected string + value mqttdevice.MqttValue + expected string }{ - {"test/topic1", "test/topic1", mqttdevice.NewMqttValue(1) , "1" }, - {"test/topic2", "test/invalid", mqttdevice.NewMqttValue(1) , "" }, + {"test/topic1", "test/topic1", mqttdevice.NewMqttValue(1), "1"}, + {"test/topic2", "test/invalid", mqttdevice.NewMqttValue(1), ""}, } - for _, c := range cases{ + for _, c := range cases { p.Publish(c.topic, c.value) val := p.PublishedEvent(c.topicPublished) if v, _ := val.StringValue(); v != c.expected {