-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathe2e_test.go
More file actions
530 lines (460 loc) · 12.9 KB
/
Copy pathe2e_test.go
File metadata and controls
530 lines (460 loc) · 12.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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// Package main provides end-to-end tests for Caddyshack.
// These tests require a running Caddy instance and are tagged with "e2e".
// Run with: go test -tags=e2e ./...
//
//go:build e2e
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/djedi/caddyshack/internal/caddy"
)
// These tests require:
// 1. A running Caddy instance with Admin API on localhost:2019
// 2. A writable Caddyfile path
//
// Run with: docker compose -f docker-compose.dev.yml up -d caddy
// Then: go test -tags=e2e -v ./...
const (
testCaddyAdminAPI = "http://localhost:2019"
testTimeout = 30 * time.Second
)
// TestCaddyAdminAPI_Integration tests the Caddy Admin API client with a real Caddy instance.
func TestCaddyAdminAPI_Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping e2e test in short mode")
}
client := caddy.NewAdminClient(testCaddyAdminAPI)
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
// Test Ping
t.Run("Ping", func(t *testing.T) {
ok, err := client.Ping(ctx)
if err != nil {
t.Fatalf("Ping failed: %v (is Caddy running?)", err)
}
if !ok {
t.Error("Ping returned false")
}
})
// Test GetStatus
t.Run("GetStatus", func(t *testing.T) {
status, err := client.GetStatus(ctx)
if err != nil {
t.Fatalf("GetStatus failed: %v", err)
}
if !status.Running {
t.Error("Caddy should be running")
}
if status.Version == "" {
t.Error("Version should not be empty")
}
t.Logf("Caddy version: %s", status.Version)
})
// Test GetConfig
t.Run("GetConfig", func(t *testing.T) {
config, err := client.GetConfig(ctx)
if err != nil {
t.Fatalf("GetConfig failed: %v", err)
}
// Config should be valid JSON
var js json.RawMessage
if err := json.Unmarshal(config, &js); err != nil {
t.Errorf("Config is not valid JSON: %v", err)
}
})
}
// TestCaddyAdminAPI_ValidateConfig tests config validation with the Caddy Admin API.
func TestCaddyAdminAPI_ValidateConfig(t *testing.T) {
if testing.Short() {
t.Skip("Skipping e2e test in short mode")
}
client := caddy.NewAdminClient(testCaddyAdminAPI)
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
// First check if Caddy is available
ok, err := client.Ping(ctx)
if err != nil || !ok {
t.Skip("Caddy not available, skipping test")
}
tests := []struct {
name string
config string
expectError bool
}{
{
name: "valid_simple_reverse_proxy",
config: `example.com {
reverse_proxy localhost:8080
}
`,
expectError: false,
},
{
name: "valid_static_site",
config: `static.example.com {
root * /var/www/html
file_server
}
`,
expectError: false,
},
{
name: "valid_redirect",
config: `old.example.com {
redir https://new.example.com{uri} 301
}
`,
expectError: false,
},
{
name: "valid_with_global_options",
config: `{
email admin@example.com
}
example.com {
reverse_proxy localhost:8080
}
`,
expectError: false,
},
{
name: "invalid_unclosed_block",
config: `example.com {`,
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := client.ValidateConfig(ctx, tt.config)
if tt.expectError && err == nil {
t.Error("Expected validation error, got nil")
}
if !tt.expectError && err != nil {
t.Errorf("Unexpected validation error: %v", err)
}
})
}
}
// TestCaddyAdminAPI_ReloadConfig tests config reload with the Caddy Admin API.
func TestCaddyAdminAPI_ReloadConfig(t *testing.T) {
if testing.Short() {
t.Skip("Skipping e2e test in short mode")
}
client := caddy.NewAdminClient(testCaddyAdminAPI)
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
// First check if Caddy is available
ok, err := client.Ping(ctx)
if err != nil || !ok {
t.Skip("Caddy not available, skipping test")
}
// Get current config to restore later
originalConfig, err := client.GetConfig(ctx)
if err != nil {
t.Fatalf("Failed to get original config: %v", err)
}
// Test reload with a simple valid config
testConfig := `localhost:9999 {
respond "Test configuration"
}
`
err = client.Reload(ctx, testConfig)
if err != nil {
t.Fatalf("Reload failed: %v", err)
}
// Verify the new config is active by checking the config endpoint
newConfig, err := client.GetConfig(ctx)
if err != nil {
t.Fatalf("Failed to get new config: %v", err)
}
// Config should have changed
if bytes.Equal(originalConfig, newConfig) {
t.Error("Config should have changed after reload")
}
// Restore original config (best effort)
t.Cleanup(func() {
// Convert JSON config back to Caddyfile format is complex,
// so we just reload with an empty config for cleanup
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cleanupCancel()
// Use a minimal config for cleanup
_ = client.Reload(cleanupCtx, "")
})
}
// TestE2E_SiteLifecycle tests the full lifecycle of a site through the Caddyshack API.
// This test requires both Caddyshack and Caddy to be running.
func TestE2E_SiteLifecycle(t *testing.T) {
if testing.Short() {
t.Skip("Skipping e2e test in short mode")
}
// Check if Caddyshack is running
caddyshackURL := os.Getenv("CADDYSHACK_URL")
if caddyshackURL == "" {
caddyshackURL = "http://localhost:8080"
}
// Try to connect to Caddyshack
resp, err := http.Get(caddyshackURL + "/health")
if err != nil {
t.Skipf("Caddyshack not available at %s: %v", caddyshackURL, err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Skipf("Caddyshack health check failed: %d", resp.StatusCode)
}
t.Run("CreateSite", func(t *testing.T) {
// Test creating a site through the web interface
// This would require proper session handling for auth
t.Skip("Full web interface testing requires authentication setup")
})
}
// TestCaddyfileRoundtrip tests parsing and writing Caddyfiles.
func TestCaddyfileRoundtrip(t *testing.T) {
if testing.Short() {
t.Skip("Skipping e2e test in short mode")
}
tempDir := t.TempDir()
caddyfilePath := filepath.Join(tempDir, "Caddyfile")
originalContent := `{
email admin@example.com
}
(common) {
encode gzip
header X-Frame-Options DENY
}
example.com {
import common
reverse_proxy localhost:8080
}
static.example.com {
root * /var/www/html
file_server
}
old.example.com {
redir https://new.example.com{uri} 301
}
`
// Write original file
if err := os.WriteFile(caddyfilePath, []byte(originalContent), 0644); err != nil {
t.Fatalf("Failed to write Caddyfile: %v", err)
}
// Read and parse
reader := caddy.NewReader(caddyfilePath)
content, err := reader.Read()
if err != nil {
t.Fatalf("Failed to read Caddyfile: %v", err)
}
parser := caddy.NewParser(content)
caddyfile, err := parser.ParseAll()
if err != nil {
t.Fatalf("Failed to parse Caddyfile: %v", err)
}
// Verify parsed content
if len(caddyfile.Sites) != 3 {
t.Errorf("Expected 3 sites, got %d", len(caddyfile.Sites))
}
if len(caddyfile.Snippets) != 1 {
t.Errorf("Expected 1 snippet, got %d", len(caddyfile.Snippets))
}
if caddyfile.GlobalOptions.Email != "admin@example.com" {
t.Errorf("Expected email 'admin@example.com', got %q", caddyfile.GlobalOptions.Email)
}
// Write back
writer := caddy.NewWriter()
newContent := writer.WriteCaddyfile(caddyfile)
// Write to new file
newPath := filepath.Join(tempDir, "Caddyfile.new")
if err := os.WriteFile(newPath, []byte(newContent), 0644); err != nil {
t.Fatalf("Failed to write new Caddyfile: %v", err)
}
// Parse the new file
reader2 := caddy.NewReader(newPath)
content2, err := reader2.Read()
if err != nil {
t.Fatalf("Failed to read new Caddyfile: %v", err)
}
parser2 := caddy.NewParser(content2)
caddyfile2, err := parser2.ParseAll()
if err != nil {
t.Fatalf("Failed to parse new Caddyfile: %v", err)
}
// Verify roundtrip preserves structure
if len(caddyfile2.Sites) != len(caddyfile.Sites) {
t.Errorf("Site count mismatch: %d vs %d", len(caddyfile2.Sites), len(caddyfile.Sites))
}
if len(caddyfile2.Snippets) != len(caddyfile.Snippets) {
t.Errorf("Snippet count mismatch: %d vs %d", len(caddyfile2.Snippets), len(caddyfile.Snippets))
}
if caddyfile2.GlobalOptions.Email != caddyfile.GlobalOptions.Email {
t.Errorf("Email mismatch: %q vs %q", caddyfile2.GlobalOptions.Email, caddyfile.GlobalOptions.Email)
}
}
// TestCaddyValidator_Integration tests the validator with the real Caddy binary.
func TestCaddyValidator_Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping e2e test in short mode")
}
// Check if caddy binary is available
validator := caddy.NewValidator()
tempDir := t.TempDir()
tests := []struct {
name string
content string
expectError bool
}{
{
name: "valid_reverse_proxy",
content: `localhost:8080 {
reverse_proxy localhost:9090
}
`,
expectError: false,
},
{
name: "valid_file_server",
content: `localhost:8080 {
root * /tmp
file_server
}
`,
expectError: false,
},
{
name: "invalid_syntax",
content: `localhost:8080 {`,
expectError: true,
},
{
name: "invalid_directive",
content: `localhost:8080 {
unknown_directive
}
`,
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
caddyfilePath := filepath.Join(tempDir, "Caddyfile_"+tt.name)
if err := os.WriteFile(caddyfilePath, []byte(tt.content), 0644); err != nil {
t.Fatalf("Failed to write Caddyfile: %v", err)
}
result, err := validator.ValidateContent(tt.content)
if tt.expectError {
if err == nil && result.Valid {
t.Error("Expected validation error, got valid result")
}
} else {
if err != nil {
// Caddy might not be available
if strings.Contains(err.Error(), "executable file not found") {
t.Skip("caddy binary not available")
}
t.Errorf("Unexpected error: %v", err)
}
if !result.Valid {
t.Errorf("Expected valid result, got: %v", result.Errors)
}
}
})
}
}
// TestHTTPHandlers_Integration tests HTTP handlers with a test server.
func TestHTTPHandlers_Integration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping e2e test in short mode")
}
// This test would start the full Caddyshack server
// and test HTTP endpoints
t.Skip("Full HTTP handler integration test requires server setup")
}
// Helper function to make authenticated requests to Caddyshack
func makeAuthRequest(t *testing.T, method, url string, body io.Reader, username, password string) *http.Response {
t.Helper()
req, err := http.NewRequest(method, url, body)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
if username != "" && password != "" {
req.SetBasicAuth(username, password)
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
return resp
}
// TestCaddyIntegration_FullFlow tests a complete flow with Caddy.
func TestCaddyIntegration_FullFlow(t *testing.T) {
if testing.Short() {
t.Skip("Skipping e2e test in short mode")
}
client := caddy.NewAdminClient(testCaddyAdminAPI)
ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
defer cancel()
// Check if Caddy is available
ok, err := client.Ping(ctx)
if err != nil || !ok {
t.Skip("Caddy not available, skipping test")
}
// Step 1: Create a new Caddyfile
tempDir := t.TempDir()
caddyfilePath := filepath.Join(tempDir, "Caddyfile")
// Step 2: Write initial config
initialConfig := `localhost:19999 {
respond "Hello from test"
}
`
if err := os.WriteFile(caddyfilePath, []byte(initialConfig), 0644); err != nil {
t.Fatalf("Failed to write Caddyfile: %v", err)
}
// Step 3: Load and reload through Admin API
err = client.Reload(ctx, initialConfig)
if err != nil {
t.Fatalf("Failed to reload initial config: %v", err)
}
// Step 4: Verify the server is responding
time.Sleep(500 * time.Millisecond) // Give Caddy time to apply config
resp, err := http.Get("http://localhost:19999")
if err != nil {
t.Logf("Note: localhost:19999 not reachable (expected in some environments): %v", err)
} else {
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if !strings.Contains(string(body), "Hello from test") {
t.Errorf("Unexpected response body: %s", string(body))
}
}
// Step 5: Update config
updatedConfig := `localhost:19999 {
respond "Updated response"
}
`
err = client.Reload(ctx, updatedConfig)
if err != nil {
t.Fatalf("Failed to reload updated config: %v", err)
}
// Step 6: Verify update
time.Sleep(500 * time.Millisecond)
resp2, err := http.Get("http://localhost:19999")
if err != nil {
t.Logf("Note: localhost:19999 not reachable after update: %v", err)
} else {
defer resp2.Body.Close()
body, _ := io.ReadAll(resp2.Body)
if !strings.Contains(string(body), "Updated response") {
t.Errorf("Unexpected response body after update: %s", string(body))
}
}
t.Log("Full flow test completed successfully")
}