github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/core/elvish/eval/vals/index_test.go (about)

     1  package vals
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/u-root/u-root/cmds/core/elvish/tt"
     7  )
     8  
     9  var (
    10  	li0 = EmptyList
    11  	li4 = MakeList("foo", "bar", "lorem", "ipsum")
    12  	m   = MakeMapFromKV("foo", "bar", "lorem", "ipsum")
    13  )
    14  
    15  var indexTests = tt.Table{
    16  	// List indices
    17  	// ============
    18  
    19  	// Simple indicies: 0 <= i < n.
    20  	Args(li4, "0").Rets("foo", nil),
    21  	Args(li4, "3").Rets("ipsum", nil),
    22  	Args(li0, "0").Rets(any, anyError),
    23  	Args(li4, "4").Rets(any, anyError),
    24  	Args(li4, "5").Rets(any, anyError),
    25  	// Negative indices: -n <= i < 0.
    26  	Args(li4, "-1").Rets("ipsum", nil),
    27  	Args(li4, "-4").Rets("foo", nil),
    28  	Args(li4, "-5").Rets(any, anyError), // Too negative.
    29  	// Decimal indicies are not allowed even if the value is an integer.
    30  	Args(li4, "0.0").Rets(any, anyError),
    31  
    32  	// Slice indicies: 0 <= i <= j <= n.
    33  	Args(li4, "1:3").Rets(eq(MakeList("bar", "lorem")), nil),
    34  	Args(li4, "3:4").Rets(eq(MakeList("ipsum")), nil),
    35  	Args(li4, "4:4").Rets(eq(EmptyList), nil), // i == j == n is allowed.
    36  	// i defaults to 0
    37  	Args(li4, ":2").Rets(eq(MakeList("foo", "bar")), nil),
    38  	Args(li4, ":-1").Rets(eq(MakeList("foo", "bar", "lorem")), nil),
    39  	// j defaults to n
    40  	Args(li4, "3:").Rets(eq(MakeList("ipsum")), nil),
    41  	Args(li4, "-2:").Rets(eq(MakeList("lorem", "ipsum")), nil),
    42  	// Both indices can be omitted.
    43  	Args(li0, ":").Rets(eq(li0), nil),
    44  	Args(li4, ":").Rets(eq(li4), nil),
    45  
    46  	// Malformed list indices.
    47  	Args(li4, "a").Rets(any, anyError),
    48  	Args(li4, "1:3:2").Rets(any, anyError),
    49  
    50  	// Map indicies
    51  	Args(m, "foo").Rets("bar", nil),
    52  	Args(m, "bad").Rets(any, anyError),
    53  }
    54  
    55  func TestIndex(t *testing.T) {
    56  	tt.Test(t, tt.Fn("Index", Index), indexTests)
    57  }