-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathintegration_test.go
More file actions
810 lines (669 loc) · 26.2 KB
/
integration_test.go
File metadata and controls
810 lines (669 loc) · 26.2 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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"testing"
"time"
"github.com/spf13/viper"
"github.com/timescale/tiger-cli/internal/tiger/api"
"github.com/timescale/tiger-cli/internal/tiger/config"
)
// setupIntegrationTest sets up isolated test environment with temporary config directory
func setupIntegrationTest(t *testing.T) string {
t.Helper()
// Create temporary directory for test config
tmpDir, err := os.MkdirTemp("", "tiger-integration-test-*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
// Set temporary config directory
os.Setenv("TIGER_CONFIG_DIR", tmpDir)
// Reset global config and viper to ensure test isolation
config.ResetGlobalConfig()
// Re-establish viper environment configuration after reset
viper.SetEnvPrefix("TIGER")
viper.AutomaticEnv()
// Set API URL in temporary config if integration URL is provided
if apiURL := os.Getenv("TIGER_API_URL_INTEGRATION"); apiURL != "" {
// Use a simple command execution without the full executeIntegrationCommand wrapper
// to avoid circular dependencies during setup
rootCmd := buildRootCmd()
rootCmd.SetArgs([]string{"config", "set", "api_url", apiURL})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Failed to set integration API URL during setup: %v", err)
}
}
t.Cleanup(func() {
// Reset global config and viper first
config.ResetGlobalConfig()
// Clean up environment variable BEFORE cleaning up file system
os.Unsetenv("TIGER_CONFIG_DIR")
// Then clean up file system
os.RemoveAll(tmpDir)
})
return tmpDir
}
// executeIntegrationCommand executes a CLI command for integration testing
func executeIntegrationCommand(args ...string) (string, error) {
// Reset both global config and viper before each command execution
// This ensures fresh config loading with proper flag precedence
config.ResetGlobalConfig()
// Re-establish viper environment configuration after reset
viper.SetEnvPrefix("TIGER")
viper.AutomaticEnv()
// Use buildRootCmd() to get a complete root command with all flags and subcommands
testRoot := buildRootCmd()
buf := new(bytes.Buffer)
testRoot.SetOut(buf)
testRoot.SetErr(buf)
testRoot.SetArgs(args)
err := testRoot.Execute()
return buf.String(), err
}
// TestServiceLifecycleIntegration tests the complete authentication and service lifecycle:
// login -> whoami -> create -> describe -> update-password -> delete -> logout
func TestServiceLifecycleIntegration(t *testing.T) {
// Check for required environment variables
publicKey := os.Getenv("TIGER_PUBLIC_KEY_INTEGRATION")
secretKey := os.Getenv("TIGER_SECRET_KEY_INTEGRATION")
projectID := os.Getenv("TIGER_PROJECT_ID_INTEGRATION")
if publicKey == "" || secretKey == "" || projectID == "" {
t.Skip("Skipping integration test: TIGER_PUBLIC_KEY_INTEGRATION, TIGER_SECRET_KEY_INTEGRATION, and TIGER_PROJECT_ID_INTEGRATION must be set")
}
// Set up isolated test environment with temporary config directory
tmpDir := setupIntegrationTest(t)
t.Logf("Using temporary config directory: %s", tmpDir)
// Generate unique service name to avoid conflicts
serviceName := fmt.Sprintf("integration-test-%d", time.Now().Unix())
var serviceID string
var deletedServiceID string // Keep track of deleted service for verification
// Always logout at the end to clean up credentials
defer func() {
t.Logf("Cleaning up authentication")
_, err := executeIntegrationCommand("auth", "logout")
if err != nil {
t.Logf("Warning: Failed to logout: %v", err)
}
}()
// Cleanup function to ensure service is deleted even if test fails
defer func() {
if serviceID != "" {
t.Logf("Cleaning up service: %s", serviceID)
// Best effort cleanup - don't fail the test if cleanup fails
_, err := executeIntegrationCommand(
"service", "delete", serviceID,
"--confirm",
"--wait-timeout", "5m",
)
if err != nil {
t.Logf("Warning: Failed to cleanup service %s: %v", serviceID, err)
}
}
}()
t.Run("Login", func(t *testing.T) {
t.Logf("Logging in with public key: %s", publicKey[:8]+"...") // Only show first 8 chars
output, err := executeIntegrationCommand(
"auth", "login",
"--public-key", publicKey,
"--secret-key", secretKey,
"--project-id", projectID,
)
if err != nil {
t.Fatalf("Login failed: %v\nOutput: %s", err, output)
}
// Verify login success message
if !strings.Contains(output, "Successfully logged in") && !strings.Contains(output, "Logged in") {
t.Errorf("Login output: %s", output)
}
t.Logf("Login successful")
})
t.Run("WhoAmI", func(t *testing.T) {
t.Logf("Verifying authentication status")
output, err := executeIntegrationCommand("auth", "whoami")
if err != nil {
t.Fatalf("WhoAmI failed: %v\nOutput: %s", err, output)
}
// Should not say "Not logged in"
if strings.Contains(output, "Not logged in") {
t.Errorf("Expected to be logged in, but got: %s", output)
}
t.Logf("Current authentication status: %s", strings.TrimSpace(output))
})
t.Run("CreateService", func(t *testing.T) {
t.Logf("Creating service: %s", serviceName)
output, err := executeIntegrationCommand(
"service", "create",
"--name", serviceName,
"--wait-timeout", "15m", // Longer timeout for integration tests
"--no-set-default", // Don't modify user's default service
"--output", "json", // Use JSON for easier parsing
)
if err != nil {
t.Fatalf("Service creation failed: %v\nOutput: %s", err, output)
}
// Extract service ID from JSON output
extractedServiceID := extractServiceIDFromCreateOutput(t, output)
if extractedServiceID == "" {
t.Fatalf("Could not extract service ID from create output: %s", output)
}
serviceID = extractedServiceID
t.Logf("Created service with ID: %s", serviceID)
})
t.Run("ListServices", func(t *testing.T) {
if serviceID == "" {
t.Skip("No service ID available from create test")
}
t.Logf("Listing services to verify creation")
output, err := executeIntegrationCommand(
"service", "list",
"--output", "json",
)
if err != nil {
t.Fatalf("Service list failed: %v\nOutput: %s", err, output)
}
// Verify our service appears in the list
if !strings.Contains(output, serviceID) {
t.Errorf("Service ID %s not found in service list output", serviceID)
}
if !strings.Contains(output, serviceName) {
t.Errorf("Service name %s not found in service list output", serviceName)
}
})
t.Run("DescribeService", func(t *testing.T) {
if serviceID == "" {
t.Skip("No service ID available from create test")
}
t.Logf("Describing service: %s", serviceID)
output, err := executeIntegrationCommand(
"service", "describe", serviceID,
"--output", "json",
)
t.Logf("Raw service describe output: %s", output)
if err != nil {
t.Fatalf("Service describe failed: %v\nOutput: %s", err, output)
}
// Parse JSON to verify service details
var service api.Service
if err := json.Unmarshal([]byte(output), &service); err != nil {
t.Fatalf("Failed to parse service JSON: %v\nOutput: %s", err, output)
}
// Verify service details
if service.ServiceId == nil || *service.ServiceId != serviceID {
t.Errorf("Expected service ID %s, got %v", serviceID, service.ServiceId)
}
if service.Name == nil || *service.Name != serviceName {
t.Errorf("Expected service name %s, got %v", serviceName, service.Name)
}
// Verify service has expected structure
if service.Endpoint == nil {
t.Error("Service endpoint should not be nil")
}
t.Logf("Service status: %v", service.Status)
})
t.Run("DatabasePsqlCommand_OriginalPassword", func(t *testing.T) {
if serviceID == "" {
t.Skip("No service ID available from create test")
}
t.Logf("Testing psql command with original password for service: %s", serviceID)
output, err := executeIntegrationCommand(
"db", "psql", serviceID,
"--", "-c", "SELECT 1 as original_password_test;",
)
if err != nil {
t.Fatalf("Database psql command with original password failed: %v\nOutput: %s", err, output)
}
// Verify we got expected output from SELECT 1
if !strings.Contains(output, "1") && !strings.Contains(output, "original_password_test") {
t.Errorf("psql command succeeded but output format unexpected - expected to contain '1' or 'original_password_test': %s", output)
}
t.Logf("✅ psql command with original password succeeded")
})
t.Run("UpdatePassword", func(t *testing.T) {
if serviceID == "" {
t.Skip("No service ID available from create test")
}
newPassword := fmt.Sprintf("integration-test-password-%d", time.Now().Unix())
t.Logf("Updating password for service: %s", serviceID)
output, err := executeIntegrationCommand(
"service", "update-password", serviceID,
"--new-password", newPassword,
"--password-storage", "keychain", // Save to keychain for psql test
)
if err != nil {
t.Fatalf("Password update failed: %v\nOutput: %s", err, output)
}
// Verify success message
if !strings.Contains(output, "updated successfully") {
t.Errorf("Expected success message in output: %s", output)
}
})
t.Run("DatabaseConnectionString", func(t *testing.T) {
if serviceID == "" {
t.Skip("No service ID available from create test")
}
t.Logf("Getting connection string for service: %s", serviceID)
output, err := executeIntegrationCommand(
"db", "connection-string", serviceID,
)
if err != nil {
t.Fatalf("Connection string failed: %v\nOutput: %s", err, output)
}
// Verify connection string format
if !strings.HasPrefix(strings.TrimSpace(output), "postgresql://") {
t.Errorf("Expected PostgreSQL connection string, got: %s", output)
}
// Verify connection string contains expected components
if !strings.Contains(output, "sslmode=require") {
t.Errorf("Expected connection string to include sslmode=require: %s", output)
}
})
t.Run("DatabasePsqlCommand_UpdatedPassword", func(t *testing.T) {
if serviceID == "" {
t.Skip("No service ID available from create test")
}
t.Logf("Testing psql command with updated password for service: %s", serviceID)
output, err := executeIntegrationCommand(
"db", "psql", serviceID,
"--", "-c", "SELECT 1 as updated_password_test;",
)
if err != nil {
t.Fatalf("Database psql command with updated password failed: %v\nOutput: %s", err, output)
}
// Verify we got expected output from SELECT 1
if !strings.Contains(output, "1") && !strings.Contains(output, "updated_password_test") {
t.Errorf("psql command succeeded but output format unexpected - expected to contain '1' or 'updated_password_test': %s", output)
}
t.Logf("✅ psql command with updated password succeeded")
})
t.Run("DeleteService", func(t *testing.T) {
if serviceID == "" {
t.Skip("No service ID available for deletion")
}
t.Logf("Deleting service: %s", serviceID)
output, err := executeIntegrationCommand(
"service", "delete", serviceID,
"--confirm",
"--wait-timeout", "10m",
)
if err != nil {
t.Fatalf("Service deletion failed: %v\nOutput: %s", err, output)
}
// Verify deletion success message
if !strings.Contains(output, "deleted successfully") && !strings.Contains(output, "Deletion completed") && !strings.Contains(output, "successfully deleted") {
t.Errorf("Expected deletion success message in output: %s", output)
}
// Store serviceID for verification, then clear it so cleanup doesn't try to delete again
deletedServiceID = serviceID
serviceID = ""
})
t.Run("VerifyServiceDeleted", func(t *testing.T) {
if deletedServiceID == "" {
t.Skip("No deleted service ID available for verification")
}
t.Logf("Verifying service %s no longer exists", deletedServiceID)
// Try to describe the deleted service - should fail
output, err := executeIntegrationCommand(
"service", "describe", deletedServiceID,
)
// We expect this to fail since the service should be deleted
if err == nil {
t.Errorf("Expected service describe to fail for deleted service, but got output: %s", output)
}
// Check that error indicates service not found
if !strings.Contains(err.Error(), "not found") && !strings.Contains(err.Error(), "404") {
t.Errorf("Expected 'not found' error for deleted service, got: %v", err)
}
// Check that it returns the correct exit code (this should be required)
if exitErr, ok := err.(interface{ ExitCode() int }); ok {
if exitErr.ExitCode() != ExitServiceNotFound {
t.Errorf("Expected exit code %d for service not found, got %d", ExitServiceNotFound, exitErr.ExitCode())
}
} else {
t.Error("Expected exitCodeError with ExitServiceNotFound exit code for deleted service")
}
})
t.Run("Logout", func(t *testing.T) {
t.Logf("Logging out")
output, err := executeIntegrationCommand("auth", "logout")
if err != nil {
t.Fatalf("Logout failed: %v\nOutput: %s", err, output)
}
// Verify logout success message
if !strings.Contains(output, "Successfully logged out") && !strings.Contains(output, "Logged out") {
t.Errorf("Logout output: %s", output)
}
t.Logf("Logout successful")
})
t.Run("VerifyLoggedOut", func(t *testing.T) {
t.Logf("Verifying we're logged out")
output, err := executeIntegrationCommand("auth", "whoami")
// This should either fail or say "Not logged in"
if err == nil && !strings.Contains(output, "Not logged in") {
t.Errorf("Expected to be logged out, but whoami succeeded: %s", output)
}
t.Logf("Verified logged out status")
})
}
// extractServiceIDFromCreateOutput extracts the service ID from service create command output
func extractServiceIDFromCreateOutput(t *testing.T, output string) string {
t.Helper()
// Try to parse as JSON first (if --output json was used)
var service api.Service
if err := json.Unmarshal([]byte(output), &service); err == nil {
if service.ServiceId != nil {
return *service.ServiceId
}
}
// Fall back to regex extraction for text output
// Look for service ID pattern (svc- followed by alphanumeric characters)
serviceIDRegex := regexp.MustCompile(`svc-[a-zA-Z0-9]+`)
matches := serviceIDRegex.FindStringSubmatch(output)
if len(matches) > 0 {
return matches[0]
}
// Try to extract from structured output lines
lines := strings.Split(output, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.Contains(line, "Service ID") || strings.Contains(line, "service_id") {
// Extract ID from lines like "📋 Service ID: p7yqpiw7a8" or "service_id: svc-12345"
parts := strings.Split(line, ":")
if len(parts) >= 2 {
id := strings.TrimSpace(parts[1])
// Look for any service ID pattern (not just svc- prefix)
serviceIDRegex := regexp.MustCompile(`[a-zA-Z0-9]{8,}`)
if match := serviceIDRegex.FindString(id); match != "" {
return match
}
}
}
}
return ""
}
// TestServiceNotFound tests that commands requiring service ID fail with correct exit code for non-existent services
func TestServiceNotFound(t *testing.T) {
// Check for required environment variables
publicKey := os.Getenv("TIGER_PUBLIC_KEY_INTEGRATION")
secretKey := os.Getenv("TIGER_SECRET_KEY_INTEGRATION")
projectID := os.Getenv("TIGER_PROJECT_ID_INTEGRATION")
if publicKey == "" || secretKey == "" || projectID == "" {
t.Skip("Skipping service not found test: TIGER_PUBLIC_KEY_INTEGRATION, TIGER_SECRET_KEY_INTEGRATION, and TIGER_PROJECT_ID_INTEGRATION must be set")
}
// Set up isolated test environment with temporary config directory
tmpDir := setupIntegrationTest(t)
t.Logf("Using temporary config directory: %s", tmpDir)
// Always logout at the end to clean up credentials
defer func() {
t.Logf("Cleaning up authentication")
_, err := executeIntegrationCommand("auth", "logout")
if err != nil {
t.Logf("Warning: Failed to logout: %v", err)
}
}()
// Login first
output, err := executeIntegrationCommand(
"auth", "login",
"--public-key", publicKey,
"--secret-key", secretKey,
"--project-id", projectID,
)
if err != nil {
t.Fatalf("Login failed: %v\nOutput: %s", err, output)
}
t.Logf("Login successful for service not found tests")
// Use a definitely non-existent service ID
nonExistentServiceID := "nonexistent-service-12345"
// Table of commands that should fail with specific exit codes for non-existent services
testCases := []struct {
name string
args []string
expectedExitCode int
reason string
}{
{
name: "service describe",
args: []string{"service", "describe", nonExistentServiceID},
expectedExitCode: ExitServiceNotFound,
},
{
name: "service update-password",
args: []string{"service", "update-password", nonExistentServiceID, "--new-password", "test-password"},
expectedExitCode: ExitServiceNotFound,
},
{
name: "service delete",
args: []string{"service", "delete", nonExistentServiceID, "--confirm"},
expectedExitCode: ExitServiceNotFound,
},
{
name: "db connection-string",
args: []string{"db", "connection-string", nonExistentServiceID},
expectedExitCode: ExitServiceNotFound,
},
{
name: "db test-connection",
args: []string{"db", "test-connection", nonExistentServiceID},
expectedExitCode: ExitInvalidParameters,
reason: "maintains compatibility with PostgreSQL tooling conventions",
},
{
name: "db psql",
args: []string{"db", "psql", nonExistentServiceID, "--", "-c", "SELECT 1;"},
expectedExitCode: ExitServiceNotFound,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
output, err := executeIntegrationCommand(tc.args...)
if err == nil {
t.Errorf("Expected %s to fail for non-existent service, but got output: %s", tc.name, output)
return
}
// Verify error message contains "not found"
if !strings.Contains(err.Error(), "not found") {
t.Errorf("Expected 'not found' error message for %s, got: %v", tc.name, err)
}
// Verify correct exit code
if exitErr, ok := err.(interface{ ExitCode() int }); ok {
if exitErr.ExitCode() != tc.expectedExitCode {
t.Errorf("Expected exit code %d for %s, got %d", tc.expectedExitCode, tc.name, exitErr.ExitCode())
}
} else {
t.Errorf("Expected exitCodeError with exit code %d for %s", tc.expectedExitCode, tc.name)
}
reasonMsg := ""
if tc.reason != "" {
reasonMsg = fmt.Sprintf(" (%s)", tc.reason)
}
t.Logf("✅ %s correctly failed with exit code %d%s", tc.name, tc.expectedExitCode, reasonMsg)
})
}
}
// TestDatabaseCommandsIntegration tests database-related commands that don't require service creation
func TestDatabaseCommandsIntegration(t *testing.T) {
// Check for required environment variables
publicKey := os.Getenv("TIGER_PUBLIC_KEY_INTEGRATION")
secretKey := os.Getenv("TIGER_SECRET_KEY_INTEGRATION")
projectID := os.Getenv("TIGER_PROJECT_ID_INTEGRATION")
existingServiceID := os.Getenv("TIGER_EXISTING_SERVICE_ID_INTEGRATION") // Optional: use existing service
if publicKey == "" || secretKey == "" || projectID == "" {
t.Skip("Skipping integration test: TIGER_PUBLIC_KEY_INTEGRATION, TIGER_SECRET_KEY_INTEGRATION, and TIGER_PROJECT_ID_INTEGRATION must be set")
}
if existingServiceID == "" {
t.Skip("Skipping database integration test: TIGER_EXISTING_SERVICE_ID_INTEGRATION not set")
}
// Set up isolated test environment with temporary config directory
tmpDir := setupIntegrationTest(t)
t.Logf("Using temporary config directory: %s", tmpDir)
// Always logout at the end to clean up credentials
defer func() {
t.Logf("Cleaning up authentication")
_, err := executeIntegrationCommand("auth", "logout")
if err != nil {
t.Logf("Warning: Failed to logout: %v", err)
}
}()
t.Run("Login", func(t *testing.T) {
t.Logf("Logging in for database tests")
output, err := executeIntegrationCommand(
"auth", "login",
"--public-key", publicKey,
"--secret-key", secretKey,
"--project-id", projectID,
)
if err != nil {
t.Fatalf("Login failed: %v\nOutput: %s", err, output)
}
t.Logf("Login successful for database tests")
})
t.Run("DatabaseTestConnection", func(t *testing.T) {
t.Logf("Testing database connection for service: %s", existingServiceID)
output, err := executeIntegrationCommand(
"db", "test-connection", existingServiceID,
"--timeout", "30s",
)
// Note: This may fail if the database isn't fully ready or credentials aren't set up
// We log the result but don't fail the test since it depends on database state
if err != nil {
t.Logf("Database connection test failed (this may be expected): %v\nOutput: %s", err, output)
} else {
t.Logf("Database connection test succeeded: %s", output)
}
})
}
// TestAuthenticationErrorsIntegration tests that all commands requiring authentication
// properly handle authentication failures and return appropriate exit codes
func TestAuthenticationErrorsIntegration(t *testing.T) {
// Check if we have valid integration test credentials
publicKey := os.Getenv("TIGER_PUBLIC_KEY_INTEGRATION")
secretKey := os.Getenv("TIGER_SECRET_KEY_INTEGRATION")
projectID := os.Getenv("TIGER_PROJECT_ID_INTEGRATION")
if publicKey == "" || secretKey == "" || projectID == "" {
t.Skip("Skipping authentication error integration test: TIGER_PUBLIC_KEY_INTEGRATION, TIGER_SECRET_KEY_INTEGRATION, and TIGER_PROJECT_ID_INTEGRATION must be set")
}
// Set up isolated test environment with temporary config directory
tmpDir := setupIntegrationTest(t)
t.Logf("Using temporary config directory: %s", tmpDir)
// Make sure we're logged out (this should always succeed or be a no-op)
_, _ = executeIntegrationCommand("auth", "logout")
// Log in with invalid credentials to trigger authentication errors (401 response from server)
invalidPublicKey := "invalid-public-key"
invalidSecretKey := "invalid-secret-key"
// Login with invalid credentials (this should succeed locally but fail on API calls)
loginOutput, loginErr := executeIntegrationCommand("auth", "login",
"--public-key", invalidPublicKey,
"--secret-key", invalidSecretKey,
"--project-id", projectID)
if loginErr != nil {
t.Logf("Login with invalid credentials failed (expected): %s", loginOutput)
} else {
t.Fatalf("Cannot test authentication errors: login with invalid credentials succeeded: %v", loginErr)
}
// Test service commands that should return authentication errors
serviceCommands := []struct {
name string
args []string
}{
{
name: "service list",
args: []string{"service", "list", "--project-id", projectID},
},
{
name: "service describe",
args: []string{"service", "describe", "non-existent-service", "--project-id", projectID},
},
{
name: "service create",
args: []string{"service", "create", "--name", "test-service", "--project-id", projectID, "--no-wait"},
},
{
name: "service update-password",
args: []string{"service", "update-password", "non-existent-service", "--new-password", "test-pass", "--project-id", projectID},
},
{
name: "service delete",
args: []string{"service", "delete", "non-existent-service", "--confirm", "--project-id", projectID, "--no-wait"},
},
}
// Test db commands that should return authentication errors
dbCommands := []struct {
name string
args []string
}{
{
name: "db connection-string",
args: []string{"db", "connection-string", "non-existent-service", "--project-id", projectID},
},
{
name: "db connect",
args: []string{"db", "connect", "non-existent-service", "--project-id", projectID},
},
// Note: db test-connection follows pg_isready conventions, so it uses exit code 3 (ExitInvalidParameters)
// for authentication issues, not ExitAuthenticationError like other commands
{
name: "db test-connection",
args: []string{"db", "test-connection", "non-existent-service", "--project-id", projectID},
},
}
// Test all service commands
for _, tc := range serviceCommands {
t.Run(tc.name, func(t *testing.T) {
output, err := executeIntegrationCommand(tc.args...)
// Should fail with authentication error
if err == nil {
t.Errorf("Expected %s to fail with authentication error when using invalid API key, but got output: %s", tc.name, output)
return
}
// Check that it's an exitCodeError with ExitAuthenticationError
if exitErr, ok := err.(interface{ ExitCode() int }); ok {
if exitErr.ExitCode() != ExitAuthenticationError {
t.Errorf("Expected exit code %d (ExitAuthenticationError) for %s, got %d. Error: %s", ExitAuthenticationError, tc.name, exitErr.ExitCode(), err.Error())
} else {
t.Logf("✅ %s correctly failed with authentication error (exit code %d)", tc.name, ExitAuthenticationError)
}
} else {
t.Errorf("Expected exitCodeError with ExitAuthenticationError exit code for %s, got: %v", tc.name, err)
}
// Check error message contains authentication-related text
if !strings.Contains(err.Error(), "authentication") && !strings.Contains(err.Error(), "API key") {
t.Logf("Note: %s error message may be acceptable: %s", tc.name, err.Error())
}
})
}
// Test all db commands
for _, tc := range dbCommands {
t.Run(tc.name, func(t *testing.T) {
output, err := executeIntegrationCommand(tc.args...)
// Should fail with authentication error
if err == nil {
t.Errorf("Expected %s to fail with authentication error when using invalid API key, but got output: %s", tc.name, output)
return
}
// Check that it's an exitCodeError with the expected exit code
if exitErr, ok := err.(interface{ ExitCode() int }); ok {
expectedExitCode := ExitAuthenticationError
expectedDescription := "authentication error"
// db test-connection follows pg_isready conventions and uses exit code 3
if tc.name == "db test-connection" {
expectedExitCode = ExitInvalidParameters
expectedDescription = "invalid parameters (pg_isready convention)"
}
if exitErr.ExitCode() != expectedExitCode {
t.Errorf("Expected exit code %d (%s) for %s, got %d. Error: %s", expectedExitCode, expectedDescription, tc.name, exitErr.ExitCode(), err.Error())
} else {
t.Logf("✅ %s correctly failed with %s (exit code %d)", tc.name, expectedDescription, expectedExitCode)
}
} else {
t.Errorf("Expected exitCodeError for %s, got: %v", tc.name, err)
}
// Check error message contains authentication-related text
if !strings.Contains(err.Error(), "authentication") && !strings.Contains(err.Error(), "API key") {
t.Logf("Note: %s error message may be acceptable: %s", tc.name, err.Error())
}
})
}
}