1
0
mirror of https://github.com/mainflux/mainflux.git synced 2025-04-24 13:48:49 +08:00
Mainflux.mainflux/mqtt/handler_test.go
b1ackd0t 790f8a6abf
NOISSUE - Make MQTT Broker Configurable (#1904)
* Minor changes on mqtt publisher using nats

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Remove vernemq dependencies

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Restore VerneMQ config files

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Fix Makefile to support custom Docker profiles

The Makefile has been updated to support custom Docker profiles.
Previously, the Makefile only supported the default profiles for the
message broker and MQTT broker. Now, the Makefile allows for custom
profiles to be specified using environment variables. If the
MF_BROKER_TYPE or MF_MQTT_BROKER_TYPE variables are not set, the
default values "nats" and "nats" will be used, respectively. This
change enables more flexibility in configuring the Docker environment
for the project.

The `run` target has also been modified to use the correct broker
configuration file based on the MF_BROKER_TYPE variable. The sed
command in the `run` target now replaces the placeholder in the
docker/docker-compose.yml file with the appropriate broker
configuration file.

This commit improves the Makefile to support custom Docker profiles
and ensures the correct broker configuration file is used when
running the project.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Fix queue binding issue in RabbitMQ pubsub

The commit fixes an issue in the RabbitMQ pubsub implementation where the queue binding was not correctly set up. Instead of using the topic as the queue name, the commit now uses a unique client ID generated by combining the topic and subscriber ID. This ensures that each subscriber has its own dedicated queue. The commit also updates the queue binding to use the correct queue name.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Refactor Docker config editing in Makefile

The commit refactors the `edit_docker_config` function in the Makefile to improve readability and maintainability. The changes include:

- Removing unnecessary conditionals related to the `rabbitmq` broker

These changes ensure that the Docker configuration is correctly updated based on the specified MQTT broker type.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Fix failing tests on RabbitMQ

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Refactor MQTT_BROKER comment in docker-compose.yml

The MQTT_BROKER comment in the docker-compose.yml file has been updated to provide a more accurate description of its functionality. The comment now states that the MQTT_BROKER handles MQTT communication between MQTT adapters and the message broker, instead of Mainflux services. This change improves clarity and aligns with the actual purpose of the MQTT_BROKER.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Rename `MF_BROKER` to `MF_MESSAGE_BROKER`

The Makefile and Semaphore configuration files have been refactored to update the variable names related to the message broker type.

These changes ensure consistency and clarity in the codebase by using more descriptive variable names related to the message broker type.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Fix Docker profile configuration for nats_rabbitmq

Update the Docker profile configuration for nats_rabbitmq by replacing the NATS URL in the .env file with the correct value.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Rename MF_BROKER_URL to MF_MESSAGE_BROKER_URL

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Fix MQTT QoS level in pubsub.go

The MQTT QoS level in the pubsub.go file was set to 1, which is the
default level. However, since NATS supports up to QoS 1, I updated the
QoS level comment to reflect this.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Refactor NewPublisher to accept QoS parameter

The NewPublisher function in the pkg/messaging/mqtt/publisher.go file has been refactored to accept a new parameter, qos, which represents the Quality of Service level for MQTT message publishing. This change allows for more flexibility in configuring the MQTT publisher.

The NewPublisher function now has the following signature:

```go
func NewPublisher(address string, qos uint8, timeout time.Duration) (messaging.Publisher, error)
```

This change ensures that the MQTT publisher can be created with the desired QoS level, enhancing the reliability and delivery guarantees of the published messages.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Fix test assertions in pubsub_test.go

The test assertions in the pubsub_test.go file were incorrect. This commit fixes the assertions to properly compare the expected and received message values.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* Test configurable MQTT broker

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

---------

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>
Signed-off-by: rodneyosodo <blackd0t@protonmail.com>
2023-10-19 21:01:09 +02:00

459 lines
11 KiB
Go

// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mqtt_test
import (
"bytes"
"context"
"fmt"
"log"
"testing"
authmocks "github.com/mainflux/mainflux/auth/mocks"
"github.com/mainflux/mainflux/logger"
"github.com/mainflux/mainflux/mqtt"
"github.com/mainflux/mainflux/mqtt/mocks"
"github.com/mainflux/mainflux/pkg/errors"
"github.com/mainflux/mproxy/pkg/session"
"github.com/stretchr/testify/assert"
)
const (
thingID = "513d02d2-16c1-4f23-98be-9e12f8fee898"
thingID1 = "513d02d2-16c1-4f23-98be-9e12f8fee899"
password = "password"
password1 = "password1"
chanID = "123e4567-e89b-12d3-a456-000000000001"
invalidID = "invalidID"
clientID = "clientID"
clientID1 = "clientID1"
subtopic = "testSubtopic"
invalidChannelIDTopic = "channels/**/messages"
)
var (
topicMsg = "channels/%s/messages"
topic = fmt.Sprintf(topicMsg, chanID)
invalidTopic = "invalidTopic"
payload = []byte("[{'n':'test-name', 'v': 1.2}]")
topics = []string{topic}
invalidTopics = []string{invalidTopic}
invalidChanIDTopics = []string{fmt.Sprintf(topicMsg, invalidTopic)}
// Test log messages for cases the handler does not provide a return value.
logBuffer = bytes.Buffer{}
sessionClient = session.Session{
ID: clientID,
Username: thingID,
Password: []byte(password),
}
sessionClientSub = session.Session{
ID: clientID1,
Username: thingID1,
Password: []byte(password1),
}
invalidThingSessionClient = session.Session{
ID: clientID,
Username: invalidID,
Password: []byte(password),
}
)
func TestAuthConnect(t *testing.T) {
handler := newHandler()
cases := []struct {
desc string
err error
session *session.Session
}{
{
desc: "connect without active session",
err: mqtt.ErrClientNotInitialized,
session: nil,
},
{
desc: "connect without clientID",
err: mqtt.ErrMissingClientID,
session: &session.Session{
ID: "",
Username: thingID,
Password: []byte(password),
},
},
{
desc: "connect with invalid password",
err: errors.ErrAuthentication,
session: &session.Session{
ID: clientID,
Username: thingID,
Password: []byte(""),
},
},
{
desc: "connect with valid password and invalid username",
err: errors.ErrAuthentication,
session: &invalidThingSessionClient,
},
{
desc: "connect with valid username and password",
err: nil,
session: &sessionClient,
},
}
for _, tc := range cases {
ctx := context.TODO()
if tc.session != nil {
ctx = session.NewContext(ctx, tc.session)
}
err := handler.AuthConnect(ctx)
assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err))
}
}
func TestAuthPublish(t *testing.T) {
handler := newHandler()
cases := []struct {
desc string
session *session.Session
err error
topic *string
payload []byte
}{
{
desc: "publish with an inactive client",
session: nil,
err: mqtt.ErrClientNotInitialized,
topic: &topic,
payload: payload,
},
{
desc: "publish without topic",
session: &sessionClient,
err: mqtt.ErrMissingTopicPub,
topic: nil,
payload: payload,
},
{
desc: "publish with malformed topic",
session: &sessionClient,
err: mqtt.ErrMalformedTopic,
topic: &invalidTopic,
payload: payload,
},
{
desc: "publish with invalid access rights",
session: &sessionClientSub,
err: errors.ErrAuthorization,
topic: &topic,
payload: payload,
},
{
desc: "publish successfully",
session: &sessionClient,
err: nil,
topic: &topic,
payload: payload,
},
}
for _, tc := range cases {
ctx := context.TODO()
if tc.session != nil {
ctx = session.NewContext(ctx, tc.session)
}
err := handler.AuthPublish(ctx, tc.topic, &tc.payload)
assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err))
}
}
func TestAuthSubscribe(t *testing.T) {
handler := newHandler()
cases := []struct {
desc string
session *session.Session
err error
topic *[]string
}{
{
desc: "subscribe without active session",
session: nil,
err: mqtt.ErrClientNotInitialized,
topic: &topics,
},
{
desc: "subscribe without topics",
session: &sessionClient,
err: mqtt.ErrMissingTopicSub,
topic: nil,
},
{
desc: "subscribe with invalid topics",
session: &sessionClient,
err: mqtt.ErrMalformedTopic,
topic: &invalidTopics,
},
{
desc: "subscribe with invalid channel ID",
session: &sessionClient,
err: errors.ErrAuthorization,
topic: &invalidChanIDTopics,
},
{
desc: "subscribe with active session, valid topics, but invalid access rights",
session: &sessionClient,
err: errors.ErrAuthorization,
topic: &topics,
},
{
desc: "subscribe successfully",
session: &sessionClientSub,
err: nil,
topic: &topics,
},
}
for _, tc := range cases {
ctx := context.TODO()
if tc.session != nil {
ctx = session.NewContext(ctx, tc.session)
}
err := handler.AuthSubscribe(ctx, tc.topic)
assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err))
}
}
func TestConnect(t *testing.T) {
handler := newHandler()
logBuffer.Reset()
cases := []struct {
desc string
session *session.Session
err error
logMsg string
}{
{
desc: "connect without active session",
session: nil,
err: errors.Wrap(mqtt.ErrFailedConnect, mqtt.ErrClientNotInitialized),
},
{
desc: "connect with active session",
session: &sessionClient,
logMsg: fmt.Sprintf(mqtt.LogInfoConnected, clientID),
err: nil,
},
}
for _, tc := range cases {
ctx := context.TODO()
if tc.session != nil {
ctx = session.NewContext(ctx, tc.session)
}
err := handler.Connect(ctx)
assert.Contains(t, logBuffer.String(), tc.logMsg)
assert.Equal(t, tc.err, err)
}
}
func TestPublish(t *testing.T) {
handler := newHandler()
logBuffer.Reset()
malformedSubtopics := topic + "/" + subtopic + "%"
wrongCharSubtopics := topic + "/" + subtopic + ">"
validSubtopic := topic + "/" + subtopic
cases := []struct {
desc string
session *session.Session
topic string
payload []byte
logMsg string
err error
}{
{
desc: "publish without active session",
session: nil,
topic: topic,
payload: payload,
err: errors.Wrap(mqtt.ErrFailedPublish, mqtt.ErrClientNotInitialized),
},
{
desc: "publish with invalid topic",
session: &sessionClient,
topic: invalidTopic,
payload: payload,
logMsg: fmt.Sprintf(mqtt.LogInfoPublished, clientID, invalidTopic),
err: errors.Wrap(mqtt.ErrFailedPublish, mqtt.ErrMalformedTopic),
},
{
desc: "publish with invalid channel ID",
session: &sessionClient,
topic: invalidChannelIDTopic,
payload: payload,
err: errors.Wrap(mqtt.ErrFailedPublish, mqtt.ErrMalformedTopic),
},
{
desc: "publish with malformed subtopic",
session: &sessionClient,
topic: malformedSubtopics,
payload: payload,
err: errors.Wrap(mqtt.ErrFailedParseSubtopic, mqtt.ErrMalformedSubtopic),
},
{
desc: "publish with subtopic containing wrong character",
session: &sessionClient,
topic: wrongCharSubtopics,
payload: payload,
err: errors.Wrap(mqtt.ErrFailedParseSubtopic, mqtt.ErrMalformedSubtopic),
},
{
desc: "publish with subtopic",
session: &sessionClient,
topic: validSubtopic,
payload: payload,
logMsg: subtopic,
},
{
desc: "publish without subtopic",
session: &sessionClient,
topic: topic,
payload: payload,
logMsg: "",
},
}
for _, tc := range cases {
ctx := context.TODO()
if tc.session != nil {
ctx = session.NewContext(ctx, tc.session)
}
err := handler.Publish(ctx, &tc.topic, &tc.payload)
assert.Contains(t, logBuffer.String(), tc.logMsg)
assert.Equal(t, tc.err, err)
}
}
func TestSubscribe(t *testing.T) {
handler := newHandler()
logBuffer.Reset()
cases := []struct {
desc string
session *session.Session
topic []string
logMsg string
err error
}{
{
desc: "subscribe without active session",
session: nil,
topic: topics,
err: errors.Wrap(mqtt.ErrFailedSubscribe, mqtt.ErrClientNotInitialized),
},
{
desc: "subscribe with valid session and topics",
session: &sessionClient,
topic: topics,
logMsg: fmt.Sprintf(mqtt.LogInfoSubscribed, clientID, topics[0]),
},
}
for _, tc := range cases {
ctx := context.TODO()
if tc.session != nil {
ctx = session.NewContext(ctx, tc.session)
}
err := handler.Subscribe(ctx, &tc.topic)
assert.Contains(t, logBuffer.String(), tc.logMsg)
assert.Equal(t, tc.err, err)
}
}
func TestUnsubscribe(t *testing.T) {
handler := newHandler()
logBuffer.Reset()
cases := []struct {
desc string
session *session.Session
topic []string
logMsg string
err error
}{
{
desc: "unsubscribe without active session",
session: nil,
topic: topics,
err: errors.Wrap(mqtt.ErrFailedUnsubscribe, mqtt.ErrClientNotInitialized),
},
{
desc: "unsubscribe with valid session and topics",
session: &sessionClient,
topic: topics,
logMsg: fmt.Sprintf(mqtt.LogInfoUnsubscribed, clientID, topics[0]),
},
}
for _, tc := range cases {
ctx := context.TODO()
if tc.session != nil {
ctx = session.NewContext(ctx, tc.session)
}
err := handler.Unsubscribe(ctx, &tc.topic)
assert.Contains(t, logBuffer.String(), tc.logMsg)
assert.Equal(t, tc.err, err)
}
}
func TestDisconnect(t *testing.T) {
handler := newHandler()
logBuffer.Reset()
cases := []struct {
desc string
session *session.Session
topic []string
logMsg string
err error
}{
{
desc: "disconnect without active session",
session: nil,
topic: topics,
err: errors.Wrap(mqtt.ErrFailedDisconnect, mqtt.ErrClientNotInitialized),
},
{
desc: "disconnect with valid session",
session: &sessionClient,
topic: topics,
err: nil,
},
}
for _, tc := range cases {
ctx := context.TODO()
if tc.session != nil {
ctx = session.NewContext(ctx, tc.session)
}
err := handler.Disconnect(ctx)
assert.Contains(t, logBuffer.String(), tc.logMsg)
assert.Equal(t, tc.err, err)
}
}
func newHandler() session.Handler {
logger, err := logger.New(&logBuffer, "debug")
if err != nil {
log.Fatalf("failed to create logger: %s", err)
}
auth := new(authmocks.Service)
eventStore := mocks.NewEventStore()
return mqtt.NewHandler(mocks.NewPublisher(), eventStore, logger, auth)
}