-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_test.go
97 lines (81 loc) · 2.34 KB
/
config_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
package main
import (
"encoding/json"
"os"
"testing"
)
func TestReadConfig(t *testing.T) {
t.Run("Valid Config File", func(t *testing.T) {
// Create a temporary config file
configFile, err := os.CreateTemp("", "config.json")
if err != nil {
t.Errorf("Error creating temporary config file: %v", err)
}
defer os.Remove(configFile.Name())
// Write the config data to the file
configData := &Config{APIKey: "123456"}
err = json.NewEncoder(configFile).Encode(configData)
if err != nil {
t.Errorf("Error encoding config data: %v", err)
}
configFile.Close()
// Call readConfig with the temporary config file
config, err := readConfig(configFile.Name())
if err != nil {
t.Errorf("Error reading config file: %v", err)
}
// Check that the config was read correctly
if config.APIKey != configData.APIKey {
t.Errorf("Expected APIKey '%s', got '%s'", configData.APIKey, config.APIKey)
}
})
t.Run("Invalid Config File", func(t *testing.T) {
// Call readConfig with a non-existent config file
_, err := readConfig("nonexistent.json")
if err == nil {
t.Errorf("Expected an error, but did not get one")
}
})
}
func TestWriteConfig(t *testing.T) {
tempFile, err := os.CreateTemp("", "Keys.json")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tempFile.Name())
config := &Config{APIKey: "test-api-key"}
err = writeConfig(tempFile.Name(), config)
if err != nil {
t.Errorf("writeConfig() returned error: %v", err)
}
data, err := os.ReadFile(tempFile.Name())
if err != nil {
t.Errorf("Error reading file: %v", err)
}
var configFromFile Config
err = json.Unmarshal(data, &configFromFile)
if err != nil {
t.Errorf("Error unmarshaling JSON: %v", err)
}
if configFromFile.APIKey != config.APIKey {
t.Errorf("API key does not match expected value. Got %s, expected %s", configFromFile.APIKey, config.APIKey)
}
}
func TestWriteConfigFail(t *testing.T) {
// Create temporary file and make it read-only
tempFile, err := os.CreateTemp("", "Keys.json")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tempFile.Name())
err = tempFile.Chmod(0400)
if err != nil {
t.Fatalf("Error setting file permissions: %v", err)
}
// Attempt to write config to read-only file
config := &Config{APIKey: "test-api-key"}
err = writeConfig(tempFile.Name(), config)
if err == nil {
t.Error("Expected error, but got nil")
}
}