Debian Codegraph @

starlark/testdata/proto.star

raw
1 # Tests of the experimental 'lib/proto' module.
2
3 load("assert.star", "assert")
4 load("proto.star", "proto")
5
6 schema = proto.file("test.proto")
7
8 m = schema.Test(
9 string_field="I'm a string!",
10 int32_field=42,
11 repeated_field=["a", "b", "c"],
12 map_field={"a": "A", "b": "B"}
13 )
14 assert.eq(type(m), "proto.Message")
15 assert.eq(type(m.repeated_field), "proto.repeated<string>")
16 assert.eq(type(m.map_field), "proto.map<string, string>")
17
18 assert.eq(m.string_field, "I'm a string!")
19 assert.eq(m.int32_field, 42)
20
21 assert.eq(list(m.repeated_field), ["a", "b", "c"])
22 assert.eq(len(m.repeated_field), 3)
23 m.repeated_field = ["d", "e"]
24 assert.eq(len(m.repeated_field), 2)
25 assert.eq(list(m.repeated_field), ["d", "e"])
26 m.repeated_field.append("f")
27 assert.eq(list(m.repeated_field), ["d", "e", "f"])
28 assert.eq(len(m.repeated_field), 3)
29
30 assert.eq(dict(m.map_field), {"a": "A", "b": "B"})
31 assert.eq(len(m.map_field), 2)
32 m.map_field["c"] = "C"
33 assert.eq(dict(m.map_field), {"a": "A", "b": "B", "c": "C"})
34 assert.eq(len(m.map_field), 3)
35
36 m.map_field = {"d": "D", "e": "E"}
37 assert.eq(dict(m.map_field), {"d": "D", "e": "E"})
38
39 m.map_field = None
40 assert.eq(dict(m.map_field), {})
41
42 # list ordering of keys
43 m.map_field = {"a": "A", "b": "B", "c": "C"}
44 assert.eq(list(m.map_field), ["a", "b", "c"])
45
46 # str
47 assert.eq(str(m.map_field), '{"a": "A", "b": "B", "c": "C"}')
48
49 # bool
50 assert.eq(bool(m.map_field), True)
51 assert.eq(bool(schema.Test().map_field), False)
52
53 # presence checks
54 found = "a" in m.map_field
55 assert.eq(found, True)
56 not_found = "z" in m.map_field
57 assert.eq(not_found, False)
58
59 # type checking
60 def _assign_bad_key():
61 m.map_field[1] = "X"
62 assert.fails(_assign_bad_key, "converting map key: got int, want string")
63 def _assign_bad_value():
64 m.map_field["a"] = 1
65 assert.fails(_assign_bad_value, "converting map value: got int, want string")
66
67 # not hashable
68 assert.fails(lambda: {m.map_field: 1}, "unhashable")
69
70 # Extensions
71
72 assert.eq(str(schema.ext_string_field), "go.starlark.net.testdata.ext_string_field")
73 assert.eq(type(schema.ext_string_field), "proto.FieldDescriptor")
74 assert.eq(dir(schema.ext_string_field), [])
75
76 m2 = schema.Test(string_field="A")
77 assert.eq(proto.has(m2, schema.ext_string_field), False)
78 proto.set_field(m2, schema.ext_string_field, "B")
79 assert.eq(proto.has(m2, schema.ext_string_field), True)
80 assert.eq(proto.get_field(m2, schema.ext_string_field), "B")