github.com/opentelekomcloud/gophertelekomcloud@v0.9.3/internal/build/query_string_test.go (about) 1 package build 2 3 import ( 4 "testing" 5 6 "github.com/opentelekomcloud/gophertelekomcloud/openstack/common/pointerto" 7 "github.com/stretchr/testify/require" 8 ) 9 10 type QueryStruct struct { 11 Bar string `q:"x_bar" required:"true"` 12 Baz int `q:"lorem_ipsum"` 13 Foo []int `q:"foo"` 14 FooStr []string `q:"foostr"` 15 Map1 map[string]string `q:"map"` 16 Map2 map[string]int `q:"map_invalid"` // not supported 17 Req *bool `q:"req"` 18 NotHere string 19 } 20 21 func TestQueryString_ok(t *testing.T) { 22 t.Parallel() 23 24 cases := map[string]struct { 25 opts *QueryStruct 26 expected string 27 }{ 28 "simple": { 29 &QueryStruct{ 30 Bar: "AAA", 31 Baz: 200, 32 Req: pointerto.Bool(false), 33 NotHere: "no", 34 }, 35 "?lorem_ipsum=200&req=false&x_bar=AAA", 36 }, 37 "with_int_slice": { 38 &QueryStruct{ 39 Bar: "AAA", 40 Foo: []int{1, 2, 3}, 41 }, 42 "?foo=1&foo=2&foo=3&x_bar=AAA", 43 }, 44 "with_str_slice": { 45 &QueryStruct{ 46 Bar: "AAA", 47 FooStr: []string{"a", "b"}, 48 }, 49 "?foostr=a&foostr=b&x_bar=AAA", 50 }, 51 "with_str_map": { 52 &QueryStruct{ 53 Bar: "AAA", 54 Map1: map[string]string{"foo": "bar"}, 55 }, 56 "?map=%7B%27foo%27%3A%27bar%27%7D&x_bar=AAA", 57 }, 58 } 59 60 for name, data := range cases { 61 t.Run(name, func(t *testing.T) { 62 data := data 63 64 t.Parallel() 65 66 query, err := QueryString(data.opts) 67 68 require.NoError(t, err) 69 require.EqualValues(t, data.expected, query.String()) 70 }) 71 } 72 } 73 74 func TestQueryString_notOk(t *testing.T) { 75 t.Parallel() 76 77 cases := map[string]struct { 78 opts interface{} 79 errMsg string 80 }{ 81 "nil opts": { 82 nil, 83 "error building query string: nil options provided", 84 }, 85 "missing_required": { 86 &QueryStruct{}, 87 "error building query string: required query parameter [Bar] not set", 88 }, 89 "not_struct": { 90 map[string]interface{}{}, 91 "error building query string: options type is not a struct", 92 }, 93 "with_non_str_map": { 94 &QueryStruct{Bar: "1", Map2: map[string]int{"foo": 1}}, 95 "error building query string: expected map[string]string, got map[string]int", 96 }, 97 } 98 99 for name, data := range cases { 100 t.Run(name, func(t *testing.T) { 101 data := data 102 103 t.Parallel() 104 105 _, err := QueryString(data.opts) 106 107 require.Error(t, err) 108 require.EqualError(t, err, data.errMsg) 109 }) 110 } 111 }