go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/starlarkproto/testdata/enums.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  # Enum constants follow C++ namespacing rules: they directly live in a namespace
    19  # that defines the enum type itself. This also matches how proto enum are
    20  # exposed in Python code.
    21  #
    22  # Values are represented by untyped integers. There's no type checks whatsoever
    23  # when getting or setting enum-valued fields.
    24  
    25  # Package-level enums.
    26  assert.eq(testprotos.ENUM_DEFAULT, 0)
    27  assert.eq(testprotos.ENUM_VAL_1, 1)
    28  
    29  # Nested enums.
    30  assert.eq(testprotos.Complex.UNKNOWN, 0)
    31  assert.eq(testprotos.Complex.ENUM_VAL_1, 1)
    32  
    33  m = testprotos.Complex()
    34  
    35  # Enum valued field has a default.
    36  assert.eq(m.enum_val, 0)
    37  
    38  # Enum valued field can be set and read.
    39  m.enum_val = testprotos.Complex.ENUM_VAL_1
    40  assert.eq(m.enum_val, testprotos.Complex.ENUM_VAL_1)
    41  
    42  # Can be reset.
    43  m.enum_val = None
    44  assert.eq(m.enum_val, 0)
    45  
    46  # Per proto3 spec, enum-valued field can be set to an arbitrary int32 integer.
    47  m.enum_val = 123
    48  assert.eq(m.enum_val, 123)
    49  
    50  # Serialization works.
    51  assert.eq(
    52      proto.to_textpb(testprotos.Complex(enum_val=testprotos.Complex.ENUM_VAL_1)),
    53      "enum_val: ENUM_VAL_1\n")
    54  
    55  # Setting to a wrong type fails.
    56  def set_bad_val():
    57    m.enum_val = ''
    58  assert.fails(set_bad_val, 'got string, want int')
    59  
    60  # Attempting to overwrite enum constant fails.
    61  def overwrite_global():
    62    testprotos.ENUM_DEFAULT = 10
    63  assert.fails(overwrite_global, 'can\'t assign to .ENUM_DEFAULT field of module')
    64  def overwrite_nested():
    65    testprotos.Complex.UNKNOWN = 10
    66  assert.fails(overwrite_nested, 'can\'t assign to .UNKNOWN field of proto.MessageType')