go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/starlarkproto/testdata/json.star (about)

     1  # Copyright 2021 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  # String fields with luci.text_pb_format option=JSON get formatted across
    19  # multiple lines
    20  
    21  m = testprotos.SimpleFields()
    22  m.json = '{"foo": 0, "bar": "blah", "baz": ["x", "y", "z"]}'
    23  assert.eq(proto.to_textpb(m), """\
    24  json:
    25    '{'
    26    '  "foo": 0,'
    27    '  "bar": "blah",'
    28    '  "baz": ['
    29    '    "x",'
    30    '    "y",'
    31    '    "z"'
    32    '  ]'
    33    '}'
    34  """)
    35  
    36  def set_json_invalid():
    37      m.json = 'foo'
    38      proto.to_textpb(m)
    39  assert.fails(set_json_invalid, "value for 'json' must be valid JSON, got value 'foo'")
    40  
    41  m2 = testprotos.SimpleFields()
    42  m2.json_rep = ['{"foo": 0}', '{"bar": 1}']
    43  assert.eq(proto.to_textpb(m2), """\
    44  json_rep:
    45    '{'
    46    '  "foo": 0'
    47    '}'
    48  json_rep:
    49    '{'
    50    '  "bar": 1'
    51    '}'
    52  """)
    53  
    54  def set_json_rep_invalid():
    55      m2.json_rep = ['foo']
    56      proto.to_textpb(m2)
    57  assert.fails(set_json_rep_invalid, "value for 'json_rep' must be valid JSON, got value 'foo'")
    58  
    59  m3 = testprotos.NestedJson()
    60  m3.nested = testprotos.Json()
    61  m3.nested.json = '{"foo": 0, "bar": 1}'
    62  assert.eq(proto.to_textpb(m3), """\
    63  nested {
    64    json:
    65      '{'
    66      '  "foo": 0,'
    67      '  "bar": 1'
    68      '}'
    69  }
    70  """)
    71  
    72  def set_nested_json_invalid():
    73      m3.nested.json = 'foo'
    74      proto.to_textpb(m3)
    75  assert.fails(set_nested_json_invalid, "value for 'nested.json' must be valid JSON, got value 'foo'")