Skip to content

Commit

Permalink
test(confmws/confmqtt): fix unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
saitofun committed Jul 22, 2024
1 parent ae3c5cc commit 37576b3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
28 changes: 17 additions & 11 deletions confmws/confmqtt/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ func init() {
mqtt.WARN = log.New(os.Stdout, "[MQTT WRN]", log.LstdFlags)
}

func LogOnConnectionLost(c mqtt.Client, err error) {
opt := c.OptionsReader()
mqtt.WARN.Printf("connection lost: `%s` caused by %v", opt.ClientID(), err)
}

func LogOnReconnecting(_ mqtt.Client, opt *mqtt.ClientOptions) {
mqtt.WARN.Printf("reconnecting: `%s`", opt.ClientID)
}

func LogOnConnected(c mqtt.Client) {
opt := c.OptionsReader()
mqtt.WARN.Printf("client connected: `%s`", opt.ClientID())
}

type Broker struct {
Server datatypex.Endpoint
Retry retry.Retry
Expand Down Expand Up @@ -101,17 +115,9 @@ func (b *Broker) options(cid string) *mqtt.ClientOptions {
options.SetConnectTimeout(b.Timeout)
options.SetPingTimeout(b.Timeout)

options.SetConnectionLostHandler(func(c mqtt.Client, err error) {
opt := c.OptionsReader()
mqtt.WARN.Printf("connection lost: `%s` caused by %v", opt.ClientID(), err)
})
options.SetReconnectingHandler(func(_ mqtt.Client, opt *mqtt.ClientOptions) {
mqtt.WARN.Printf("reconnecting: `%s`", opt.ClientID)
})
options.SetOnConnectHandler(func(c mqtt.Client) {
opt := c.OptionsReader()
mqtt.WARN.Printf("client connected: `%s`", opt.ClientID())
})
options.SetConnectionLostHandler(LogOnConnectionLost)
options.SetReconnectingHandler(LogOnReconnecting)
options.SetOnConnectHandler(LogOnConnected)

return options
}
Expand Down
8 changes: 8 additions & 0 deletions confmws/confmqtt/broker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/google/uuid"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"github.com/xoctopus/x/misc/must"

. "github.com/xoctopus/confx/confmws/confmqtt"
Expand Down Expand Up @@ -122,6 +123,13 @@ func TestBrokerExt(t *testing.T) {
NewWithT(t).Expect(err).To(Equal(ErrInvalidTopic))
NewWithT(t).Expect(c).To(BeNil())
})
t.Run("ClientOptionHooks", func(t *testing.T) {
opt := &mqtt.ClientOptions{ClientID: "logger_client"}
c := mqtt.NewClient(opt)
LogOnConnected(c)
LogOnReconnecting(c, opt)
LogOnConnectionLost(c, errors.New("conn lost"))
})
}

func TestClientTimeout(t *testing.T) {
Expand Down

0 comments on commit 37576b3

Please sign in to comment.