go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/starlarkproto/testdata/from_jsonpb.star (about) 1 # Copyright 2019 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 # Works in general. Detailed tests for type conversions are in from_proto.star. 19 m = proto.from_jsonpb(testprotos.Simple, '{"i": 123}') 20 assert.eq(type(m), 'proto.Message<testprotos.Simple>') 21 assert.eq(m.i, 123) 22 23 # Unrecognized fields are OK. 24 proto.from_jsonpb(testprotos.Simple, '{"unknown": 123}') 25 26 # Unrecognized fields are rejected if discard_unknown is false. 27 def from_jsonpb_reject_unknown(): 28 proto.from_jsonpb(testprotos.Simple, '{"unknown": 123}', discard_unknown = False) 29 assert.fails(from_jsonpb_reject_unknown, 'unknown field') 30 31 # The returned message is frozen. 32 def from_jsonpb_frozen(): 33 proto.from_jsonpb(testprotos.Simple, '{"i": 123}').i = 456 34 assert.fails(from_jsonpb_frozen, 'cannot modify frozen') 35 36 # Bad JSONPB proto. 37 def from_jsonpb_bad_proto(): 38 proto.from_jsonpb(testprotos.Simple, 'huh?') 39 assert.fails(from_jsonpb_bad_proto, "syntax error") 40 41 # Too many arguments. 42 def from_jsonpb_too_many_args(): 43 proto.from_jsonpb(testprotos.Simple, '{"i": 123}', True, True) 44 assert.fails(from_jsonpb_too_many_args, 'from_jsonpb: got 4 arguments, want at most 3') 45 46 # Wrong type for constructor. 47 def from_jsonpb_with_wrong_ctor(): 48 proto.from_jsonpb(lambda: None, '{"i": 123}') 49 assert.fails(from_jsonpb_with_wrong_ctor, 'from_jsonpb: got function, expecting a proto message constructor')