diff --git a/testtools/testtools.go b/testtools/testtools.go index 85c3056..7c3b46c 100644 --- a/testtools/testtools.go +++ b/testtools/testtools.go @@ -3,8 +3,10 @@ package testtools import ( "context" "fmt" + "github.com/cyrilix/robocar-base/mqttdevice" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/wait" + "sync" "testing" ) @@ -35,3 +37,24 @@ func MqttContainer(t *testing.T) (context.Context, testcontainers.Container, str mqttUri := fmt.Sprintf("tcp://%s:%d", ip, port.Int()) return ctx, mqttC, mqttUri } + +func NewFakePublisher() *FakePublisher{ + return &FakePublisher{msg:make(map[string]mqttdevice.MqttValue)} +} + +type FakePublisher struct { + muMsg sync.Mutex + msg map[string]mqttdevice.MqttValue +} + +func (f *FakePublisher) Publish(topic string, payload mqttdevice.MqttValue) { + f.muMsg.Lock() + defer f.muMsg.Unlock() + f.msg[topic] = payload +} + +func (f* FakePublisher) PublishedEvent(topic string) mqttdevice.MqttValue{ + f.muMsg.Lock() + defer f.muMsg.Unlock() + return f.msg[topic] +} diff --git a/testtools/testtools_test.go b/testtools/testtools_test.go new file mode 100644 index 0000000..e95c6aa --- /dev/null +++ b/testtools/testtools_test.go @@ -0,0 +1,29 @@ +package testtools + +import ( + "github.com/cyrilix/robocar-base/mqttdevice" + "testing" +) + +func TestFakePublisher_Publish(t *testing.T) { + p := NewFakePublisher() + + cases := []struct { + topic string + topicPublished string + value mqttdevice.MqttValue + expected string + }{ + {"test/topic1", "test/topic1", mqttdevice.NewMqttValue(1) , "1" }, + {"test/topic2", "test/invalid", mqttdevice.NewMqttValue(1) , "" }, + } + + for _, c := range cases{ + p.Publish(c.topic, c.value) + val := p.PublishedEvent(c.topicPublished) + if v, _ := val.StringValue(); v != c.expected { + t.Errorf("FakePublisher.Publish(%v, %v): %v, wants %v", c.topic, string(c.value), v, c.expected) + } + + } +}