github.com/k14s/starlark-go@v0.0.0-20200720175618-3a5c849cc368/starlark/testdata/builtins.star (about)

     1  # Tests of Starlark built-in functions
     2  # option:float option:set
     3  
     4  load("assert.star", "assert")
     5  
     6  # len
     7  assert.eq(len([1, 2, 3]), 3)
     8  assert.eq(len((1, 2, 3)), 3)
     9  assert.eq(len({1: 2}), 1)
    10  assert.fails(lambda: len(1), "int.*has no len")
    11  
    12  # and, or
    13  assert.eq(123 or "foo", 123)
    14  assert.eq(0 or "foo", "foo")
    15  assert.eq(123 and "foo", "foo")
    16  assert.eq(0 and "foo", 0)
    17  none = None
    18  _1 = none and none[0]      # rhs is not evaluated
    19  _2 = (not none) or none[0] # rhs is not evaluated
    20  
    21  # any, all
    22  assert.true(all([]))
    23  assert.true(all([1, True, "foo"]))
    24  assert.true(not all([1, True, ""]))
    25  assert.true(not any([]))
    26  assert.true(any([0, False, "foo"]))
    27  assert.true(not any([0, False, ""]))
    28  
    29  # in
    30  assert.true(3 in [1, 2, 3])
    31  assert.true(4 not in [1, 2, 3])
    32  assert.true(3 in (1, 2, 3))
    33  assert.true(4 not in (1, 2, 3))
    34  assert.fails(lambda: 3 in "foo", "in.*requires string as left operand")
    35  assert.true(123 in {123: ""})
    36  assert.true(456 not in {123:""})
    37  assert.true([] not in {123: ""})
    38  
    39  # sorted
    40  assert.eq(sorted([42, 123, 3]), [3, 42, 123])
    41  assert.eq(sorted([42, 123, 3], reverse=True), [123, 42, 3])
    42  assert.eq(sorted(["wiz", "foo", "bar"]), ["bar", "foo", "wiz"])
    43  assert.eq(sorted(["wiz", "foo", "bar"], reverse=True), ["wiz", "foo", "bar"])
    44  assert.fails(lambda: sorted([1, 2, None, 3]), "int < NoneType not implemented")
    45  assert.fails(lambda: sorted([1, "one"]), "string < int not implemented")
    46  # custom key function
    47  assert.eq(sorted(["two", "three", "four"], key=len),
    48            ["two", "four", "three"])
    49  assert.eq(sorted(["two", "three", "four"], key=len, reverse=True),
    50            ["three", "four", "two"])
    51  assert.fails(lambda: sorted([1, 2, 3], key=None), "got NoneType, want callable")
    52  # sort is stable
    53  pairs = [(4, 0), (3, 1), (4, 2), (2, 3), (3, 4), (1, 5), (2, 6), (3, 7)]
    54  assert.eq(sorted(pairs, key=lambda x: x[0]),
    55            [(1, 5),
    56             (2, 3), (2, 6),
    57             (3, 1), (3, 4), (3, 7),
    58             (4, 0), (4, 2)])
    59  assert.fails(lambda: sorted(1), 'sorted: for parameter iterable: got int, want iterable')
    60  
    61  # reversed
    62  assert.eq(reversed([1, 144, 81, 16]), [16, 81, 144, 1])
    63  
    64  # set
    65  assert.contains(set([1, 2, 3]), 1)
    66  assert.true(4 not in set([1, 2, 3]))
    67  assert.eq(len(set([1, 2, 3])), 3)
    68  assert.eq(sorted([x for x in set([1, 2, 3])]), [1, 2, 3])
    69  
    70  # dict
    71  assert.eq(dict([(1, 2), (3, 4)]), {1: 2, 3: 4})
    72  assert.eq(dict([(1, 2), (3, 4)], foo="bar"), {1: 2, 3: 4, "foo": "bar"})
    73  assert.eq(dict({1:2, 3:4}), {1: 2, 3: 4})
    74  assert.eq(dict({1:2, 3:4}.items()), {1: 2, 3: 4})
    75  
    76  # range
    77  assert.eq("range", type(range(10)))
    78  assert.eq("range(10)", str(range(0, 10, 1)))
    79  assert.eq("range(1, 10)", str(range(1, 10)))
    80  assert.eq(range(0, 5, 10), range(0, 5, 11))
    81  assert.eq("range(0, 10, -1)", str(range(0, 10, -1)))
    82  assert.fails(lambda: {range(10): 10}, "unhashable: range")
    83  assert.true(bool(range(1, 2)))
    84  assert.true(not(range(2, 1))) # an empty range is false
    85  assert.eq([x*x for x in range(5)], [0, 1, 4, 9, 16])
    86  assert.eq(list(range(5)), [0, 1, 2, 3, 4])
    87  assert.eq(list(range(-5)), [])
    88  assert.eq(list(range(2, 5)), [2, 3, 4])
    89  assert.eq(list(range(5, 2)), [])
    90  assert.eq(list(range(-2, -5)), [])
    91  assert.eq(list(range(-5, -2)), [-5, -4, -3])
    92  assert.eq(list(range(2, 10, 3)), [2, 5, 8])
    93  assert.eq(list(range(10, 2, -3)), [10, 7, 4])
    94  assert.eq(list(range(-2, -10, -3)), [-2, -5, -8])
    95  assert.eq(list(range(-10, -2, 3)), [-10, -7, -4])
    96  assert.eq(list(range(10, 2, -1)), [10, 9, 8, 7, 6, 5, 4, 3])
    97  assert.eq(list(range(5)[1:]), [1, 2, 3, 4])
    98  assert.eq(len(range(5)[1:]), 4)
    99  assert.eq(list(range(5)[:2]), [0, 1])
   100  assert.eq(list(range(10)[1:]), [1, 2, 3, 4, 5, 6, 7, 8, 9])
   101  assert.eq(list(range(10)[1:9:2]), [1, 3, 5, 7])
   102  assert.eq(list(range(10)[1:10:2]), [1, 3, 5, 7, 9])
   103  assert.eq(list(range(10)[1:11:2]), [1, 3, 5, 7, 9])
   104  assert.eq(list(range(10)[::-2]), [9, 7, 5, 3, 1])
   105  assert.eq(list(range(0, 10, 2)[::2]), [0, 4, 8])
   106  assert.eq(list(range(0, 10, 2)[::-2]), [8, 4, 0])
   107  assert.fails(lambda: range(3000000000), "3000000000 out of range") # signed 32-bit values only
   108  assert.eq(len(range(0x7fffffff)), 0x7fffffff) # O(1)
   109  # Two ranges compare equal if they denote the same sequence:
   110  assert.eq(range(0), range(2, 1, 3))       # []
   111  assert.eq(range(0, 3, 2), range(0, 4, 2)) # [0, 2]
   112  assert.ne(range(1, 10), range(2, 10))
   113  assert.fails(lambda: range(0) < range(0), "range < range not implemented")
   114  # <number> in <range>
   115  assert.contains(range(3), 1)
   116  assert.contains(range(3), 2.0)    # acts like 2
   117  assert.fails(lambda: True in range(3), "requires integer.*not bool") # bools aren't numbers
   118  assert.fails(lambda: "one" in range(10), "requires integer.*not string")
   119  assert.true(4 not in range(4))
   120  assert.true(1e15 not in range(4)) # too big for int32
   121  assert.true(1e100 not in range(4)) # too big for int64
   122  # https://github.com/google/starlark-go/issues/116
   123  assert.fails(lambda: range(0, 0, 2)[:][0], "index 0 out of range: empty range")
   124  
   125  # list
   126  assert.eq(list("abc".elems()), ["a", "b", "c"])
   127  assert.eq(sorted(list({"a": 1, "b": 2})), ['a', 'b'])
   128  
   129  # min, max
   130  assert.eq(min(5, -2, 1, 7, 3), -2)
   131  assert.eq(max(5, -2, 1, 7, 3), 7)
   132  assert.eq(min([5, -2, 1, 7, 3]), -2)
   133  assert.eq(min("one", "two", "three", "four"), "four")
   134  assert.eq(max("one", "two", "three", "four"), "two")
   135  assert.fails(min, "min requires at least one positional argument")
   136  assert.fails(lambda: min(1), "not iterable")
   137  assert.fails(lambda: min([]), "empty")
   138  assert.eq(min(5, -2, 1, 7, 3, key=lambda x: x*x), 1) # min absolute value
   139  assert.eq(min(5, -2, 1, 7, 3, key=lambda x: -x), 7) # min negated value
   140  
   141  # enumerate
   142  assert.eq(enumerate("abc".elems()), [(0, "a"), (1, "b"), (2, "c")])
   143  assert.eq(enumerate([False, True, None], 42), [(42, False), (43, True), (44, None)])
   144  
   145  # zip
   146  assert.eq(zip(), [])
   147  assert.eq(zip([]), [])
   148  assert.eq(zip([1, 2, 3]), [(1,), (2,), (3,)])
   149  assert.eq(zip("".elems()), [])
   150  assert.eq(zip("abc".elems(),
   151                list("def".elems()),
   152                "hijk".elems()),
   153            [("a", "d", "h"), ("b", "e", "i"), ("c", "f", "j")])
   154  z1 = [1]
   155  assert.eq(zip(z1), [(1,)])
   156  z1.append(2)
   157  assert.eq(zip(z1), [(1,), (2,)])
   158  assert.fails(lambda: zip(z1, 1), "zip: argument #2 is not iterable: int")
   159  z1.append(3)
   160  
   161  # dir for builtin_function_or_method
   162  assert.eq(dir(None), [])
   163  assert.eq(dir({})[:3], ["clear", "get", "items"]) # etc
   164  assert.eq(dir(1), [])
   165  assert.eq(dir([])[:3], ["append", "clear", "extend"]) # etc
   166  
   167  # hasattr, getattr, dir
   168  # hasfields is an application-defined type defined in eval_test.go.
   169  hf = hasfields()
   170  assert.eq(dir(hf), [])
   171  assert.true(not hasattr(hf, "x"))
   172  assert.fails(lambda: getattr(hf, "x"), "no .x field or method")
   173  assert.eq(getattr(hf, "x", 42), 42)
   174  hf.x = 1
   175  assert.true(hasattr(hf, "x"))
   176  assert.eq(getattr(hf, "x"), 1)
   177  assert.eq(hf.x, 1)
   178  hf.x = 2
   179  assert.eq(getattr(hf, "x"), 2)
   180  assert.eq(hf.x, 2)
   181  # built-in types can have attributes (methods) too.
   182  myset = set([])
   183  assert.eq(dir(myset), ["union"])
   184  assert.true(hasattr(myset, "union"))
   185  assert.true(not hasattr(myset, "onion"))
   186  assert.eq(str(getattr(myset, "union")), "<built-in method union of set value>")
   187  assert.fails(lambda: getattr(myset, "onion"), "no .onion field or method")
   188  assert.eq(getattr(myset, "onion", 42), 42)
   189  
   190  # dir returns a new, sorted, mutable list
   191  assert.eq(sorted(dir("")), dir("")) # sorted
   192  dir("").append("!") # mutable
   193  assert.true("!" not in dir("")) # new
   194  
   195  # error messages should suggest spelling corrections
   196  hf.one = 1
   197  hf.two = 2
   198  hf.three = 3
   199  hf.forty_five = 45
   200  assert.fails(lambda: hf.One, 'no .One field.*did you mean .one')
   201  assert.fails(lambda: hf.oone, 'no .oone field.*did you mean .one')
   202  assert.fails(lambda: hf.FortyFive, 'no .FortyFive field.*did you mean .forty_five')
   203  assert.fails(lambda: hf.trhee, 'no .trhee field.*did you mean .three')
   204  assert.fails(lambda: hf.thirty, 'no .thirty field or method$') # no suggestion
   205  
   206  # spell check in setfield too
   207  def setfield(): hf.noForty_Five = 46  # "no" prefix => SetField returns NoSuchField
   208  assert.fails(setfield, 'no .noForty_Five field.*did you mean .forty_five')
   209  
   210  # repr
   211  assert.eq(repr(1), "1")
   212  assert.eq(repr("x"), '"x"')
   213  assert.eq(repr(["x", 1]), '["x", 1]')
   214  
   215  # fail
   216  ---
   217  fail() ### `fail: $`
   218  x = 1//0 # unreachable
   219  ---
   220  fail(1) ### `fail: 1`
   221  ---
   222  fail(1, 2, 3) ### `fail: 1 2 3`
   223  ---
   224  fail(1, 2, 3, sep="/") ### `fail: 1/2/3`