go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/starlarkproto/testdata/misc.star (about) 1 # Copyright 2018 The LUCI Authors. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 l = proto.new_loader(proto.new_descriptor_set(blob=read('./testprotos/all.pb'))) 16 testprotos = l.module('go.chromium.org/luci/starlark/starlarkproto/testprotos/test.proto') 17 18 m = testprotos.Simple() 19 20 # type() works. 21 assert.eq(type(m), 'proto.Message<testprotos.Simple>') 22 23 # proto.message_type() works. 24 assert.eq(proto.message_type(m), testprotos.Simple) 25 26 # dir() works. 27 assert.eq(dir(m), ['i', 'many_i']) 28 29 # All proto messages are truthy. 30 assert.true(bool(m)) 31 32 # Stringification works. 33 assert.eq(str(testprotos.Simple(i=123)), 'i: 123') 34 assert.eq(str(testprotos.Complex(i64=1, msg_val={'i': 1})), 'i64: 1\nmsg_val { i: 1 }') 35 36 # Stringifying the type returns its proto type name. 37 assert.eq(str(testprotos.Simple), 'testprotos.Simple') 38 39 # Assigning totally unsupported types to fields fails. 40 def set_unrelated(): 41 m.i = set([]) 42 assert.fails(set_unrelated, 'got set, want int') 43 44 # Grabbing unknown field fails. 45 def get_unknown(): 46 print(m.zzz) 47 assert.fails(get_unknown, 'proto.Message<testprotos.Simple> has no field "zzz"') 48 49 # Setting unknown field fails. 50 def set_unknown(): 51 m.zzz = 123 52 assert.fails(set_unknown, 'proto.Message<testprotos.Simple> has no field "zzz"') 53 54 # Proto messages are non-hashable currently. 55 def use_as_key(): 56 d = {m: 123} 57 assert.fails(use_as_key, 'not hashable') 58 59 # dir(...) on a message namespace works. 60 assert.eq(dir(testprotos.Complex), ['ENUM_VAL_1', 'InnerMessage', 'UNKNOWN']) 61 62 # Attempting to access undefined inner message type fails. 63 def unknown_inner(): 64 testprotos.Complex.Blah() 65 assert.fails(unknown_inner, 'proto.MessageType has no .Blah field or method') 66 67 # Attempting to replace inner message type fails. 68 def replace_inner(): 69 testprotos.Complex.InnerMessage = None 70 assert.fails(replace_inner, 'can\'t assign to .InnerMessage field of proto.MessageType') 71 72 # Using message_type or non-proto fails. 73 assert.fails(lambda: proto.message_type(123), 'got int, want proto.Message')