github.com/shohhei1126/hugo@v0.42.2-0.20180623210752-3d5928889ad7/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/deps"
    21  	"github.com/stretchr/testify/assert"
    22  	"github.com/stretchr/testify/require"
    23  )
    24  
    25  func TestIndex(t *testing.T) {
    26  	t.Parallel()
    27  
    28  	ns := New(&deps.Deps{})
    29  
    30  	for i, test := range []struct {
    31  		item    interface{}
    32  		indices []interface{}
    33  		expect  interface{}
    34  		isErr   bool
    35  	}{
    36  		{[]int{0, 1}, []interface{}{0}, 0, false},
    37  		{[]int{0, 1}, []interface{}{9}, nil, false}, // index out of range
    38  		{[]uint{0, 1}, nil, []uint{0, 1}, false},
    39  		{[][]int{{1, 2}, {3, 4}}, []interface{}{0, 0}, 1, false},
    40  		{map[int]int{1: 10, 2: 20}, []interface{}{1}, 10, false},
    41  		{map[int]int{1: 10, 2: 20}, []interface{}{0}, 0, false},
    42  		// errors
    43  		{nil, nil, nil, true},
    44  		{[]int{0, 1}, []interface{}{"1"}, nil, true},
    45  		{[]int{0, 1}, []interface{}{nil}, nil, true},
    46  		{tstNoStringer{}, []interface{}{0}, nil, true},
    47  	} {
    48  		errMsg := fmt.Sprintf("[%d] %v", i, test)
    49  
    50  		result, err := ns.Index(test.item, test.indices...)
    51  
    52  		if test.isErr {
    53  			require.Error(t, err, errMsg)
    54  			continue
    55  		}
    56  
    57  		require.NoError(t, err, errMsg)
    58  		assert.Equal(t, test.expect, result, errMsg)
    59  	}
    60  }