maeqtt/subscription/subscription_test.go

58 lines
1.6 KiB
Go
Raw Normal View History

2021-10-01 22:18:48 +02:00
package subscription
import (
"testing"
"badat.dev/maeqtt/v2/mqtt/packets"
)
2021-10-08 23:53:37 +02:00
func assertMatches(topic packets.Topic, topicName string, shouldMatch bool, t *testing.T) {
2021-10-01 22:18:48 +02:00
tree := newSubscriptionTreeNode()
channel := make(SubscriptionChannel)
topicFilter := packets.TopicFilter{
Topic: topic,
MaxQoS: 1,
}
tree.Subscribe(topicFilter, channel)
2021-10-08 23:53:37 +02:00
subs := tree.GetSubscriptions(topicName)
2021-10-01 22:18:48 +02:00
2021-10-08 23:53:37 +02:00
if (len(subs) != 1) && shouldMatch {
t.Errorf("Topic %v did not match %v", topic, topicName)
2021-10-01 22:18:48 +02:00
}
2021-10-08 23:53:37 +02:00
if (len(subs) == 1) && !shouldMatch {
t.Errorf("Topic %v matched %v (it wasn't supposed to)", topic, topicName )
2021-10-01 22:18:48 +02:00
}
}
2021-10-08 23:53:37 +02:00
func TestSubscribe(t *testing.T) {
topic, _ := packets.ParseTopic("a/b/c")
assertMatches(topic, "a/b/c", true, t)
assertMatches(topic, "a/c/c", false, t)
assertMatches(topic, "b/b/c", false, t)
assertMatches(topic, "aaa/c/a", false, t)
}
func TestSingleLevelWildcard(t *testing.T) {
topic, _ := packets.ParseTopic("a/+/c")
assertMatches(topic, "a/b/c", true, t)
assertMatches(topic, "a/c/c", true, t)
assertMatches(topic, "a/b/d", false, t)
assertMatches(topic, "aaa/c/a", false, t)
topic, _ = packets.ParseTopic("+/+/+")
assertMatches(topic, "a/b/c", true, t)
assertMatches(topic, "a/c/c", true, t)
assertMatches(topic, "a/b/d/e", false, t)
assertMatches(topic, "c/a", true, t)
}
func TestMultiLevelWildcard(t *testing.T) {
topic, _ := packets.ParseTopic("a/b/c/#")
assertMatches(topic, "a/b/c", true, t)
assertMatches(topic, "a/b/c/a", true, t)
assertMatches(topic, "a/b/c/d", true, t)
assertMatches(topic, "a/b/c/f", true, t)
assertMatches(topic, "a/b/d/a", false, t)
}