...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package baseapp
16
17 import (
18 "os"
19 "reflect"
20 "testing"
21 "time"
22 )
23
24 func TestSetValuesFromEnv(t *testing.T) {
25 tests := map[string]struct {
26 Input func(*HTTPConfig)
27 Prefix string
28 Variables map[string]string
29 Output func(*HTTPConfig)
30 }{
31 "noVariables": {
32 Input: func(c *HTTPConfig) {
33 c.Address = "0.0.0.0"
34 c.Port = 8080
35 },
36 Output: func(c *HTTPConfig) {
37 c.Address = "0.0.0.0"
38 c.Port = 8080
39 },
40 },
41 "overwriteExisting": {
42 Input: func(c *HTTPConfig) {
43 c.Address = "127.0.0.1"
44 },
45 Variables: map[string]string{
46 "ADDRESS": "0.0.0.0",
47 },
48 Output: func(c *HTTPConfig) {
49 c.Address = "0.0.0.0"
50 },
51 },
52 "allVariables": {
53 Variables: map[string]string{
54 "ADDRESS": "127.0.0.1",
55 "PORT": "8080",
56 "PUBLIC_URL": "https://baseapp.company.domain",
57 "TLS_CERT_FILE": "/path/to/cert.crt",
58 "TLS_KEY_FILE": "/path/to/key.pem",
59 "SHUTDOWN_WAIT_TIME": "5m",
60 },
61 Output: func(c *HTTPConfig) {
62 c.Address = "127.0.0.1"
63 c.Port = 8080
64 c.PublicURL = "https://baseapp.company.domain"
65 c.TLSConfig = &TLSConfig{
66 CertFile: "/path/to/cert.crt",
67 KeyFile: "/path/to/key.pem",
68 }
69 d := 5 * time.Minute
70 c.ShutdownWaitTime = &d
71 },
72 },
73 "withPrefix": {
74 Input: func(c *HTTPConfig) {
75 c.PublicURL = "https://baseapp.company.domain"
76 },
77 Prefix: "TEST_",
78 Variables: map[string]string{
79 "TEST_PUBLIC_URL": "https://app.company.domain",
80 },
81 Output: func(c *HTTPConfig) {
82 c.PublicURL = "https://app.company.domain"
83 },
84 },
85 "emptyValues": {
86 Input: func(c *HTTPConfig) {
87 c.PublicURL = "https://baseapp.company.domain"
88 },
89 Variables: map[string]string{
90 "PUBLIC_URL": "",
91 },
92 Output: func(c *HTTPConfig) {
93 c.PublicURL = ""
94 },
95 },
96 }
97
98 for name, test := range tests {
99 t.Run(name, func(t *testing.T) {
100 for k, v := range test.Variables {
101 if err := os.Setenv(k, v); err != nil {
102 t.Fatalf("failed to set environment variable: %s: %v", k, err)
103 }
104 }
105
106 defer func() {
107 for k := range test.Variables {
108 if err := os.Unsetenv(k); err != nil {
109 t.Fatalf("failed to clear environment variable: %s: %v", k, err)
110 }
111 }
112 }()
113
114 var in HTTPConfig
115 if test.Input != nil {
116 test.Input(&in)
117 }
118
119 var out HTTPConfig
120 if test.Output != nil {
121 test.Output(&out)
122 }
123
124 in.SetValuesFromEnv(test.Prefix)
125
126 if !reflect.DeepEqual(out, in) {
127 t.Errorf("incorrect configuration\nexpected: %+v\n actual: %+v", out, in)
128 }
129 })
130 }
131 }
132
View as plain text