-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcfgx_test.go
More file actions
317 lines (249 loc) · 8.27 KB
/
Copy pathcfgx_test.go
File metadata and controls
317 lines (249 loc) · 8.27 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
package cfgx
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/BurntSushi/toml"
"github.com/gomantics/cfgx/internal/envoverride"
"github.com/stretchr/testify/require"
)
func TestGenerate(t *testing.T) {
data, err := os.ReadFile("testdata/test.toml")
require.NoError(t, err, "failed to read test file")
output, err := Generate(data, "testconfig", true)
require.NoError(t, err, "Generate() should not error")
// Write to temp file and try to compile it
tmpDir := t.TempDir()
configFile := filepath.Join(tmpDir, "config.go")
err = os.WriteFile(configFile, output, 0644)
require.NoError(t, err, "failed to write output file")
// Try to compile the generated code
cmd := exec.Command("go", "build", configFile)
cmd.Dir = tmpDir
output, err = cmd.CombinedOutput()
require.NoError(t, err, "generated code does not compile: %s", output)
}
func TestGenerate_WithEnvOverrides(t *testing.T) {
tomlData := []byte(`
[server]
addr = ":8080"
timeout = 30
[database]
dsn = "localhost"
max_conns = 10
`)
os.Setenv("CONFIG_SERVER_ADDR", ":9090")
os.Setenv("CONFIG_DATABASE_MAX_CONNS", "100")
defer os.Unsetenv("CONFIG_SERVER_ADDR")
defer os.Unsetenv("CONFIG_DATABASE_MAX_CONNS")
var data map[string]any
err := toml.Unmarshal(tomlData, &data)
require.NoError(t, err)
err = envoverride.Apply(data)
require.NoError(t, err, "Apply() should not error")
var buf bytes.Buffer
enc := toml.NewEncoder(&buf)
err = enc.Encode(data)
require.NoError(t, err)
output, err := Generate(buf.Bytes(), "testconfig", true)
require.NoError(t, err, "Generate() should not error")
outputStr := string(output)
require.Contains(t, outputStr, `":9090"`, "environment override for server.addr not applied")
require.Contains(t, outputStr, "100", "environment override for database.max_conns not applied")
require.NotContains(t, outputStr, `":8080"`, "original server.addr should have been overridden")
}
func TestGenerateFromFile_GetterModeIgnoresEnvOverrides(t *testing.T) {
tmpDir := t.TempDir()
inputFile := filepath.Join(tmpDir, "config.toml")
outputFile := filepath.Join(tmpDir, "config.go")
tomlData := []byte(`
[server]
addr = ":8080"
[secrets]
api_key = "set-from-env"
`)
err := os.WriteFile(inputFile, tomlData, 0644)
require.NoError(t, err)
// Set env var that would override the TOML value at generation time
os.Setenv("CONFIG_SECRETS_API_KEY", "sk-real-secret-key-12345")
defer os.Unsetenv("CONFIG_SECRETS_API_KEY")
opts := &GenerateOptions{
InputFile: inputFile,
OutputFile: outputFile,
PackageName: "config",
EnableEnv: true,
Mode: "getter",
}
err = GenerateFromFile(opts)
require.NoError(t, err, "GenerateFromFile() should not error")
output, err := os.ReadFile(outputFile)
require.NoError(t, err)
outputStr := string(output)
// The generated code should use the TOML default, NOT the env var value
require.Contains(t, outputStr, `"set-from-env"`,
"getter mode should use TOML default, not env var value")
require.NotContains(t, outputStr, "sk-real-secret-key-12345",
"getter mode must not bake env var values into generated code")
// It should still have the os.Getenv call for runtime override
require.Contains(t, outputStr, `os.Getenv("CONFIG_SECRETS_API_KEY")`,
"getter mode should still generate runtime env var lookups")
}
func TestGenerateFromFile(t *testing.T) {
// Create a temporary TOML file
tmpDir := t.TempDir()
inputFile := filepath.Join(tmpDir, "config.toml")
outputFile := filepath.Join(tmpDir, "config.go")
tomlData := []byte(`
[server]
addr = ":8080"
read_timeout = 30
write_timeout = 30
shutdown_timeout = 10
[database]
dsn = "postgres://localhost:5432/myapp"
max_open_conns = 25
max_idle_conns = 5
conn_max_lifetime = 300
[redis]
addr = "localhost:6379"
password = ""
db = 0
pool_size = 10
[logging]
level = "info"
format = "json"
[features]
auth_enabled = true
rate_limiting = true
metrics_enabled = true
`)
err := os.WriteFile(inputFile, tomlData, 0644)
require.NoError(t, err, "failed to write input file")
opts := &GenerateOptions{
InputFile: inputFile,
OutputFile: outputFile,
PackageName: "config",
EnableEnv: true,
}
err = GenerateFromFile(opts)
require.NoError(t, err, "GenerateFromFile() should not error")
// Verify the file was created
_, err = os.Stat(outputFile)
require.NoError(t, err, "output file was not created")
// Read the generated code
output, err := os.ReadFile(outputFile)
require.NoError(t, err, "failed to read output file")
// Verify the generated code compiles
cmd := exec.Command("go", "build", outputFile)
cmd.Dir = tmpDir
cmdOutput, err := cmd.CombinedOutput()
require.NoError(t, err, "generated code does not compile: %s", cmdOutput)
// Verify expected structures are present
outputStr := string(output)
expectedStructs := []string{
"type DatabaseConfig struct",
"type FeaturesConfig struct",
"type LoggingConfig struct",
"type RedisConfig struct",
"type ServerConfig struct",
}
for _, expected := range expectedStructs {
require.Contains(t, outputStr, expected, "expected struct definition not found: %s", expected)
}
require.Contains(t, outputStr, "var (", "expected var block")
expectedVars := []string{
"Database = DatabaseConfig",
"Features = FeaturesConfig",
"Logging = LoggingConfig",
"Redis = RedisConfig",
"Server = ServerConfig",
}
for _, expected := range expectedVars {
require.Contains(t, outputStr, expected, "expected variable declaration not found: %s", expected)
}
}
func TestGenerateFromFile_WithFileEmbedding(t *testing.T) {
tmpDir := t.TempDir()
inputFile := filepath.Join(tmpDir, "config.toml")
outputFile := filepath.Join(tmpDir, "generated/config.go")
filesDir := filepath.Join(tmpDir, "data")
err := os.MkdirAll(filesDir, 0755)
require.NoError(t, err)
testContent := []byte("Hello from embedded file!\nLine 2")
testFile := filepath.Join(filesDir, "test.txt")
err = os.WriteFile(testFile, testContent, 0644)
require.NoError(t, err)
tomlData := []byte(`
[app]
name = "test"
content = "file:data/test.txt"
[server]
addr = ":8080"
`)
err = os.WriteFile(inputFile, tomlData, 0644)
require.NoError(t, err)
opts := &GenerateOptions{
InputFile: inputFile,
OutputFile: outputFile,
PackageName: "config",
EnableEnv: false,
MaxFileSize: 10 * 1024 * 1024,
}
err = GenerateFromFile(opts)
require.NoError(t, err, "GenerateFromFile() should not error")
output, err := os.ReadFile(outputFile)
require.NoError(t, err)
outputStr := string(output)
require.Contains(t, outputStr, "Content []byte", "should have []byte field")
require.Contains(t, outputStr, "0x48", "should contain 'H' (0x48)")
require.Contains(t, outputStr, "0x65", "should contain 'e' (0x65)")
require.Contains(t, outputStr, "[]byte{", "should have byte array literal")
cmd := exec.Command("go", "build", outputFile)
cmd.Dir = tmpDir
cmdOutput, err := cmd.CombinedOutput()
require.NoError(t, err, "generated code does not compile: %s", cmdOutput)
}
func TestGenerateFromFile_FileNotFound(t *testing.T) {
tmpDir := t.TempDir()
inputFile := filepath.Join(tmpDir, "config.toml")
outputFile := filepath.Join(tmpDir, "config.go")
// Create TOML with reference to non-existent file
tomlData := []byte(`
[app]
content = "file:nonexistent.txt"
`)
err := os.WriteFile(inputFile, tomlData, 0644)
require.NoError(t, err)
opts := &GenerateOptions{
InputFile: inputFile,
OutputFile: outputFile,
}
err = GenerateFromFile(opts)
require.Error(t, err, "should error on non-existent file")
require.Contains(t, err.Error(), "file not found", "error should mention file not found")
}
func TestGenerateFromFile_FileSizeExceeded(t *testing.T) {
tmpDir := t.TempDir()
inputFile := filepath.Join(tmpDir, "config.toml")
outputFile := filepath.Join(tmpDir, "config.go")
// Create a test file
largeFile := filepath.Join(tmpDir, "large.txt")
err := os.WriteFile(largeFile, []byte("This file is too large for the limit"), 0644)
require.NoError(t, err)
tomlData := []byte(`
[app]
content = "file:large.txt"
`)
err = os.WriteFile(inputFile, tomlData, 0644)
require.NoError(t, err)
opts := &GenerateOptions{
InputFile: inputFile,
OutputFile: outputFile,
MaxFileSize: 10, // Very small limit
}
err = GenerateFromFile(opts)
require.Error(t, err, "should error on file size exceeded")
require.Contains(t, err.Error(), "exceeds max size", "error should mention size limit")
}