go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/starlarkproto/testdata/oneof.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.Complex() 19 20 # Oneof alternatives have no defaults. 21 assert.eq(m.simple, None) 22 assert.eq(m.another_simple, None) 23 24 # Setting one alternative resets the other (and doesn't touch other fields). 25 m.i64 = 123 26 m.simple = testprotos.Simple() 27 assert.true(m.simple != None) 28 assert.true(m.another_simple == None) 29 assert.eq(m.i64, 123) 30 m.another_simple = testprotos.AnotherSimple() 31 assert.true(m.simple == None) 32 assert.true(m.another_simple != None) 33 assert.eq(m.i64, 123) 34 35 # Setting a "picked" alternative to None resets it. 36 assert.true(m.another_simple != None) 37 m.another_simple = None 38 assert.true(m.another_simple == None) 39 40 # Setting some other alternative to None does nothing. 41 m.simple = testprotos.Simple() 42 m.another_simple = None 43 assert.true(m.simple != None) 44 45 # In constructors the last kwarg wins (starlark dicts preserve order). 46 m2 = testprotos.Complex( 47 simple=testprotos.Simple(), 48 another_simple=testprotos.AnotherSimple()) 49 assert.true(m2.simple == None) 50 assert.true(m2.another_simple != None) 51 m3 = testprotos.Complex( 52 another_simple=testprotos.AnotherSimple(), 53 simple=testprotos.Simple()) 54 assert.true(m3.simple != None) 55 assert.true(m3.another_simple == None) 56 57 # Serialization works. 58 assert.eq( 59 proto.to_textpb(testprotos.Complex(simple=testprotos.Simple(i=1))), 60 "simple {\n i: 1\n}\n")