go.starlark.net@v0.0.0-20231101134539-556fd59b42f6/starlark/testdata/builtins.star (about)

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