-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathservice_test.go
More file actions
1828 lines (1568 loc) · 54.4 KB
/
service_test.go
File metadata and controls
1828 lines (1568 loc) · 54.4 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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
"github.com/timescale/tiger-cli/internal/tiger/api"
"github.com/timescale/tiger-cli/internal/tiger/config"
)
func setupServiceTest(t *testing.T) string {
t.Helper()
// Create temporary directory for test config
tmpDir, err := os.MkdirTemp("", "tiger-service-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()
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
}
func executeServiceCommand(args ...string) (string, error, *cobra.Command) {
// No need to reset any flags - we build fresh commands with local variables
// 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, testRoot
}
func TestServiceList_NoAuth(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and API URL
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication failure
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "", fmt.Errorf("not logged in")
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service list command
_, err, _ = executeServiceCommand("service", "list")
if err == nil {
t.Fatal("Expected error when not authenticated")
}
if !strings.Contains(err.Error(), "authentication required") {
t.Errorf("Expected authentication error, got: %v", err)
}
}
func TestOutputServices_JSON(t *testing.T) {
setupServiceTest(t)
// Create test services
services := createTestServices()
// Create test command
cmd := &cobra.Command{}
buf := new(bytes.Buffer)
cmd.SetOut(buf)
// Test JSON output
err := outputServices(cmd, services, "json", false)
if err != nil {
t.Fatalf("Failed to output JSON: %v", err)
}
// Verify JSON is valid
var result []api.Service
if err := json.Unmarshal(buf.Bytes(), &result); err != nil {
t.Fatalf("Invalid JSON output: %v", err)
}
if len(result) != len(services) {
t.Errorf("Expected %d services in JSON, got %d", len(services), len(result))
}
}
func TestOutputServices_YAML(t *testing.T) {
setupServiceTest(t)
// Create test services
services := createTestServices()
// Create test command
cmd := &cobra.Command{}
buf := new(bytes.Buffer)
cmd.SetOut(buf)
// Test YAML output
err := outputServices(cmd, services, "yaml", false)
if err != nil {
t.Fatalf("Failed to output YAML: %v", err)
}
// Verify YAML is valid
var result []api.Service
if err := yaml.Unmarshal(buf.Bytes(), &result); err != nil {
t.Fatalf("Invalid YAML output: %v", err)
}
if len(result) != len(services) {
t.Errorf("Expected %d services in YAML, got %d", len(services), len(result))
}
}
func TestOutputServices_Table(t *testing.T) {
setupServiceTest(t)
// Create test services
services := createTestServices()
// Create test command
cmd := &cobra.Command{}
buf := new(bytes.Buffer)
cmd.SetOut(buf)
// Test table output
err := outputServices(cmd, services, "table", false)
if err != nil {
t.Fatalf("Failed to output table: %v", err)
}
output := buf.String()
// Verify table contains headers
if !strings.Contains(output, "SERVICE ID") {
t.Error("Table output should contain SERVICE ID header")
}
if !strings.Contains(output, "NAME") {
t.Error("Table output should contain NAME header")
}
if !strings.Contains(output, "STATUS") {
t.Error("Table output should contain STATUS header")
}
// Verify table contains service data
if !strings.Contains(output, "test-service-1") {
t.Error("Table output should contain test service name")
}
}
func TestServiceFork_NoAuth(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and service ID
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
"service_id": "source-service-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication failure
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "", fmt.Errorf("not logged in")
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service fork command with required timing flag
_, err, _ = executeServiceCommand("service", "fork", "--now")
if err == nil {
t.Fatal("Expected error when not authenticated")
}
if !strings.Contains(err.Error(), "authentication required") {
t.Errorf("Expected authentication error, got: %v", err)
}
}
func TestServiceFork_NoSourceService(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID but no service ID
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication success
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "test-api-key", nil
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service fork command without providing service ID but with timing flag
_, err, _ = executeServiceCommand("service", "fork", "--now")
if err == nil {
t.Fatal("Expected error when no service ID provided")
}
if !strings.Contains(err.Error(), "service ID is required") {
t.Errorf("Expected service ID required error, got: %v", err)
}
}
func TestServiceFork_NoTimingFlag(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and service ID
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
"service_id": "source-service-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication success
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "test-api-key", nil
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service fork command without any timing flag
_, err, _ = executeServiceCommand("service", "fork", "source-service-123")
if err == nil {
t.Fatal("Expected error when no timing flag provided")
}
if !strings.Contains(err.Error(), "must specify --now, --last-snapshot or --to-timestamp") {
t.Errorf("Expected timing flag required error, got: %v", err)
}
}
func TestServiceFork_MultipleTiming(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and service ID
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
"service_id": "source-service-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication success
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "test-api-key", nil
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service fork command with multiple timing flags
_, err, _ = executeServiceCommand("service", "fork", "source-service-123", "--now", "--last-snapshot")
if err == nil {
t.Fatal("Expected error when multiple timing flags provided")
}
if !strings.Contains(err.Error(), "can only specify one of --now, --last-snapshot or --to-timestamp") {
t.Errorf("Expected multiple timing flags error, got: %v", err)
}
}
func TestServiceFork_InvalidTimestamp(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and service ID
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
"service_id": "source-service-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication success
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "test-api-key", nil
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service fork command with invalid timestamp
_, err, _ = executeServiceCommand("service", "fork", "source-service-123", "--to-timestamp", "invalid-timestamp")
if err == nil {
t.Fatal("Expected error when invalid timestamp provided")
}
if !strings.Contains(err.Error(), "invalid time format") {
t.Errorf("Expected invalid timestamp error, got: %v", err)
}
}
func TestServiceFork_CPUMemoryValidation(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and service ID
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
"service_id": "source-service-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication success
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "test-api-key", nil
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Test with invalid CPU/memory combination (this would fail at API call stage)
// Since we don't want to make real API calls, we expect the command to fail during validation
_, err, _ = executeServiceCommand("service", "fork", "source-service-123", "--now", "--cpu", "999", "--memory", "1")
// This test is mainly to ensure the flags are parsed correctly
// The actual validation happens later in the process when we have source service details
// So we expect either a validation error or an API connection error
if err == nil {
t.Fatal("Expected some error due to invalid CPU/memory or API connection")
}
// We're mainly testing that the flags are accepted and parsed
// The detailed validation logic is tested in integration tests
}
func TestFormatTimePtr(t *testing.T) {
testTime := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
if formatTimePtr(&testTime) == "" {
t.Error("formatTimePtr should return formatted time string")
}
if formatTimePtr(nil) != "" {
t.Error("formatTimePtr should return empty string for nil")
}
}
func TestServiceCreate_ValidationErrors(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and a mock API URL to prevent network calls
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "http://localhost:9999", // Use a local URL that will fail fast
"project_id": "test-project-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "test-api-key", nil
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Test with no name (should auto-generate) - this should now work without error
// Just test that it doesn't fail due to missing name
_, err, _ = executeServiceCommand("service", "create", "--addons", "none", "--region", "us-east-1")
// This should fail due to network/API call, not due to missing name
if err != nil && (strings.Contains(err.Error(), "name") && strings.Contains(err.Error(), "required")) {
t.Errorf("Should not fail due to missing name anymore (should auto-generate), got: %v", err)
}
// Test with explicit empty region (should still fail validation)
_, err, _ = executeServiceCommand("service", "create", "--name", "test", "--addons", "none", "--region", "")
if err == nil {
t.Fatal("Expected error when region is empty")
}
if !strings.Contains(err.Error(), "region") && !strings.Contains(err.Error(), "empty") {
t.Errorf("Expected error about empty region, got: %v", err)
}
// Test invalid addon - this should fail validation before making API call
_, err, _ = executeServiceCommand("service", "create", "--addons", "invalid-addon", "--region", "us-east-1", "--cpu", "1000", "--memory", "4", "--replicas", "1")
if err == nil {
t.Fatal("Expected error when addon is invalid")
}
if !strings.Contains(err.Error(), "invalid add-on") {
t.Errorf("Expected error about invalid add-on, got: %v", err)
}
}
func TestServiceCreate_NoAuth(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and API URL
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication failure
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "", fmt.Errorf("not logged in")
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service create command with valid parameters (name will be auto-generated)
_, err, _ = executeServiceCommand("service", "create", "--addons", "none", "--region", "us-east-1", "--cpu", "1000", "--memory", "4", "--replicas", "1")
if err == nil {
t.Fatal("Expected error when not authenticated")
}
if !strings.Contains(err.Error(), "authentication required") {
t.Errorf("Expected authentication error, got: %v", err)
}
}
// Helper function to create test services
func createTestServices() []api.Service {
testServiceID1 := "12345678-9abc-def0-1234-56789abcdef0"
testServiceID2 := "98765432-10fe-dcba-9876-543210fedcba"
name1 := "test-service-1"
name2 := "test-service-2"
region1 := "us-east-1"
region2 := "eu-west-1"
status1 := api.DeployStatus("running")
status2 := api.DeployStatus("stopped")
serviceType1 := api.ServiceType("POSTGRES")
serviceType2 := api.ServiceType("TIMESCALEDB")
created1 := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
created2 := time.Date(2024, 1, 2, 12, 0, 0, 0, time.UTC)
return []api.Service{
{
ServiceId: &testServiceID1,
Name: &name1,
RegionCode: ®ion1,
Status: &status1,
ServiceType: &serviceType1,
Created: &created1,
},
{
ServiceId: &testServiceID2,
Name: &name2,
RegionCode: ®ion2,
Status: &status2,
ServiceType: &serviceType2,
Created: &created2,
},
}
}
func TestAutoGeneratedServiceName(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and a mock API URL to prevent network calls
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "http://localhost:9999", // Use a local URL that will fail fast
"project_id": "test-project-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "test-api-key", nil
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Test that service name is auto-generated when not provided
// We expect this to fail at the API call stage, not at validation
var rootCmd *cobra.Command
_, err, rootCmd = executeServiceCommand("service", "create", "--addons", "none", "--region", "us-east-1")
// The command should not fail due to missing service name
if err != nil && strings.Contains(err.Error(), "service name is required") {
t.Error("Service name should be auto-generated, not required")
}
// Navigate to the create command that was actually used
if rootCmd == nil {
t.Fatal("rootCmd should not be nil")
}
// Find service command
serviceCmd, _, err := rootCmd.Find([]string{"service"})
if err != nil {
t.Fatalf("Failed to find service command: %v", err)
}
// Find create subcommand
createCmd, _, err := serviceCmd.Find([]string{"create"})
if err != nil {
t.Fatalf("Failed to find create command: %v", err)
}
nameFlag := createCmd.Flags().Lookup("name")
if nameFlag == nil {
t.Fatal("name flag should exist on create command")
}
serviceName := nameFlag.Value.String()
if serviceName == "" {
t.Error("Service name should have been auto-generated")
}
// Check pattern (should start with "db-" followed by numbers)
if !strings.HasPrefix(serviceName, "db-") {
t.Errorf("Auto-generated name should start with 'db-', got: %s", serviceName)
}
}
func TestServiceGet_NoServiceID(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID but no default service ID
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "test-api-key", nil
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service get command without service ID
_, err, _ = executeServiceCommand("service", "get")
if err == nil {
t.Fatal("Expected error when no service ID is provided or configured")
}
if !strings.Contains(err.Error(), "service ID is required") {
t.Errorf("Expected error about missing service ID, got: %v", err)
}
}
func TestServiceGet_NoAuth(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID and service ID
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
"service_id": "svc-12345",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication failure
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "", fmt.Errorf("not logged in")
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service get command
_, err, _ = executeServiceCommand("service", "get")
if err == nil {
t.Fatal("Expected error when not authenticated")
}
if !strings.Contains(err.Error(), "authentication required") {
t.Errorf("Expected authentication error, got: %v", err)
}
}
func TestOutputService_JSON(t *testing.T) {
// Create a test service object
serviceID := "svc-12345"
serviceName := "test-service"
serviceType := api.TIMESCALEDB
regionCode := "us-east-1"
status := api.READY
created := time.Now()
initialPassword := "secret-password-123"
service := api.Service{
ServiceId: &serviceID,
Name: &serviceName,
ServiceType: &serviceType,
RegionCode: ®ionCode,
Status: &status,
Created: &created,
InitialPassword: &initialPassword,
}
// Create a test command
cmd := &cobra.Command{}
buf := new(bytes.Buffer)
cmd.SetOut(buf)
// Test JSON output
err := outputService(cmd, service, "json", false)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Verify JSON output
output := buf.String()
if !strings.Contains(output, `"service_id": "svc-12345"`) {
t.Errorf("Expected JSON to contain service ID, got: %s", output)
}
// Verify that initialpassword is NOT in the output
if strings.Contains(output, "secret-password-123") || strings.Contains(output, "initialpassword") || strings.Contains(output, "initial_password") || strings.Contains(output, "password") {
t.Errorf("JSON output should not contain initialpassword field, got: %s", output)
}
// Verify it's valid JSON
var jsonResult api.Service
err = json.Unmarshal([]byte(output), &jsonResult)
if err != nil {
t.Errorf("Output should be valid JSON: %v", err)
}
// Verify that the unmarshaled result has no initial password
// Since we're now using maps for sanitized output, we need to parse it differently
var jsonMap map[string]interface{}
err2 := json.Unmarshal([]byte(output), &jsonMap)
if err2 != nil {
t.Errorf("Output should be valid JSON map: %v", err2)
}
// Check that initialpassword fields are not present in the map
if _, exists := jsonMap["initial_password"]; exists {
t.Error("JSON should not contain initial_password field")
}
if _, exists := jsonMap["initialpassword"]; exists {
t.Error("JSON should not contain initialpassword field")
}
if _, exists := jsonMap["password"]; exists {
t.Error("JSON should not contain password field")
}
}
func TestOutputService_YAML(t *testing.T) {
// Create a test service object
serviceID := "svc-12345"
serviceName := "test-service"
serviceType := api.TIMESCALEDB
regionCode := "us-east-1"
status := api.READY
created := time.Now()
initialPassword := "secret-password-123"
service := api.Service{
ServiceId: &serviceID,
Name: &serviceName,
ServiceType: &serviceType,
RegionCode: ®ionCode,
Status: &status,
Created: &created,
InitialPassword: &initialPassword,
}
// Create a test command
cmd := &cobra.Command{}
buf := new(bytes.Buffer)
cmd.SetOut(buf)
// Test YAML output
err := outputService(cmd, service, "yaml", false)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Verify YAML output
output := buf.String()
if !strings.Contains(output, "service_id: svc-12345") {
t.Errorf("Expected YAML to contain service ID, got: %s", output)
}
// Verify that initialpassword is NOT in the output
if strings.Contains(output, "secret-password-123") || strings.Contains(output, "initialpassword") || strings.Contains(output, "password") {
t.Errorf("YAML output should not contain initialpassword field, got: %s", output)
}
// Verify it's valid YAML
var yamlResult api.Service
err = yaml.Unmarshal([]byte(output), &yamlResult)
if err != nil {
t.Errorf("Output should be valid YAML: %v", err)
}
// Verify that the unmarshaled result has no initial password
// Since we're now using maps for sanitized output, we need to parse it differently
var yamlMap map[string]interface{}
err2 := yaml.Unmarshal([]byte(output), &yamlMap)
if err2 != nil {
t.Errorf("Output should be valid YAML map: %v", err2)
}
// Check that initialpassword fields are not present in the map
if _, exists := yamlMap["initial_password"]; exists {
t.Error("YAML should not contain initial_password field")
}
if _, exists := yamlMap["initialpassword"]; exists {
t.Error("YAML should not contain initialpassword field")
}
if _, exists := yamlMap["password"]; exists {
t.Error("YAML should not contain password field")
}
}
func TestOutputService_Table(t *testing.T) {
// Create a test service object with resource information
serviceID := "svc-12345"
serviceName := "test-service"
serviceType := api.TIMESCALEDB
regionCode := "us-east-1"
status := api.READY
created := time.Now()
cpuMillis := 2000
memoryGbs := 8
replicaCount := 2
host := "test.tigerdata.com"
port := 5432
initialPassword := "secret-password-123"
service := api.Service{
ServiceId: &serviceID,
Name: &serviceName,
ServiceType: &serviceType,
RegionCode: ®ionCode,
Status: &status,
Created: &created,
InitialPassword: &initialPassword,
Resources: &[]struct {
Id *string `json:"id,omitempty"`
Spec *struct {
CpuMillis *int `json:"cpu_millis,omitempty"`
MemoryGbs *int `json:"memory_gbs,omitempty"`
VolumeType *string `json:"volume_type,omitempty"`
} `json:"spec,omitempty"`
}{
{
Spec: &struct {
CpuMillis *int `json:"cpu_millis,omitempty"`
MemoryGbs *int `json:"memory_gbs,omitempty"`
VolumeType *string `json:"volume_type,omitempty"`
}{
CpuMillis: &cpuMillis,
MemoryGbs: &memoryGbs,
},
},
},
HaReplicas: &api.HAReplica{
ReplicaCount: &replicaCount,
},
Endpoint: &api.Endpoint{
Host: &host,
Port: &port,
},
}
// Create a test command
cmd := &cobra.Command{}
buf := new(bytes.Buffer)
cmd.SetOut(buf)
// Test table output
err := outputService(cmd, service, "table", false)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Verify table output contains expected information
output := buf.String()
expectedContents := []string{
"svc-12345",
"test-service",
"READY",
"TIMESCALEDB",
"us-east-1",
"2 cores (2000m)",
"8 GB",
"2",
"test.tigerdata.com:5432",
}
for _, content := range expectedContents {
if !strings.Contains(output, content) {
t.Errorf("Expected table to contain %q, got: %s", content, output)
}
}
// Verify that initialpassword is NOT in the table output
if strings.Contains(output, "secret-password-123") || strings.Contains(output, "password") {
t.Errorf("Table output should not contain password information, got: %s", output)
}
}
func TestPrepareServiceForOutput_WithoutPassword(t *testing.T) {
// Create a service with sensitive data
serviceID := "svc-12345"
serviceName := "test-service"
initialPassword := "secret-password-123"
service := api.Service{
ServiceId: &serviceID,
Name: &serviceName,
InitialPassword: &initialPassword,
}
// Mock a cobra command for testing
cmd := &cobra.Command{}
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetErr(buf)
// Prepare service for output without password
outputSvc := prepareServiceForOutput(service, false, cmd.ErrOrStderr())
// Verify that password is removed
if outputSvc.InitialPassword != nil {
t.Error("Expected InitialPassword to be nil when withPassword=false")
}
if outputSvc.Password != "" {
t.Error("Expected Password to be empty when withPassword=false")
}
// Verify that other fields are preserved
if outputSvc.ServiceId == nil || *outputSvc.ServiceId != serviceID {
t.Error("Expected service_id to be preserved")
}
if outputSvc.Name == nil || *outputSvc.Name != serviceName {
t.Error("Expected name to be preserved")
}
}
func TestPrepareServiceForOutput_WithPassword(t *testing.T) {
// Create a service with sensitive data
serviceID := "svc-12345"
serviceName := "test-service"
initialPassword := "secret-password-123"
serviceHost := "test.tigerdata.com"
servicePort := 5432
service := api.Service{
ServiceId: &serviceID,
Name: &serviceName,
InitialPassword: &initialPassword,
Endpoint: &api.Endpoint{
Host: &serviceHost,
Port: &servicePort,
},
}
// Mock a cobra command for testing
cmd := &cobra.Command{}
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetErr(buf)
// Prepare service for output with password
outputSvc := prepareServiceForOutput(service, true, cmd.ErrOrStderr())
// Verify that password is preserved
if outputSvc.InitialPassword != nil {
t.Error("Expected InitialPassword to be nil when withPassword=true")
}
if outputSvc.Password == "" || outputSvc.Password != initialPassword {
t.Error("Expected Password to be preserved when withPassword=true")
}
// Verify that other fields are preserved
if outputSvc.ServiceId == nil || *outputSvc.ServiceId != serviceID {
t.Error("Expected service_id to be preserved")
}
if outputSvc.Name == nil || *outputSvc.Name != serviceName {
t.Error("Expected name to be preserved")
}
}
func TestSanitizeServicesForOutput(t *testing.T) {
// Create services with sensitive data
serviceID1 := "svc-12345"
serviceName1 := "test-service-1"
initialPassword1 := "secret-password-123"
serviceID2 := "svc-67890"
serviceName2 := "test-service-2"
initialPassword2 := "another-secret-456"
services := []api.Service{
{
ServiceId: &serviceID1,
Name: &serviceName1,
InitialPassword: &initialPassword1,
},
{
ServiceId: &serviceID2,
Name: &serviceName2,
InitialPassword: &initialPassword2,
},
}
// Sanitize the services
sanitized := prepareServicesForOutput(services, false, nil)
// Verify that we have the same number of services
if len(sanitized) != len(services) {
t.Errorf("Expected %d sanitized services, got %d", len(services), len(sanitized))
}
// Verify that sensitive fields are removed from all services
for i, service := range sanitized {
if service.InitialPassword != nil {
t.Errorf("Expected InitialPassword to be nil in sanitized service %d", i)
}
if service.Password != "" {
t.Errorf("Expected Password to be empty in sanitized service %d", i)
}
// Verify that other fields are preserved
if service.ServiceId == nil {
t.Errorf("Expected ServiceId to be preserved in sanitized service %d", i)
}
if service.Name == nil {
t.Errorf("Expected Name to be preserved in sanitized service %d", i)
}
}
}
func TestServiceUpdatePassword_NoServiceID(t *testing.T) {
tmpDir := setupServiceTest(t)
// Set up config with project ID but no default service ID
_, err := config.UseTestConfig(tmpDir, map[string]any{
"api_url": "https://api.tigerdata.com/public/v1",
"project_id": "test-project-123",
})
if err != nil {
t.Fatalf("Failed to save test config: %v", err)
}
// Mock authentication
originalGetAPIKey := getAPIKeyForService
getAPIKeyForService = func() (string, error) {
return "test-api-key", nil
}
defer func() { getAPIKeyForService = originalGetAPIKey }()
// Execute service update-password command without service ID
_, err, _ = executeServiceCommand("service", "update-password", "--new-password", "new-password")