...

Text file src/go.starlark.net/starlarkstruct/testdata/struct.star

Documentation: go.starlark.net/starlarkstruct/testdata

     1# Tests of Starlark 'struct' extension.
     2# This is not a standard feature and the Go and Starlark APIs may yet change.
     3
     4load("assert.star", "assert")
     5
     6assert.eq(str(struct), "<built-in function struct>")
     7
     8# struct is a constructor for "unbranded" structs.
     9s = struct(host = "localhost", port = 80)
    10assert.eq(s, s)
    11assert.eq(s, struct(host = "localhost", port = 80))
    12assert.ne(s, struct(host = "localhost", port = 81))
    13assert.eq(type(s), "struct")
    14assert.eq(str(s), 'struct(host = "localhost", port = 80)')
    15assert.eq(s.host, "localhost")
    16assert.eq(s.port, 80)
    17assert.fails(lambda : s.protocol, "struct has no .protocol attribute")
    18assert.eq(dir(s), ["host", "port"])
    19
    20# Use gensym to create "branded" struct types.
    21hostport = gensym(name = "hostport")
    22assert.eq(type(hostport), "symbol")
    23assert.eq(str(hostport), "hostport")
    24
    25# Call the symbol to instantiate a new type.
    26http = hostport(host = "localhost", port = 80)
    27assert.eq(type(http), "struct")
    28assert.eq(str(http), 'hostport(host = "localhost", port = 80)')  # includes name of constructor
    29assert.eq(http, http)
    30assert.eq(http, hostport(host = "localhost", port = 80))
    31assert.ne(http, hostport(host = "localhost", port = 443))
    32assert.eq(http.host, "localhost")
    33assert.eq(http.port, 80)
    34assert.fails(lambda : http.protocol, "hostport struct has no .protocol attribute")
    35
    36person = gensym(name = "person")
    37bob = person(name = "bob", age = 50)
    38alice = person(name = "alice", city = "NYC")
    39assert.ne(http, bob)  # different constructor symbols
    40assert.ne(bob, alice)  # different fields
    41
    42hostport2 = gensym(name = "hostport")
    43assert.eq(hostport, hostport)
    44assert.ne(hostport, hostport2)  # same name, different symbol
    45assert.ne(http, hostport2(host = "localhost", port = 80))  # equal fields but different ctor symbols
    46
    47# dir
    48assert.eq(dir(alice), ["city", "name"])
    49assert.eq(dir(bob), ["age", "name"])
    50assert.eq(dir(http), ["host", "port"])
    51
    52# hasattr, getattr
    53assert.true(hasattr(alice, "city"))
    54assert.eq(hasattr(alice, "ageaa"), False)
    55assert.eq(getattr(alice, "city"), "NYC")
    56
    57# +
    58assert.eq(bob + bob, bob)
    59assert.eq(bob + alice, person(age = 50, city = "NYC", name = "alice"))
    60assert.eq(alice + bob, person(age = 50, city = "NYC", name = "bob"))  # not commutative! a misfeature
    61assert.fails(lambda : alice + 1, "struct \\+ int")
    62assert.eq(http + http, http)
    63assert.fails(lambda : http + bob, "different constructors: hostport \\+ person")

View as plain text