Skip to content

Commit 312d578

Browse files
committed
Resolve race condition and ensure t.Error is not called from goroutine.
1 parent 90d13b0 commit 312d578

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

client_test.go

+22-4
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,27 @@ func TestCustomConnectionFunction(t *testing.T) {
3131
netClient, netServer := net.Pipe()
3232
defer netClient.Close()
3333
defer netServer.Close()
34-
var firstMessage = ""
34+
35+
outputChan := make(chan struct {
36+
msg []byte
37+
err error
38+
})
3539
go func() {
3640
// read first message only
3741
bytes := make([]byte, 1024)
42+
netServer.SetDeadline(time.Now().Add(time.Second)) // Ensure this will always complete
3843
n, err := netServer.Read(bytes)
3944
if err != nil {
40-
t.Errorf("%v", err)
45+
outputChan <- struct {
46+
msg []byte
47+
err error
48+
}{err: err}
49+
} else {
50+
outputChan <- struct {
51+
msg []byte
52+
err error
53+
}{msg: bytes[:n]}
4154
}
42-
firstMessage = string(bytes[:n])
4355
}()
4456
// Set custom network connection function and client connect
4557
var customConnectionFunc OpenConnectionFunc = func(uri *url.URL, options ClientOptions) (net.Conn, error) {
@@ -52,10 +64,16 @@ func TestCustomConnectionFunction(t *testing.T) {
5264

5365
// Try to connect using custom function, wait for 2 seconds, to pass MQTT first message
5466
if token := client.Connect(); token.WaitTimeout(2*time.Second) && token.Error() != nil {
55-
t.Errorf("%v", token.Error())
67+
t.Fatalf("%v", token.Error())
68+
}
69+
70+
msg := <-outputChan
71+
if msg.err != nil {
72+
t.Fatalf("read from simulated connection failed: %v", msg.err)
5673
}
5774

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

0 commit comments

Comments
 (0)