-
Notifications
You must be signed in to change notification settings - Fork 670
Expand file tree
/
Copy pathconn_error_context_test.go
More file actions
347 lines (294 loc) · 10.9 KB
/
Copy pathconn_error_context_test.go
File metadata and controls
347 lines (294 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package clickhouse
import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"strings"
"testing"
"time"
"github.com/ClickHouse/ch-go/compress"
chproto "github.com/ClickHouse/ch-go/proto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ClickHouse/clickhouse-go/v2/lib/proto"
)
// mockNetConn is a mock net.Conn that can be configured to return specific errors
type mockNetConn struct {
net.Conn
readErr error
writeErr error
closed bool
}
func (m *mockNetConn) Read(b []byte) (n int, err error) {
if m.readErr != nil {
return 0, m.readErr
}
return 0, io.EOF
}
func (m *mockNetConn) Write(b []byte) (n int, err error) {
if m.writeErr != nil {
return 0, m.writeErr
}
return len(b), nil
}
func (m *mockNetConn) Close() error {
m.closed = true
return nil
}
func (m *mockNetConn) LocalAddr() net.Addr {
return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 12345}
}
func (m *mockNetConn) RemoteAddr() net.Addr {
return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 9000}
}
func (m *mockNetConn) SetDeadline(t time.Time) error { return nil }
func (m *mockNetConn) SetReadDeadline(t time.Time) error { return nil }
func (m *mockNetConn) SetWriteDeadline(t time.Time) error { return nil }
// createMockConnect creates a connect instance with mock components for testing
func createMockConnect(mockConn *mockNetConn) *connect {
reader := chproto.NewReader(mockConn)
buffer := new(chproto.Buffer)
compressor := &compress.Writer{}
return &connect{
id: 1,
conn: mockConn,
buffer: buffer,
reader: reader,
connectedAt: time.Now().Add(-5 * time.Minute),
readTimeout: 10 * time.Second,
compression: CompressionLZ4,
compressor: compressor,
maxCompressionBuffer: 1024 * 1024,
logger: newNoopLogger(),
opt: &Options{},
revision: ClientTCPProtocolVersion,
}
}
// TestHandshakeErrorContext tests that handshake errors include server address and connection info
func TestHandshakeErrorContext(t *testing.T) {
mockConn := &mockNetConn{readErr: io.EOF}
conn := createMockConnect(mockConn)
err := conn.handshake(Auth{
Database: "default",
Username: "default",
Password: "",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "handshake")
assert.Contains(t, err.Error(), "127.0.0.1:9000", "should contain server address")
assert.Contains(t, err.Error(), "conn_id=1", "should contain connection ID")
assert.Contains(t, err.Error(), "auth_db=default", "should contain database name")
assert.True(t, errors.Is(err, io.EOF), "should wrap io.EOF")
}
// TestQueryProcessingErrorContext tests that query processing errors include connection info
func TestQueryProcessingErrorContext(t *testing.T) {
mockConn := &mockNetConn{readErr: io.EOF}
conn := createMockConnect(mockConn)
_, err := conn.firstBlockImpl(context.Background(), &onProcess{})
require.Error(t, err)
assert.Contains(t, err.Error(), "query processing")
assert.Contains(t, err.Error(), "127.0.0.1:9000", "should contain server address")
assert.Contains(t, err.Error(), "conn_id=1", "should contain connection ID")
assert.True(t, errors.Is(err, io.EOF), "should wrap io.EOF")
}
// TestPingErrorContext tests that ping errors include connection age and connection info
func TestPingErrorContext(t *testing.T) {
mockConn := &mockNetConn{readErr: io.EOF}
conn := createMockConnect(mockConn)
// First flush succeeds (mocked Write), then read fails
mockConn.writeErr = nil // Allow flush to succeed
err := conn.ping(context.Background())
require.Error(t, err)
assert.Contains(t, err.Error(), "ping")
assert.Contains(t, err.Error(), "127.0.0.1:9000", "should contain server address")
assert.Contains(t, err.Error(), "conn_id=1", "should contain connection ID")
assert.Contains(t, err.Error(), "age=", "should contain connection age")
assert.True(t, errors.Is(err, io.EOF), "should wrap io.EOF")
}
// TestReadDataErrorContext tests that read data errors include connection and compression info
func TestReadDataErrorContext(t *testing.T) {
mockConn := &mockNetConn{readErr: io.EOF}
conn := createMockConnect(mockConn)
_, err := conn.readData(context.Background(), proto.ServerData, false)
require.Error(t, err)
assert.Contains(t, err.Error(), "read data")
assert.Contains(t, err.Error(), "127.0.0.1:9000", "should contain server address")
assert.Contains(t, err.Error(), "conn_id=1", "should contain connection ID")
assert.True(t, errors.Is(err, io.EOF), "should wrap io.EOF")
}
// TestSendDataErrorContext tests that send data errors include block information
func TestSendDataErrorContext(t *testing.T) {
mockConn := &mockNetConn{writeErr: io.EOF}
conn := createMockConnect(mockConn)
// Create a simple block with columns for testing
block := proto.NewBlock()
_ = block.AddColumn("col1", "UInt64")
_ = block.AddColumn("col2", "String")
err := conn.sendData(block, "test")
require.Error(t, err)
assert.Contains(t, err.Error(), "send data")
assert.Contains(t, err.Error(), "127.0.0.1:9000", "should contain server address")
assert.Contains(t, err.Error(), "conn_id=1", "should contain connection ID")
assert.Contains(t, err.Error(), "block_cols=2", "should contain block column count")
assert.Contains(t, err.Error(), "block_rows=", "should contain block row count")
assert.True(t, errors.Is(err, io.EOF), "should wrap io.EOF")
}
// TestErrorContextPreservesEOF tests that all error wrappers preserve io.EOF for errors.Is
func TestErrorContextPreservesEOF(t *testing.T) {
testCases := []struct {
name string
testFunc func(*connect) error
}{
{
name: "handshake",
testFunc: func(c *connect) error {
return c.handshake(Auth{Database: "default"})
},
},
{
name: "ping",
testFunc: func(c *connect) error {
return c.ping(context.Background())
},
},
{
name: "firstBlock",
testFunc: func(c *connect) error {
_, err := c.firstBlockImpl(context.Background(), &onProcess{})
return err
},
},
{
name: "readData",
testFunc: func(c *connect) error {
_, err := c.readData(context.Background(), proto.ServerData, false)
return err
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
mockConn := &mockNetConn{readErr: io.EOF}
conn := createMockConnect(mockConn)
err := tc.testFunc(conn)
require.Error(t, err)
assert.True(t, errors.Is(err, io.EOF),
"error from %s should preserve io.EOF for errors.Is check", tc.name)
// Also verify the error is not bare io.EOF
assert.NotEqual(t, io.EOF, err,
"error from %s should be wrapped, not bare io.EOF", tc.name)
// Verify error message has context
assert.NotEqual(t, "EOF", err.Error(),
"error from %s should have context beyond just 'EOF'", tc.name)
})
}
}
// TestErrorContextDistinguishesOperations tests that different operations produce distinguishable errors
func TestErrorContextDistinguishesOperations(t *testing.T) {
mockConn := &mockNetConn{readErr: io.EOF}
operations := map[string]func(*connect) error{
"handshake": func(c *connect) error {
return c.handshake(Auth{Database: "default"})
},
"ping": func(c *connect) error {
return c.ping(context.Background())
},
"query processing": func(c *connect) error {
_, err := c.firstBlockImpl(context.Background(), &onProcess{})
return err
},
"read data": func(c *connect) error {
_, err := c.readData(context.Background(), proto.ServerData, false)
return err
},
}
errorMessages := make(map[string]string)
for opName, opFunc := range operations {
conn := createMockConnect(mockConn)
err := opFunc(conn)
require.Error(t, err, "operation %s should return error", opName)
errorMessages[opName] = err.Error()
}
// Verify all error messages are unique and contain the operation name
for opName, errMsg := range errorMessages {
assert.Contains(t, strings.ToLower(errMsg), strings.ToLower(opName),
"error message should identify the operation: %s", opName)
// Verify this error is different from all others
for otherOp, otherMsg := range errorMessages {
if opName != otherOp {
assert.NotEqual(t, errMsg, otherMsg,
"error messages for %s and %s should be different", opName, otherOp)
}
}
}
}
// TestIsConnBrokenErrorDetectsEOF tests that isConnBrokenError still detects EOF errors
func TestIsConnBrokenErrorDetectsEOF(t *testing.T) {
mockConn := &mockNetConn{readErr: io.EOF}
conn := createMockConnect(mockConn)
// Test various wrapped EOF errors
testCases := []struct {
name string
getError func(*connect) error
}{
{
name: "handshake EOF",
getError: func(c *connect) error {
return c.handshake(Auth{Database: "default"})
},
},
{
name: "ping EOF",
getError: func(c *connect) error {
return c.ping(context.Background())
},
},
{
name: "query processing EOF",
getError: func(c *connect) error {
_, err := c.firstBlockImpl(context.Background(), &onProcess{})
return err
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := tc.getError(conn)
require.Error(t, err)
// Verify that isConnBrokenError correctly identifies these as connection errors
isBroken := isConnBrokenError(err)
assert.True(t, isBroken,
"isConnBrokenError should detect wrapped EOF from %s", tc.name)
})
}
}
// TestIsConnBrokenError_WrappedNetOpError verifies a *net.OpError wrapped
// inside fmt.Errorf is still detected as a broken connection.
func TestIsConnBrokenError_WrappedNetOpError(t *testing.T) {
opErr := &net.OpError{Op: "write", Net: "tcp", Err: os.ErrDeadlineExceeded}
// Direct *net.OpError is detected.
assert.True(t, isConnBrokenError(opErr), "bare *net.OpError should be detected")
// Wrapped once — as flush() does via fmt.Errorf("write: %w", err).
onceWrapped := fmt.Errorf("write: %w", opErr)
assert.True(t, isConnBrokenError(onceWrapped), "once-wrapped *net.OpError should be detected")
// Wrapped twice — as sendData does via fmt.Errorf("send data: ...: %w", flushErr).
twiceWrapped := fmt.Errorf("send data: failed to flush (conn_id=1): %w", onceWrapped)
assert.True(t, isConnBrokenError(twiceWrapped), "twice-wrapped *net.OpError should be detected")
// Unrelated error is not detected.
assert.False(t, isConnBrokenError(errors.New("some other error")), "unrelated error should not be detected")
}
// TestSendData_ClosesConnectionOnNetOpError verifies that sendData marks the connection closed
// when the underlying write returns a *net.OpError.
func TestSendData_ClosesConnectionOnNetOpError(t *testing.T) {
writeErr := &net.OpError{Op: "write", Net: "tcp", Err: os.ErrDeadlineExceeded}
mockConn := &mockNetConn{writeErr: writeErr}
conn := createMockConnect(mockConn)
block := proto.NewBlock()
_ = block.AddColumn("col1", "UInt64")
err := conn.sendData(block, "test")
require.Error(t, err)
assert.True(t, conn.isClosed(), "connection should be marked closed after a *net.OpError write failure")
}