google.golang.org/grpc@v1.72.2/internal/envconfig/envconfig_test.go (about) 1 /* 2 * 3 * Copyright 2022 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 package envconfig 20 21 import ( 22 "os" 23 "testing" 24 25 "google.golang.org/grpc/internal/grpctest" 26 ) 27 28 type s struct { 29 grpctest.Tester 30 } 31 32 func Test(t *testing.T) { 33 grpctest.RunSubTests(t, s{}) 34 } 35 36 func (s) TestUint64FromEnv(t *testing.T) { 37 var testCases = []struct { 38 name string 39 val string 40 def, min, max uint64 41 want uint64 42 }{ 43 { 44 name: "error parsing", 45 val: "asdf", def: 5, want: 5, 46 }, { 47 name: "unset", 48 val: "", def: 5, want: 5, 49 }, { 50 name: "too low", 51 val: "5", min: 10, want: 10, 52 }, { 53 name: "too high", 54 val: "5", max: 2, want: 2, 55 }, { 56 name: "in range", 57 val: "17391", def: 13000, min: 12000, max: 18000, want: 17391, 58 }, 59 } 60 for _, tc := range testCases { 61 t.Run(tc.name, func(t *testing.T) { 62 const testVar = "testvar" 63 if tc.val == "" { 64 os.Unsetenv(testVar) 65 } else { 66 os.Setenv(testVar, tc.val) 67 } 68 if got := uint64FromEnv(testVar, tc.def, tc.min, tc.max); got != tc.want { 69 t.Errorf("uint64FromEnv(%q(=%q), %v, %v, %v) = %v; want %v", testVar, tc.val, tc.def, tc.min, tc.max, got, tc.want) 70 } 71 }) 72 } 73 } 74 75 func (s) TestBoolFromEnv(t *testing.T) { 76 var testCases = []struct { 77 val string 78 def bool 79 want bool 80 }{ 81 {val: "", def: true, want: true}, 82 {val: "", def: false, want: false}, 83 {val: "true", def: true, want: true}, 84 {val: "true", def: false, want: true}, 85 {val: "false", def: true, want: false}, 86 {val: "false", def: false, want: false}, 87 {val: "asdf", def: true, want: true}, 88 {val: "asdf", def: false, want: false}, 89 } 90 for _, tc := range testCases { 91 t.Run("", func(t *testing.T) { 92 const testVar = "testvar" 93 if tc.val == "" { 94 os.Unsetenv(testVar) 95 } else { 96 os.Setenv(testVar, tc.val) 97 } 98 if got := boolFromEnv(testVar, tc.def); got != tc.want { 99 t.Errorf("boolFromEnv(%q(=%q), %v) = %v; want %v", testVar, tc.val, tc.def, got, tc.want) 100 } 101 }) 102 } 103 }