go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/starlarkproto/testdata/map_msg.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  msg = testprotos.MapWithMessageType()
    19  
    20  # Default value is empty dict.
    21  assert.eq(len(msg.m), 0)
    22  
    23  # Can set and get values, they are stored by reference.
    24  simple = testprotos.Simple(i=123)
    25  msg.m['k'] = simple
    26  assert.eq(msg.m['k'].i, 123)
    27  simple.i = 456
    28  assert.eq(msg.m['k'].i, 456)
    29  
    30  # None values are converted to empty messages. Use 'pop' to throw values away.
    31  msg.m['k'] = None
    32  assert.eq(type(msg.m['k']), 'proto.Message<testprotos.Simple>')
    33  assert.eq(str(msg.m['k']), '')
    34  msg.m.pop('k')
    35  assert.eq(msg.m.get('k'), None)
    36  
    37  # Dicts are converted to corresponding messages.
    38  msg.m['k'] = {'i': 999}
    39  assert.eq(msg.m['k'].i, 999)
    40  
    41  # Dicts with wrong schema are rejected.
    42  def bad_schema():
    43    msg.m['k'] = {'unknown': 123}
    44  assert.fails(bad_schema, 'proto.Message<testprotos.Simple> has no field "unknown"')
    45  
    46  # Serialization to text proto works.
    47  text = proto.to_textpb(testprotos.MapWithMessageType(m={
    48    'k1': testprotos.Simple(i=1),
    49    'k2': testprotos.Simple(i=2),
    50  }))
    51  assert.eq(text, """m {
    52    key: "k1"
    53    value {
    54      i: 1
    55    }
    56  }
    57  m {
    58    key: "k2"
    59    value {
    60      i: 2
    61    }
    62  }
    63  """)