-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpool_test.go
More file actions
370 lines (325 loc) · 9.35 KB
/
pool_test.go
File metadata and controls
370 lines (325 loc) · 9.35 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package db
import (
"database/sql"
"testing"
"time"
"github.com/go-playground/validator/v10"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
noopm "go.opentelemetry.io/otel/metric/noop"
noopt "go.opentelemetry.io/otel/trace/noop"
"gorm.io/gorm/logger"
pkgotel "github.com/jasoet/pkg/v2/otel"
)
func TestDatabaseConfigValidation(t *testing.T) {
validConfig := &ConnectionConfig{
DBType: Mysql,
Host: "localhost",
Port: 3306,
Username: "root",
Password: "",
DBName: "mydb",
Timeout: 3 * time.Second,
MaxIdleConns: 5,
MaxOpenConns: 10,
}
invalidConfig := &ConnectionConfig{
DBType: "invalid_db_type",
Host: "",
Port: -1,
Username: "",
Password: "",
DBName: "",
MaxIdleConns: 0,
MaxOpenConns: 0,
}
validate := validator.New()
err := validate.Struct(validConfig)
assert.NoError(t, err, "valid database config should pass validation")
err = validate.Struct(invalidConfig)
assert.Error(t, err, "invalid database config should fail validation")
}
func TestCustomValidationTags(t *testing.T) {
type CustomStruct struct {
CustomField string `validate:"custom"`
}
validate := validator.New()
_ = validate.RegisterValidation("custom", func(fl validator.FieldLevel) bool {
value := fl.Field().String()
return value == "foo" || value == "bar"
})
validStruct := &CustomStruct{CustomField: "foo"}
invalidStruct := &CustomStruct{CustomField: "baz"}
err := validate.Struct(validStruct)
assert.NoError(t, err, "valid custom struct should pass validation")
err = validate.Struct(invalidStruct)
assert.Error(t, err, "invalid custom struct should fail validation")
}
func TestConnectionConfig_dsn(t *testing.T) {
tests := []struct {
name string
config ConnectionConfig
wantDsn string
}{
{
name: "MySQL connection",
config: ConnectionConfig{
DBType: Mysql,
Host: "localhost",
Port: 3306,
Username: "root",
Password: "password",
DBName: "test",
Timeout: 3 * time.Second,
},
wantDsn: "root:password@tcp(localhost:3306)/test?parseTime=true&timeout=3s",
},
{
name: "Postgres connection",
config: ConnectionConfig{
DBType: Postgresql,
Host: "localhost",
Port: 5432,
Username: "postgres",
Password: "password",
DBName: "test",
Timeout: 3 * time.Second,
},
wantDsn: "user=postgres password=password host=localhost port=5432 dbname=test sslmode=require connect_timeout=3",
},
{
name: "Different port",
config: ConnectionConfig{
DBType: Mysql,
Host: "localhost",
Port: 8080,
Username: "root",
Password: "password",
DBName: "test",
Timeout: 5 * time.Second,
},
wantDsn: "root:password@tcp(localhost:8080)/test?parseTime=true&timeout=5s",
},
{
name: "All configurations are empty",
config: ConnectionConfig{
DBType: "",
Host: "",
Port: 0,
Username: "",
Password: "",
DBName: "",
Timeout: 0 * time.Second,
},
wantDsn: "", // Unknown DbType returns empty DSN
},
{
name: "MSSQL connection",
config: ConnectionConfig{
DBType: MSSQL,
Host: "localhost",
Port: 1433,
Username: "sa",
Password: "password",
DBName: "test",
Timeout: 5 * time.Second,
},
wantDsn: "sqlserver://sa:password@localhost:1433?database=test&connectTimeout=5s&encrypt=require",
},
{
name: "Postgres with custom SSLMode",
config: ConnectionConfig{
DBType: Postgresql,
Host: "localhost",
Port: 5432,
Username: "postgres",
Password: "password",
DBName: "test",
Timeout: 3 * time.Second,
SSLMode: "require",
},
wantDsn: "user=postgres password=password host=localhost port=5432 dbname=test sslmode=require connect_timeout=3",
},
{
name: "Zero timeout uses default 30s",
config: ConnectionConfig{
DBType: Mysql,
Host: "localhost",
Port: 3306,
Username: "root",
Password: "password",
DBName: "test",
Timeout: 0,
},
wantDsn: "root:password@tcp(localhost:3306)/test?parseTime=true&timeout=30s",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotDsn := tt.config.dsn()
assert.Equal(t, tt.wantDsn, gotDsn)
})
}
}
// TestExtractOperationType removed - extractOperationType is no longer used
// The uptrace otelgorm library handles operation type extraction internally
func TestEffectiveTimeout(t *testing.T) {
c := &ConnectionConfig{Timeout: 0}
assert.Equal(t, 30*time.Second, c.effectiveTimeout())
c.Timeout = 5 * time.Second
assert.Equal(t, 5*time.Second, c.effectiveTimeout())
}
func TestEffectiveSSLMode(t *testing.T) {
c := &ConnectionConfig{}
assert.Equal(t, "require", c.effectiveSSLMode())
c.SSLMode = "disable"
assert.Equal(t, "disable", c.effectiveSSLMode())
}
func TestEffectiveGormLogLevel(t *testing.T) {
c := &ConnectionConfig{}
assert.Equal(t, logger.Silent, c.effectiveGormLogLevel())
c.GormLogLevel = int(logger.Info)
assert.Equal(t, logger.Info, c.effectiveGormLogLevel())
c.GormLogLevel = 99 // Invalid value
assert.Equal(t, logger.Silent, c.effectiveGormLogLevel())
}
func TestConnectionConfig_collectPoolMetrics_NilOTelConfig(t *testing.T) {
config := &ConnectionConfig{
DBType: Postgresql,
Host: "localhost",
Port: 5432,
Username: "test",
Password: "test",
DBName: "test",
OTelConfig: nil, // No OTel config
}
// Create a mock sql.DB - this won't actually connect
db, err := sql.Open("postgres", "host=invalid")
require.NoError(t, err)
defer db.Close()
// Should not panic and should return early
config.collectPoolMetrics(db)
// If we get here without panic, the nil check worked
}
func TestConnectionConfig_collectPoolMetrics_MetricsDisabled(t *testing.T) {
// OTel config with only tracing enabled (no MeterProvider = metrics disabled)
otelConfig := pkgotel.NewConfig("test").
WithTracerProvider(noopt.NewTracerProvider())
config := &ConnectionConfig{
DBType: Postgresql,
Host: "localhost",
Port: 5432,
Username: "test",
Password: "test",
DBName: "test",
OTelConfig: otelConfig,
}
// Create a mock sql.DB
db, err := sql.Open("postgres", "host=invalid")
require.NoError(t, err)
defer db.Close()
// Should return early when metrics are disabled
config.collectPoolMetrics(db)
// If we get here without panic, the metrics disabled check worked
}
func TestConnectionConfig_collectPoolMetrics_WithValidConfig(t *testing.T) {
// OTel config with metrics enabled (using noop MeterProvider for testing)
otelConfig := pkgotel.NewConfig("test-metrics").
WithMeterProvider(noopm.NewMeterProvider())
config := &ConnectionConfig{
DBType: Postgresql,
Host: "localhost",
Port: 5432,
Username: "test",
Password: "test",
DBName: "test",
OTelConfig: otelConfig,
}
// Create a mock sql.DB
db, err := sql.Open("postgres", "host=invalid")
require.NoError(t, err)
defer db.Close()
// Should successfully register metrics callbacks
config.collectPoolMetrics(db)
// If we get here, metrics were collected successfully
}
// TestConnectionConfig_installOTelCallbacks tests removed
// The uptrace otelgorm plugin is now used instead of custom callbacks
func TestConnectionConfig_Pool_InvalidDbType(t *testing.T) {
config := &ConnectionConfig{
DBType: "invalid-db-type",
Host: "localhost",
Port: 5432,
Username: "test",
Password: "test",
DBName: "test",
Timeout: 5 * time.Second,
MaxIdleConns: 5,
MaxOpenConns: 10,
}
_, err := config.Pool()
assert.Error(t, err)
assert.Contains(t, err.Error(), "unsupported database type")
}
func TestConnectionConfig_Pool_ConnectionFailure(t *testing.T) {
config := &ConnectionConfig{
DBType: Postgresql,
Host: "invalid-host-that-does-not-exist.local",
Port: 5432,
Username: "test",
Password: "test",
DBName: "test",
Timeout: 1 * time.Second,
MaxIdleConns: 5,
MaxOpenConns: 10,
}
_, err := config.Pool()
assert.Error(t, err)
// The error should be from the connection attempt
}
func TestConnectionConfig_Pool_EmptyDSN(t *testing.T) {
config := &ConnectionConfig{
DBType: "",
Host: "",
Port: 0,
Username: "",
Password: "",
DBName: "",
Timeout: 5 * time.Second,
MaxIdleConns: 5,
MaxOpenConns: 10,
}
_, err := config.Pool()
assert.Error(t, err)
}
func TestRedactedDsn_MasksPassword(t *testing.T) {
cfg := ConnectionConfig{
Host: "localhost", Port: 5432, Username: "admin",
Password: "supersecret", DBName: "testdb", DBType: Postgresql,
}
redacted := cfg.RedactedDsn()
assert.Contains(t, redacted, "***")
assert.NotContains(t, redacted, "supersecret")
}
func TestEffectiveSSLMode_DefaultsToRequire(t *testing.T) {
cfg := ConnectionConfig{}
assert.Equal(t, "require", cfg.effectiveSSLMode())
}
func TestConnectionConfig_SQLDB_ConnectionFailure(t *testing.T) {
config := &ConnectionConfig{
DBType: Postgresql,
Host: "invalid-host.local",
Port: 5432,
Username: "test",
Password: "test",
DBName: "test",
Timeout: 1 * time.Second,
MaxIdleConns: 5,
MaxOpenConns: 10,
}
// SQLDB() calls Pool() internally, which will fail to connect
db, err := config.SQLDB()
assert.Error(t, err)
assert.Nil(t, db)
// Should get a connection error
}