|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path/filepath" |
| 6 | + "testing" |
| 7 | +) |
| 8 | + |
| 9 | +func TestConfig_Save(t *testing.T) { |
| 10 | + t.Parallel() |
| 11 | + |
| 12 | + // Create a temporary directory for the test |
| 13 | + tmpDir := t.TempDir() |
| 14 | + |
| 15 | + // Change to temp directory so relative paths resolve correctly |
| 16 | + originalDir, err := os.Getwd() |
| 17 | + if err != nil { |
| 18 | + t.Fatalf("Failed to get current directory: %v", err) |
| 19 | + } |
| 20 | + defer func() { |
| 21 | + if err := os.Chdir(originalDir); err != nil { |
| 22 | + t.Logf("Failed to restore original directory: %v", err) |
| 23 | + } |
| 24 | + }() |
| 25 | + |
| 26 | + tests := []struct { |
| 27 | + name string |
| 28 | + configPath string |
| 29 | + contextName string |
| 30 | + expectFileAt string // Expected file location for verification |
| 31 | + useAbsolutePath bool // Whether to use absolute path for expectFileAt |
| 32 | + }{ |
| 33 | + { |
| 34 | + name: "relative path without prefix", |
| 35 | + configPath: "test-config.yaml", |
| 36 | + contextName: "test", |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "relative path with prefix", |
| 40 | + configPath: "./test-config-2.yaml", |
| 41 | + contextName: "test2", |
| 42 | + }, |
| 43 | + { |
| 44 | + name: "absolute path", |
| 45 | + configPath: filepath.Join(tmpDir, "absolute-config.yaml"), |
| 46 | + contextName: "test3", |
| 47 | + }, |
| 48 | + } |
| 49 | + |
| 50 | + for _, tt := range tests { |
| 51 | + t.Run(tt.name, func(t *testing.T) { |
| 52 | + t.Parallel() |
| 53 | + |
| 54 | + if err := os.Chdir(tmpDir); err != nil { |
| 55 | + t.Fatalf("Failed to change to temp directory: %v", err) |
| 56 | + } |
| 57 | + |
| 58 | + cfg := &Config{ |
| 59 | + CurrentContext: tt.contextName, |
| 60 | + Contexts: map[string]*Context{ |
| 61 | + tt.contextName: { |
| 62 | + Name: tt.contextName, |
| 63 | + }, |
| 64 | + }, |
| 65 | + path: tt.configPath, |
| 66 | + } |
| 67 | + |
| 68 | + // This should not fail when saving the config |
| 69 | + err := cfg.Save() |
| 70 | + if err != nil { |
| 71 | + t.Errorf("Expected no error when saving config, got: %v", err) |
| 72 | + } |
| 73 | + |
| 74 | + // Verify the file was created |
| 75 | + if _, err := os.Stat(tt.configPath); os.IsNotExist(err) { |
| 76 | + t.Errorf("Config file was not created at expected path: %s", tt.configPath) |
| 77 | + } |
| 78 | + }) |
| 79 | + } |
| 80 | +} |
0 commit comments