[testtools] Add tooling for publish test

This commit is contained in:
Cyrille Nofficial 2019-12-07 11:18:11 +01:00
parent 9124b09976
commit abefe81090
2 changed files with 52 additions and 0 deletions

View File

@ -3,8 +3,10 @@ package testtools
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/cyrilix/robocar-base/mqttdevice"
"github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait" "github.com/testcontainers/testcontainers-go/wait"
"sync"
"testing" "testing"
) )
@ -35,3 +37,24 @@ func MqttContainer(t *testing.T) (context.Context, testcontainers.Container, str
mqttUri := fmt.Sprintf("tcp://%s:%d", ip, port.Int()) mqttUri := fmt.Sprintf("tcp://%s:%d", ip, port.Int())
return ctx, mqttC, mqttUri 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]
}

View File

@ -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)
}
}
}