go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/starlarkproto/testdata/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  m = testprotos.MessageFields()
    19  
    20  # The default value is zero value of the corresponding type (as we check by
    21  # grabbing a field from it, since == for proto messages is not implemented yet).
    22  assert.eq(m.single.i, 0)
    23  
    24  # Setter works.
    25  m.single = testprotos.Simple(i=123)
    26  assert.eq(m.single.i, 123)
    27  
    28  # We set by reference, not by value.
    29  ref = testprotos.Simple(i=456)
    30  m.single = ref
    31  assert.eq(m.single.i, 456)
    32  ref.i = 789
    33  assert.eq(m.single.i, 789)
    34  
    35  # Clearing resets the field to its default zero value.
    36  m.single = None
    37  assert.eq(m.single.i, 0)
    38  
    39  # Setting wrong type is forbidden.
    40  def set_as_int():
    41    m.single = 123
    42  assert.fails(set_as_int, 'got int, want proto.Message<testprotos.Simple>')
    43  
    44  # Setting to a message of a wrong type is also forbidden.
    45  def set_as_msg():
    46    m.single = testprotos.MessageFields()
    47  assert.fails(set_as_msg,
    48      'got proto.Message<testprotos.MessageFields>, want proto.Message<testprotos.Simple>')
    49  
    50  # Serialization works.
    51  text = proto.to_textpb(testprotos.MessageFields(single=testprotos.Simple(i=999)))
    52  assert.eq(text, """single {
    53    i: 999
    54  }
    55  """)