@@ -142,6 +142,90 @@ func TestParseDurationFromEnv(t *testing.T) {
142142 }
143143}
144144
145+ func TestParseDurationFromEnvEdgeCases (t * testing.T ) {
146+ envKey := "SOME_ENV_KEY"
147+ def := 3 * time .Minute
148+ minimum := 1 * time .Second
149+ maximum := 2160 * time .Hour // 3 months
150+
151+ testCases := []struct {
152+ name string
153+ env string
154+ expected time.Duration
155+ }{{
156+ name : "EnvNotSet" ,
157+ expected : def ,
158+ }, {
159+ name : "Durations defined as days are valid" ,
160+ env : "12d" ,
161+ expected : time .Hour * 24 * 12 ,
162+ }, {
163+ name : "Negative durations should fail parsing and use the default value" ,
164+ env : "-1h" ,
165+ expected : def ,
166+ }, {
167+ name : "Negative day durations should fail parsing and use the default value" ,
168+ env : "-12d" ,
169+ expected : def ,
170+ }, {
171+ name : "Scientific notation should fail parsing and use the default value" ,
172+ env : "1e3s" ,
173+ expected : def ,
174+ }, {
175+ name : "Durations with a leading zero are considered valid and parsed as decimal notation" ,
176+ env : "0755s" ,
177+ expected : time .Second * 755 ,
178+ }, {
179+ name : "Durations with many leading zeroes are considered valid and parsed as decimal notation" ,
180+ env : "000083m" ,
181+ expected : time .Minute * 83 ,
182+ }, {
183+ name : "Decimal Durations should not fail parsing" ,
184+ env : "30.5m" ,
185+ expected : time .Minute * 30 + time .Second * 30 ,
186+ }, {
187+ name : "Decimal Day Durations should fail parsing and use the default value" ,
188+ env : "30.5d" ,
189+ expected : def ,
190+ }, {
191+ name : "Fraction Durations should fail parsing and use the default value" ,
192+ env : "1/2h" ,
193+ expected : def ,
194+ }, {
195+ name : "Durations without a time unit should fail parsing and use the default value" ,
196+ env : "15" ,
197+ expected : def ,
198+ }, {
199+ name : "Durations with a trailing symbol should fail parsing and use the default value" ,
200+ env : "+12d" ,
201+ expected : def ,
202+ }, {
203+ name : "Leading space Duration should fail parsing use the default value" ,
204+ env : " 2h" ,
205+ expected : def ,
206+ }, {
207+ name : "Trailing space Duration should fail parsing use the default value" ,
208+ env : "6m " ,
209+ expected : def ,
210+ }, {
211+ name : "Empty Duration should fail parsing use the default value" ,
212+ env : "" ,
213+ expected : def ,
214+ }, {
215+ name : "Whitespace Duration should fail parsing and use the default value" ,
216+ env : " " ,
217+ expected : def ,
218+ }}
219+
220+ for _ , tc := range testCases {
221+ t .Run (tc .name , func (t * testing.T ) {
222+ t .Setenv (envKey , tc .env )
223+ val := ParseDurationFromEnv (envKey , def , minimum , maximum )
224+ assert .Equal (t , tc .expected , val )
225+ })
226+ }
227+ }
228+
145229func Test_ParseBoolFromEnv (t * testing.T ) {
146230 envKey := "SOMEKEY"
147231
0 commit comments