This repository has been archived by the owner on Mar 6, 2019. It is now read-only.
forked from adtac/commento
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_test.go
127 lines (109 loc) · 2.44 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
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
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
type testCaseConfig struct {
name string
files map[string]string
expected map[string]string
}
func TestConfig(t *testing.T) {
tests := []func(t *testing.T){
testLoadConfig,
}
for _, test := range tests {
setupConfigTest(t)
test(t)
cleanupConfigTest(t)
}
}
func setupConfigTest(t *testing.T) {
oldFiles, err := filepath.Glob(".env*")
if err != nil {
t.Fatalf("Unable to glob for .env* files: %v\n", err)
}
for _, oldFile := range oldFiles {
t.Logf("renaming %s to %s", oldFile, ".tmp"+oldFile)
os.Rename(oldFile, ".tmp"+oldFile)
}
}
func cleanupConfigTest(t *testing.T) {
createdFiles, err := filepath.Glob(".env*")
if err == nil {
for _, createdFile := range createdFiles {
os.Remove(createdFile)
}
}
tmpFiles, err := filepath.Glob(".tmp.env*")
if err != nil {
t.Fatalf("Unable to glob for .tmp.env* files: %v\n", err)
}
for _, tmpFile := range tmpFiles {
t.Logf("restoring %s to %s", tmpFile, strings.TrimPrefix(tmpFile, ".tmp"))
os.Rename(tmpFile, strings.TrimPrefix(tmpFile, ".tmp"))
}
}
func runTests(t *testing.T, funcName string, testCasesConfig []testCaseConfig) {
for _, tc := range testCasesConfig {
for filename, contents := range tc.files {
f, err := os.Create(filename)
if err != nil {
t.Fatalf("Cannot create file %s: %v\n", filename, err)
}
f.WriteString(contents)
f.Close()
}
loadConfig()
for key, value := range tc.expected {
if os.Getenv(key) != value {
t.Errorf("%s: %s: expected %s=%s, got %s=%s", funcName, tc.name, key, value, key, os.Getenv(key))
}
os.Setenv(key, "")
}
}
}
func testLoadConfig(t *testing.T) {
testCasesConfig := []testCaseConfig{
testCaseConfig{
"Absence of all .env* files should load defaults",
map[string]string{},
map[string]string{
"COMMENTO_PORT": "8080",
},
},
testCaseConfig{
".env should be loaded",
map[string]string{
".env": `
COMMENTO_PORT=8081
env1=val1
env2=val2`,
},
map[string]string{
"COMMENTO_PORT": "8081",
"env1": "val1",
"env2": "val2",
},
},
testCaseConfig{
".env.test should dominate .env",
map[string]string{
".env": `
env1=val1
env2=val2`,
".env.test": `
env2=val3
env3=val4`,
},
map[string]string{
"env1": "val1",
"env2": "val3",
"env3": "val4",
},
},
}
runTests(t, "loadConfig", testCasesConfig)
}