github.com/anakojm/hugo-katex@v0.0.0-20231023141351-42d6f5de9c0b/tpl/collections/index_test.go (about) 1 // Copyright 2017 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package collections 15 16 import ( 17 "fmt" 18 "testing" 19 20 "github.com/gohugoio/hugo/common/maps" 21 22 qt "github.com/frankban/quicktest" 23 ) 24 25 func TestIndex(t *testing.T) { 26 t.Parallel() 27 c := qt.New(t) 28 ns := newNs() 29 30 var ( 31 emptyInterface any 32 nilPointer *int 33 ) 34 35 for i, test := range []struct { 36 item any 37 indices []any 38 expect any 39 isErr bool 40 }{ 41 {[]int{0, 1}, []any{0}, 0, false}, 42 {[]int{0, 1}, []any{9}, nil, false}, // index out of range 43 {[]uint{0, 1}, nil, []uint{0, 1}, false}, 44 {[][]int{{1, 2}, {3, 4}}, []any{0, 0}, 1, false}, 45 {map[int]int{1: 10, 2: 20}, []any{1}, 10, false}, 46 {map[int]int{1: 10, 2: 20}, []any{0}, 0, false}, 47 {map[string]map[string]string{"a": {"b": "c"}}, []any{"a", "b"}, "c", false}, 48 {[]map[string]map[string]string{{"a": {"b": "c"}}}, []any{0, "a", "b"}, "c", false}, 49 {map[string]map[string]any{"a": {"b": []string{"c", "d"}}}, []any{"a", "b", 1}, "d", false}, 50 {maps.Params{"a": "av"}, []any{"A"}, "av", false}, 51 {maps.Params{"a": map[string]any{"b": "bv"}}, []any{"A", "B"}, "bv", false}, 52 53 // These used to be errors. 54 // See issue 10489. 55 {nil, nil, nil, false}, 56 {nil, []any{0}, nil, false}, 57 {emptyInterface, []any{0}, nil, false}, 58 {nilPointer, []any{0}, nil, false}, 59 60 // errors 61 {[]int{0, 1}, []any{"1"}, nil, true}, 62 {[]int{0, 1}, []any{nil}, nil, true}, 63 {tstNoStringer{}, []any{0}, nil, true}, 64 } { 65 66 c.Run(fmt.Sprintf("vararg %d", i), func(c *qt.C) { 67 errMsg := qt.Commentf("[%d] %v", i, test) 68 69 result, err := ns.Index(test.item, test.indices...) 70 71 if test.isErr { 72 c.Assert(err, qt.Not(qt.IsNil), errMsg) 73 return 74 } 75 c.Assert(err, qt.IsNil, errMsg) 76 c.Assert(result, qt.DeepEquals, test.expect, errMsg) 77 }) 78 79 c.Run(fmt.Sprintf("slice %d", i), func(c *qt.C) { 80 errMsg := qt.Commentf("[%d] %v", i, test) 81 82 result, err := ns.Index(test.item, test.indices) 83 84 if test.isErr { 85 c.Assert(err, qt.Not(qt.IsNil), errMsg) 86 return 87 } 88 c.Assert(err, qt.IsNil, errMsg) 89 c.Assert(result, qt.DeepEquals, test.expect, errMsg) 90 }) 91 } 92 }