Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolve race condition and ensure t.Error is not called from goroutine. #606

Merged
merged 1 commit into from Aug 9, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 22 additions & 4 deletions client_test.go
Expand Up @@ -31,15 +31,27 @@ func TestCustomConnectionFunction(t *testing.T) {
netClient, netServer := net.Pipe()
defer netClient.Close()
defer netServer.Close()
var firstMessage = ""

outputChan := make(chan struct {
msg []byte
err error
})
go func() {
// read first message only
bytes := make([]byte, 1024)
netServer.SetDeadline(time.Now().Add(time.Second)) // Ensure this will always complete
n, err := netServer.Read(bytes)
if err != nil {
t.Errorf("%v", err)
outputChan <- struct {
msg []byte
err error
}{err: err}
} else {
outputChan <- struct {
msg []byte
err error
}{msg: bytes[:n]}
}
firstMessage = string(bytes[:n])
}()
// Set custom network connection function and client connect
var customConnectionFunc OpenConnectionFunc = func(uri *url.URL, options ClientOptions) (net.Conn, error) {
Expand All @@ -52,10 +64,16 @@ func TestCustomConnectionFunction(t *testing.T) {

// Try to connect using custom function, wait for 2 seconds, to pass MQTT first message
if token := client.Connect(); token.WaitTimeout(2*time.Second) && token.Error() != nil {
t.Errorf("%v", token.Error())
t.Fatalf("%v", token.Error())
}

msg := <-outputChan
if msg.err != nil {
t.Fatalf("read from simulated connection failed: %v", msg.err)
}

// Analyze first message sent by client and received by the server
firstMessage := string(msg.msg)
if len(firstMessage) <= 0 || !strings.Contains(firstMessage, "MQTT") {
t.Error("no message received on connect")
}
Expand Down