go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/starlarkproto/testdata/to_jsonpb.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.SimpleFields()
    19  
    20  # Works in general.
    21  m.i64 = 123
    22  m.b = True
    23  assert.eq(proto.to_jsonpb(m), """{
    24  	"i64": "123",
    25  	"b": true
    26  }""")
    27  
    28  # Omits defaults.
    29  m.i64 = 0
    30  m.b = False
    31  assert.eq(proto.to_jsonpb(m), '{}')
    32  
    33  # Obeys the use_proto_names argument.
    34  m.str_rep = ["hello"]
    35  assert.eq(proto.to_jsonpb(m), """{
    36  	"strRep": [
    37  		"hello"
    38  	]
    39  }""")
    40  assert.eq(proto.to_jsonpb(m, use_proto_names = True), """{
    41  	"str_rep": [
    42  		"hello"
    43  	]
    44  }""")
    45  
    46  # to_jsonpb expects an argument.
    47  def to_jsonpb_no_args():
    48    proto.to_jsonpb()
    49  assert.fails(to_jsonpb_no_args, 'missing argument for msg')
    50  
    51  # Too many arguments.
    52  def to_jsonpb_too_many_args():
    53    proto.to_jsonpb(m, False, False)
    54  assert.fails(to_jsonpb_too_many_args, 'to_jsonpb: got 3 arguments, want at most 2')
    55  
    56  # None argument.
    57  def to_jsonpb_with_none():
    58    proto.to_jsonpb(None)
    59  assert.fails(to_jsonpb_with_none, 'to_jsonpb: for parameter msg: got NoneType, want proto.Message')
    60  
    61  # Wrongly typed argument.
    62  def to_jsonpb_with_int():
    63    proto.to_jsonpb(1)
    64  assert.fails(to_jsonpb_with_int, 'to_jsonpb: for parameter msg: got int, want proto.Message')