-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers_test.go
443 lines (389 loc) · 10.5 KB
/
helpers_test.go
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package main
import (
"bytes"
"context"
"errors"
"io"
"log/slog"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
)
// MockPgxPool mocks pgxpool.Pool for testing
type MockPgxPool struct {
PingFunc func(ctx context.Context) error
CloseFunc func()
}
func (m *MockPgxPool) Ping(ctx context.Context) error {
if m.PingFunc != nil {
return m.PingFunc(ctx)
}
return nil
}
func (m *MockPgxPool) Close() {
if m.CloseFunc != nil {
m.CloseFunc()
}
}
func TestSetupDatabase_NoDatabaseURL(t *testing.T) {
ctx := context.Background()
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
// Unset DATABASE_URL
os.Setenv("DATABASE_URL", "")
dbconn, err := setupDatabase(ctx, logger)
if err == nil {
t.Fatal("Expected error when DATABASE_URL is not set, got nil")
}
expectedErr := "DATABASE_URL environment variable is not set"
if err.Error() != expectedErr {
t.Fatalf("Expected error '%s', got '%v'", expectedErr, err)
}
if dbconn != nil {
t.Fatal("Expected dbconn to be nil when error occurs")
}
}
func TestSetupDatabase_PoolConfigError(t *testing.T) {
ctx := context.Background()
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
// Set DATABASE_URL to some value
os.Setenv("DATABASE_URL", "lol")
// Override PoolConfigFunc to return an error
originalPoolConfigFunc := PoolConfigFunc
defer func() { PoolConfigFunc = originalPoolConfigFunc }()
PoolConfigFunc = func(dbURL *string, logger *slog.Logger) (*pgxpool.Config, error) {
return nil, errors.New("mock PoolConfig error")
}
dbconn, err := setupDatabase(ctx, logger)
if err == nil {
t.Fatal("Expected error when PoolConfig returns an error, got nil")
}
expectedErr := "failed to create pool config: mock PoolConfig error"
if err.Error() != expectedErr {
t.Fatalf("Expected error '%s', got '%v'", expectedErr, err)
}
if dbconn != nil {
t.Fatal("Expected dbconn to be nil when error occurs")
}
}
func TestSetupDatabase_NewWithConfigFails(t *testing.T) {
ctx := context.Background()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
// Set DATABASE_URL to some value
os.Setenv("DATABASE_URL", "postgres://user:pass@localhost/dbname")
// Override PoolConfigFunc to return a valid config
originalPoolConfigFunc := PoolConfigFunc
defer func() { PoolConfigFunc = originalPoolConfigFunc }()
PoolConfigFunc = func(dbURL *string, logger *slog.Logger) (*pgxpool.Config, error) {
return &pgxpool.Config{}, nil
}
// Override NewWithConfigFunc to return an error
originalNewWithConfigFunc := NewWithConfigFunc
defer func() { NewWithConfigFunc = originalNewWithConfigFunc }()
attempts := 0
NewWithConfigFunc = func(ctx context.Context, config *pgxpool.Config) (*pgxpool.Pool, error) {
attempts++
return nil, errors.New("mock NewWithConfig error")
}
dbconn, err := setupDatabase(ctx, logger)
if err == nil {
t.Fatal("Expected error when NewWithConfig fails, got nil")
}
expectedErr := "unable to connect to database after 3 attempts: mock NewWithConfig error"
if err.Error() != expectedErr {
t.Fatalf("Expected error '%s', got '%v'", expectedErr, err)
}
if dbconn != nil {
t.Fatal("Expected dbconn to be nil when error occurs")
}
if attempts != 3 {
t.Fatalf("Expected 3 attempts, got %d", attempts)
}
}
func TestCreateConfigDirTwo(t *testing.T) {
tests := []struct {
name string
dir string
setup func()
wantErr bool
}{
{
name: "Create new directory",
dir: "testdata/config",
setup: func() {
// No setup needed for this test case
},
wantErr: false,
},
{
name: "Create existing directory",
dir: "testdata/existing",
setup: func() {
os.MkdirAll("testdata/existing", 0o700) // Create the directory beforehand
},
wantErr: false,
},
{
name: "Error creating main directory",
dir: "testdata/error-main",
setup: func() {
// Simulate an error by creating a file with the same name
os.WriteFile("testdata/error-main", []byte{}, 0o600)
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Setup the test case
tt.setup()
defer os.RemoveAll(tt.dir)
// Attempt to create the directory
err := createConfigDir(tt.dir)
if (err != nil) != tt.wantErr {
t.Errorf("os.MkdirAll() error = %v, wantErr %v", err, tt.wantErr)
}
// Check permissions if no error is expected
if !tt.wantErr {
info, err := os.Stat(tt.dir)
if err != nil {
t.Errorf("Failed to get directory info: %v", err)
} else if info.Mode().Perm() != 0o700 {
t.Errorf("Incorrect permissions: got %v, want %v", info.Mode().Perm(), 0o700)
}
}
// Clean up
os.RemoveAll(tt.dir)
})
}
}
func TestExpandSNIName(t *testing.T) {
tests := []struct {
name string
hostname string
expandSNIName func(ctx context.Context, hostname string) (string, bool)
expectedSNI string
expectedLog string
}{
{
name: "Successful expansion",
hostname: "example.com",
expandSNIName: func(ctx context.Context, hostname string) (string, bool) {
return "expanded.example.com", true
},
expectedSNI: "expanded.example.com",
expectedLog: "",
},
{
name: "Failed expansion",
hostname: "example.com",
expandSNIName: func(ctx context.Context, hostname string) (string, bool) {
return "", false
},
expectedSNI: "",
expectedLog: "error expanding SNI name",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
mockClient := &MockTailscaleClient{
ExpandSNINameFunc: tt.expandSNIName,
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
// Temporarily set the hostname variable
hostname = &tt.hostname
// Capture log output
var logOutput io.Writer
if tt.expectedLog != "" {
logOutput = &bytes.Buffer{}
logger = slog.New(slog.NewTextHandler(logOutput, nil))
}
sni := expandSNIName(ctx, mockClient, logger)
if sni != tt.expectedSNI {
t.Errorf("Expected SNI '%s', got '%s'", tt.expectedSNI, sni)
}
if tt.expectedLog != "" {
logStr := logOutput.(*bytes.Buffer).String()
if !strings.Contains(logStr, tt.expectedLog) {
t.Errorf("Expected log to contain '%s', got '%s'", tt.expectedLog, logStr)
}
}
})
}
}
func TestEnvOr(t *testing.T) {
tests := []struct {
name string
envKey string
envValue string
defaultVal string
expected string
}{
{
name: "Environment variable set",
envKey: "TEST_ENV",
envValue: "value_from_env",
defaultVal: "default_value",
expected: "value_from_env",
},
{
name: "Environment variable not set",
envKey: "TEST_ENV",
envValue: "",
defaultVal: "default_value",
expected: "default_value",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Set up the environment variable
if tt.envValue != "" {
os.Setenv(tt.envKey, tt.envValue)
} else {
os.Unsetenv(tt.envKey)
}
// Call the function
result := envOr(tt.envKey, tt.defaultVal)
// Check the result
if result != tt.expected {
t.Errorf("envOr() = %v, want %v", result, tt.expected)
}
// Clean up the environment variable
os.Unsetenv(tt.envKey)
})
}
}
func TestNewLogger(t *testing.T) {
tests := []struct {
name string
logLevel slog.Level
logFunc func(logger *slog.Logger)
expectMsg string
}{
{
name: "Debug level",
logLevel: slog.LevelDebug,
logFunc: func(logger *slog.Logger) {
logger.Debug("debug message")
},
expectMsg: "debug message",
},
{
name: "Info level",
logLevel: slog.LevelInfo,
logFunc: func(logger *slog.Logger) {
logger.Info("info message")
},
expectMsg: "info message",
},
{
name: "Warn level",
logLevel: slog.LevelWarn,
logFunc: func(logger *slog.Logger) {
logger.Warn("warn message")
},
expectMsg: "warn message",
},
{
name: "Error level",
logLevel: slog.LevelError,
logFunc: func(logger *slog.Logger) {
logger.Error("error message")
},
expectMsg: "error message",
},
{
name: "Debug log doesn't appear in Info level",
logLevel: slog.LevelInfo,
logFunc: func(logger *slog.Logger) {
logger.Debug("debug message")
},
expectMsg: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
logger := newLogger(&buf, &tt.logLevel)
tt.logFunc(logger)
if tt.expectMsg != "" && !strings.Contains(buf.String(), tt.expectMsg) {
t.Errorf("Expected log output to contain '%s', got %v", tt.expectMsg, buf.String())
} else if tt.expectMsg == "" && buf.Len() != 0 {
t.Errorf("Expected no log output, got %v", buf.String())
}
})
}
}
func TestSetupLogger(t *testing.T) {
tests := []struct {
name string
debug bool
expectedLevel slog.Level
logFunc func(logger *slog.Logger)
expectMsg string
}{
{
name: "Debug mode enabled",
debug: true,
expectedLevel: slog.LevelDebug,
logFunc: func(logger *slog.Logger) {
logger.Debug("debug message")
},
expectMsg: "debug message",
},
{
name: "Debug mode disabled",
debug: false,
expectedLevel: slog.LevelInfo, // Assuming default log level is Info
logFunc: func(logger *slog.Logger) {
logger.Info("info message")
},
expectMsg: "info message",
},
{
name: "Debug log doesn't appear in Info level",
debug: false,
expectedLevel: slog.LevelInfo,
logFunc: func(logger *slog.Logger) {
logger.Debug("debug message")
},
expectMsg: "",
},
{
name: "Info log appears in Debug level",
debug: true,
expectedLevel: slog.LevelDebug,
logFunc: func(logger *slog.Logger) {
logger.Info("info message")
},
expectMsg: "info message",
},
{
name: "Error log appears in Info level",
debug: false,
expectedLevel: slog.LevelInfo,
logFunc: func(logger *slog.Logger) {
logger.Error("error message")
},
expectMsg: "error message",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Temporarily set the debug variable
debug = &tt.debug
// Capture log output
var buf bytes.Buffer
logger := newLogger(&buf, &tt.expectedLevel)
// Perform the log function
tt.logFunc(logger)
// Check the log output
if tt.expectMsg != "" && !strings.Contains(buf.String(), tt.expectMsg) {
t.Errorf("Expected log output to contain '%s', got %v", tt.expectMsg, buf.String())
} else if tt.expectMsg == "" && buf.Len() != 0 {
t.Errorf("Expected no log output, got %v", buf.String())
}
})
}
}