[testtools] Add tooling for publish test
This commit is contained in:
parent
9124b09976
commit
abefe81090
@ -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]
|
||||
}
|
||||
|
29
testtools/testtools_test.go
Normal file
29
testtools/testtools_test.go
Normal 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)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user