Repository navigation
Expand file tree
/
Copy pathloading_test.go
More file actions
98 lines (87 loc) · 2.33 KB
/
Copy pathloading_test.go
File metadata and controls
98 lines (87 loc) · 2.33 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
package env
import (
"os"
"strings"
"testing"
)
// TestParse checks that Parse reads a reader into a map, expanding double
// quoted/unquoted values while leaving single quotes literal.
func TestParse(t *testing.T) {
os.Clearenv()
Set("BASE", "world")
src := "A=hello\nB=\"x ${BASE}\"\nC='$BASE'\n"
m, err := Parse(strings.NewReader(src))
if err != nil {
t.Fatal(err)
}
want := map[string]string{"A": "hello", "B": "x world", "C": "$BASE"}
for k, v := range want {
if m[k] != v {
t.Errorf("Parse[%s] = %q, want %q", k, m[k], v)
}
}
}
// TestParseRaw checks that ParseRaw does not expand variables.
func TestParseRaw(t *testing.T) {
os.Clearenv()
Set("BASE", "world")
m, err := ParseRaw(strings.NewReader("B=$BASE\n"))
if err != nil {
t.Fatal(err)
}
if m["B"] != "$BASE" {
t.Errorf("ParseRaw[B] = %q, want %q", m["B"], "$BASE")
}
}
// TestRead checks that Read returns the file as a map without touching the
// process environment.
func TestRead(t *testing.T) {
os.Clearenv()
m, err := Read("./fixtures/simple.env")
if err != nil {
t.Fatal(err)
}
if m["KEY_0"] != "value 0" || m["KEY_1"] != "value_1" {
t.Errorf("unexpected map: %v", m)
}
if _, ok := os.LookupEnv("KEY_0"); ok {
t.Error("Read must not write to the environment")
}
}
// TestLoadReader checks that LoadReader loads into the environment and does
// not override existing keys.
func TestLoadReader(t *testing.T) {
os.Clearenv()
if err := LoadReader(strings.NewReader("X=1\nY=2\n")); err != nil {
t.Fatal(err)
}
if Get("X") != "1" || Get("Y") != "2" {
t.Errorf("X=%q Y=%q", Get("X"), Get("Y"))
}
Set("X", "keep")
if err := LoadReader(strings.NewReader("X=changed\n")); err != nil {
t.Fatal(err)
}
if Get("X") != "keep" {
t.Errorf("LoadReader must not override existing keys, X=%q", Get("X"))
}
}
// TestUnmarshalFile checks that UnmarshalFile decodes a file into a struct
// without touching the process environment.
func TestUnmarshalFile(t *testing.T) {
type cfg struct {
Key0 string `env:"KEY_0"`
Key1 string `env:"KEY_1"`
}
os.Clearenv()
var c cfg
if err := UnmarshalFile("./fixtures/simple.env", &c); err != nil {
t.Fatal(err)
}
if c.Key0 != "value 0" || c.Key1 != "value_1" {
t.Errorf("unexpected struct: %+v", c)
}
if _, ok := os.LookupEnv("KEY_0"); ok {
t.Error("UnmarshalFile must not write to the environment")
}
}