vitess.io/vitess@v0.16.2/go/vt/vtadmin/http/request_test.go (about) 1 /* 2 Copyright 2021 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package http 18 19 import ( 20 "fmt" 21 "net/http" 22 "net/url" 23 "testing" 24 25 "github.com/stretchr/testify/assert" 26 "github.com/stretchr/testify/require" 27 ) 28 29 func TestParseQueryParamAsBool(t *testing.T) { 30 t.Parallel() 31 32 tests := []struct { 33 name string 34 fragment string 35 param string 36 defaultValue bool 37 expected bool 38 shouldErr bool 39 }{ 40 { 41 name: "successful parse", 42 fragment: "?a=true&b=false", 43 param: "a", 44 defaultValue: false, 45 expected: true, 46 shouldErr: false, 47 }, 48 { 49 name: "no query fragment", 50 fragment: "", 51 param: "active_only", 52 defaultValue: false, 53 expected: false, 54 shouldErr: false, 55 }, 56 { 57 name: "param not set", 58 fragment: "?foo=bar", 59 param: "baz", 60 defaultValue: true, 61 expected: true, 62 shouldErr: false, 63 }, 64 { 65 name: "param not bool-like", 66 fragment: "?foo=bar", 67 param: "foo", 68 defaultValue: false, 69 shouldErr: true, 70 }, 71 } 72 73 for _, tt := range tests { 74 tt := tt 75 76 t.Run(tt.name, func(t *testing.T) { 77 t.Parallel() 78 79 rawurl := fmt.Sprintf("http://example.com/%s", tt.fragment) 80 u, err := url.Parse(rawurl) 81 require.NoError(t, err, "could not parse %s", rawurl) 82 83 r := Request{ 84 &http.Request{URL: u}, 85 } 86 87 val, err := r.ParseQueryParamAsBool(tt.param, tt.defaultValue) 88 if tt.shouldErr { 89 assert.Error(t, err) 90 91 return 92 } 93 94 assert.NoError(t, err) 95 assert.Equal(t, tt.expected, val) 96 }) 97 } 98 }