Python google.protobuf.text_format.MessageToString() Examples

The following are code examples for showing how to use google.protobuf.text_format.MessageToString(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 6 votes vote down vote up
def testPrintExotic(self, message_module):
    message = message_module.TestAllTypes()
    message.repeated_int64.append(-9223372036854775808)
    message.repeated_uint64.append(18446744073709551615)
    message.repeated_double.append(123.456)
    message.repeated_double.append(1.23e22)
    message.repeated_double.append(1.23e-18)
    message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
    message.repeated_string.append(u'\u00fc\ua71f')
    self.CompareToGoldenText(
        self.RemoveRedundantZeros(text_format.MessageToString(message)),
        'repeated_int64: -9223372036854775808\n'
        'repeated_uint64: 18446744073709551615\n'
        'repeated_double: 123.456\n'
        'repeated_double: 1.23e+22\n'
        'repeated_double: 1.23e-18\n'
        'repeated_string:'
        ' "\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""\n'
        'repeated_string: "\\303\\274\\352\\234\\237"\n') 
Example 2
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 6 votes vote down vote up
def testPrintExoticAsOneLine(self, message_module):
    message = message_module.TestAllTypes()
    message.repeated_int64.append(-9223372036854775808)
    message.repeated_uint64.append(18446744073709551615)
    message.repeated_double.append(123.456)
    message.repeated_double.append(1.23e22)
    message.repeated_double.append(1.23e-18)
    message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
    message.repeated_string.append(u'\u00fc\ua71f')
    self.CompareToGoldenText(
        self.RemoveRedundantZeros(text_format.MessageToString(
            message, as_one_line=True)),
        'repeated_int64: -9223372036854775808'
        ' repeated_uint64: 18446744073709551615'
        ' repeated_double: 123.456'
        ' repeated_double: 1.23e+22'
        ' repeated_double: 1.23e-18'
        ' repeated_string: '
        '"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""'
        ' repeated_string: "\\303\\274\\352\\234\\237"') 
Example 3
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 6 votes vote down vote up
def testPrintMessageSet(self):
    message = unittest_mset_pb2.TestMessageSetContainer()
    ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
    ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
    message.message_set.Extensions[ext1].i = 23
    message.message_set.Extensions[ext2].str = 'foo'
    self.CompareToGoldenText(
        text_format.MessageToString(message), 'message_set {\n'
        '  [protobuf_unittest.TestMessageSetExtension1] {\n'
        '    i: 23\n'
        '  }\n'
        '  [protobuf_unittest.TestMessageSetExtension2] {\n'
        '    str: \"foo\"\n'
        '  }\n'
        '}\n')

    message = message_set_extensions_pb2.TestMessageSet()
    ext = message_set_extensions_pb2.message_set_extension3
    message.Extensions[ext].text = 'bar'
    self.CompareToGoldenText(
        text_format.MessageToString(message),
        '[google.protobuf.internal.TestMessageSetExtension3] {\n'
        '  text: \"bar\"\n'
        '}\n') 
Example 4
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 6 votes vote down vote up
def testPrintMessageExpandAnyRepeated(self):
    packed_message = unittest_pb2.OneString()
    message = any_test_pb2.TestAny()
    packed_message.data = 'string0'
    message.repeated_any_value.add().Pack(packed_message)
    packed_message.data = 'string1'
    message.repeated_any_value.add().Pack(packed_message)
    self.assertEqual(
        text_format.MessageToString(message),
        'repeated_any_value {\n'
        '  [type.googleapis.com/protobuf_unittest.OneString] {\n'
        '    data: "string0"\n'
        '  }\n'
        '}\n'
        'repeated_any_value {\n'
        '  [type.googleapis.com/protobuf_unittest.OneString] {\n'
        '    data: "string1"\n'
        '  }\n'
        '}\n') 
Example 5
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 6 votes vote down vote up
def testPrettyPrintMultiLine(self, message_module):

    def printer(m, indent, as_one_line):
      if m.DESCRIPTOR == message_module.TestAllTypes.NestedMessage.DESCRIPTOR:
        line_deliminator = (' ' if as_one_line else '\n') + ' ' * indent
        return 'My lucky number is:%s%s' % (line_deliminator, m.bb)
      return None

    message = message_module.TestAllTypes()
    msg = message.repeated_nested_message.add()
    msg.bb = 42
    self.CompareToGoldenText(
        text_format.MessageToString(
            message, as_one_line=True, message_formatter=printer),
        'repeated_nested_message { My lucky number is: 42 }')
    self.CompareToGoldenText(
        text_format.MessageToString(
            message, as_one_line=False, message_formatter=printer),
        'repeated_nested_message {\n  My lucky number is:\n  42\n}\n') 
Example 6
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 6 votes vote down vote up
def testPrettyPrintEntireMessage(self, message_module):

    def printer(m, indent, as_one_line):
      del indent, as_one_line
      if m.DESCRIPTOR == message_module.TestAllTypes.DESCRIPTOR:
        return 'The is the message!'
      return None

    message = message_module.TestAllTypes()
    self.CompareToGoldenText(
        text_format.MessageToString(
            message, as_one_line=False, message_formatter=printer),
        'The is the message!\n')
    self.CompareToGoldenText(
        text_format.MessageToString(
            message, as_one_line=True, message_formatter=printer),
        'The is the message!') 
Example 7
Project: recipes-py   Author: luci   File: build.py    Apache License 2.0 6 votes vote down vote up
def RunSteps(api):
  text = text_format.MessageToString(api.buildbucket.build)
  api.step('build', ['echo'] + text.splitlines())
  api.step('hostname', ['echo', api.buildbucket.host])
  api.step('is_critical', ['echo', api.buildbucket.is_critical()])

  child_build_tags = [
      '%s:%s' % t
      for t in api.buildbucket.tags_for_child_build.iteritems()
  ]
  api.step('tags_for_child_build', ['echo'] + child_build_tags)

  api.assertions.assertEqual(
      api.buildbucket.bucket_v1,
      api.properties.get('expected_bucket_v1'))
  api.assertions.assertEqual(
      api.buildbucket.builder_name,
      api.buildbucket.build.builder.builder)
  api.assertions.assertEqual(
      api.buildbucket.gitiles_commit,
      api.buildbucket.build.input.gitiles_commit) 
Example 8
Project: gftools   Author: googlefonts   File: gftools-add-font.py    Apache License 2.0 6 votes vote down vote up
def main(argv):
  if len(argv) != 2:
    sys.exit('One argument, a directory containing a font family')
  fontdir = argv[1]

  is_new = True
  old_metadata_file = os.path.join(fontdir, 'METADATA.pb')
  if os.path.isfile(old_metadata_file):
    is_new = False

  metadata = _MakeMetadata(fontdir, is_new)
  text_proto = text_format.MessageToString(metadata)

  desc = os.path.join(fontdir, 'DESCRIPTION.en_us.html')
  if os.path.isfile(desc):
    print('DESCRIPTION.en_us.html exists')
  else:
    _WriteTextFile(desc, 'N/A')

  _WriteTextFile(os.path.join(fontdir, 'METADATA.pb'), text_proto) 
Example 9
Project: tf-object-detection   Author: ndaidong   File: config_util.py    MIT License 6 votes vote down vote up
def save_pipeline_config(pipeline_config, directory):
  """Saves a pipeline config text file to disk.

  Args:
    pipeline_config: A pipeline_pb2.TrainEvalPipelineConfig.
    directory: The model directory into which the pipeline config file will be
      saved.
  """
  if not file_io.file_exists(directory):
    file_io.recursive_create_dir(directory)
  pipeline_config_path = os.path.join(directory, "pipeline.config")
  config_text = text_format.MessageToString(pipeline_config)
  with tf.gfile.Open(pipeline_config_path, "wb") as f:
    tf.logging.info("Writing pipeline config file to %s",
                    pipeline_config_path)
    f.write(config_text) 
Example 10
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: decorators.py    GNU General Public License v3.0 6 votes vote down vote up
def with_proto_compression(func):

    def wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        text = text_format.MessageToString(res)

        # Send chunks of max 1MB.
        chunk_size = 1024 * 1024
        chunks = []
        for i in range(0, len(text), chunk_size):
            chunks.append(text[i: i + chunk_size])

        for chunk in chunks:
            compressed = ETScoresCompressedResponse()
            compressed.data = gzip.compress(chunk.encode('utf-8'))
            yield compressed

    return wrapper 
Example 11
Project: SherpaHighLevel   Author: Shedino   File: mavwp.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def save_as_pb(self, filename):
        mission = mission_pb2.Mission()
        for w in self.wpoints:
            waypoint = mission.waypoint.add()
            waypoint.command = w.command
            waypoint.frame = w.frame
            waypoint.seq = w.seq
            waypoint.current = w.current
            waypoint.autocontinue = w.autocontinue
            waypoint.param1 = w.param1
            waypoint.param2 = w.param2
            waypoint.param3 = w.param3
            waypoint.param4 = w.param4
            waypoint.x = w.x
            waypoint.y = w.y
            waypoint.z = w.z
        with open(filename, 'w') as f:
            f.write('QGC WPL PB 110\n')
            f.write(text_format.MessageToString(mission)) 
Example 12
Project: SherpaHighLevel   Author: Shedino   File: mavwp.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def save_as_pb(self, filename):
        mission = mission_pb2.Mission()
        for w in self.wpoints:
            waypoint = mission.waypoint.add()
            waypoint.command = w.command
            waypoint.frame = w.frame
            waypoint.seq = w.seq
            waypoint.current = w.current
            waypoint.autocontinue = w.autocontinue
            waypoint.param1 = w.param1
            waypoint.param2 = w.param2
            waypoint.param3 = w.param3
            waypoint.param4 = w.param4
            waypoint.x = w.x
            waypoint.y = w.y
            waypoint.z = w.z
        with open(filename, 'w') as f:
            f.write('QGC WPL PB 110\n')
            f.write(text_format.MessageToString(mission)) 
Example 13
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 6 votes vote down vote up
def testPrintExotic(self, message_module):
    message = message_module.TestAllTypes()
    message.repeated_int64.append(-9223372036854775808)
    message.repeated_uint64.append(18446744073709551615)
    message.repeated_double.append(123.456)
    message.repeated_double.append(1.23e22)
    message.repeated_double.append(1.23e-18)
    message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
    message.repeated_string.append(u'\u00fc\ua71f')
    self.CompareToGoldenText(
        self.RemoveRedundantZeros(text_format.MessageToString(message)),
        'repeated_int64: -9223372036854775808\n'
        'repeated_uint64: 18446744073709551615\n'
        'repeated_double: 123.456\n'
        'repeated_double: 1.23e+22\n'
        'repeated_double: 1.23e-18\n'
        'repeated_string:'
        ' "\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""\n'
        'repeated_string: "\\303\\274\\352\\234\\237"\n') 
Example 14
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 6 votes vote down vote up
def testPrintExoticAsOneLine(self, message_module):
    message = message_module.TestAllTypes()
    message.repeated_int64.append(-9223372036854775808)
    message.repeated_uint64.append(18446744073709551615)
    message.repeated_double.append(123.456)
    message.repeated_double.append(1.23e22)
    message.repeated_double.append(1.23e-18)
    message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
    message.repeated_string.append(u'\u00fc\ua71f')
    self.CompareToGoldenText(
        self.RemoveRedundantZeros(text_format.MessageToString(
            message, as_one_line=True)),
        'repeated_int64: -9223372036854775808'
        ' repeated_uint64: 18446744073709551615'
        ' repeated_double: 123.456'
        ' repeated_double: 1.23e+22'
        ' repeated_double: 1.23e-18'
        ' repeated_string: '
        '"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\""'
        ' repeated_string: "\\303\\274\\352\\234\\237"') 
Example 15
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 6 votes vote down vote up
def testPrintMessageSet(self):
    message = unittest_mset_pb2.TestMessageSetContainer()
    ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
    ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
    message.message_set.Extensions[ext1].i = 23
    message.message_set.Extensions[ext2].str = 'foo'
    self.CompareToGoldenText(
        text_format.MessageToString(message), 'message_set {\n'
        '  [protobuf_unittest.TestMessageSetExtension1] {\n'
        '    i: 23\n'
        '  }\n'
        '  [protobuf_unittest.TestMessageSetExtension2] {\n'
        '    str: \"foo\"\n'
        '  }\n'
        '}\n')

    message = message_set_extensions_pb2.TestMessageSet()
    ext = message_set_extensions_pb2.message_set_extension3
    message.Extensions[ext].text = 'bar'
    self.CompareToGoldenText(
        text_format.MessageToString(message),
        '[google.protobuf.internal.TestMessageSetExtension3] {\n'
        '  text: \"bar\"\n'
        '}\n') 
Example 16
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 6 votes vote down vote up
def testPrintMessageSetAsOneLine(self):
    message = unittest_mset_pb2.TestMessageSetContainer()
    ext1 = unittest_mset_pb2.TestMessageSetExtension1.message_set_extension
    ext2 = unittest_mset_pb2.TestMessageSetExtension2.message_set_extension
    message.message_set.Extensions[ext1].i = 23
    message.message_set.Extensions[ext2].str = 'foo'
    self.CompareToGoldenText(
        text_format.MessageToString(message, as_one_line=True),
        'message_set {'
        ' [protobuf_unittest.TestMessageSetExtension1] {'
        ' i: 23'
        ' }'
        ' [protobuf_unittest.TestMessageSetExtension2] {'
        ' str: \"foo\"'
        ' }'
        ' }') 
Example 17
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 6 votes vote down vote up
def testPrintMessageExpandAnyRepeated(self):
    packed_message = unittest_pb2.OneString()
    message = any_test_pb2.TestAny()
    packed_message.data = 'string0'
    message.repeated_any_value.add().Pack(packed_message)
    packed_message.data = 'string1'
    message.repeated_any_value.add().Pack(packed_message)
    self.assertEqual(
        text_format.MessageToString(message),
        'repeated_any_value {\n'
        '  [type.googleapis.com/protobuf_unittest.OneString] {\n'
        '    data: "string0"\n'
        '  }\n'
        '}\n'
        'repeated_any_value {\n'
        '  [type.googleapis.com/protobuf_unittest.OneString] {\n'
        '    data: "string1"\n'
        '  }\n'
        '}\n') 
Example 18
Project: bigquerylayers   Author: smandaric   File: proto_builder_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testMakeSimpleProtoClass(self):
    """Test that we can create a proto class."""
    proto_cls = proto_builder.MakeSimpleProtoClass(
        self._fields,
        full_name='net.proto2.python.public.proto_builder_test.Test')
    proto = proto_cls()
    proto.foo = 12345
    proto.bar = 'asdf'
    self.assertMultiLineEqual(
        'bar: "asdf"\nfoo: 12345\n', text_format.MessageToString(proto)) 
Example 19
Project: bigquerylayers   Author: smandaric   File: proto_builder_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testOrderedFields(self):
    """Test that the field order is maintained when given an OrderedDict."""
    proto_cls = proto_builder.MakeSimpleProtoClass(
        self.ordered_fields,
        full_name='net.proto2.python.public.proto_builder_test.OrderedTest')
    proto = proto_cls()
    proto.foo = 12345
    proto.bar = 'asdf'
    self.assertMultiLineEqual(
        'foo: 12345\nbar: "asdf"\n', text_format.MessageToString(proto)) 
Example 20
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintExoticUnicodeSubclass(self, message_module):

    class UnicodeSub(six.text_type):
      pass

    message = message_module.TestAllTypes()
    message.repeated_string.append(UnicodeSub(u'\u00fc\ua71f'))
    self.CompareToGoldenText(
        text_format.MessageToString(message),
        'repeated_string: "\\303\\274\\352\\234\\237"\n') 
Example 21
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintNestedMessageAsOneLine(self, message_module):
    message = message_module.TestAllTypes()
    msg = message.repeated_nested_message.add()
    msg.bb = 42
    self.CompareToGoldenText(
        text_format.MessageToString(message, as_one_line=True),
        'repeated_nested_message { bb: 42 }') 
Example 22
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def VerifyPrintShortFormatRepeatedFields(self, message_module, as_one_line):
    message = message_module.TestAllTypes()
    message.repeated_int32.append(1)
    message.repeated_string.append('Google')
    message.repeated_string.append('Hello,World')
    message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_FOO)
    message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_BAR)
    message.repeated_foreign_enum.append(unittest_pb2.FOREIGN_BAZ)
    message.optional_nested_message.bb = 3
    for i in (21, 32):
      msg = message.repeated_nested_message.add()
      msg.bb = i
    expected_ascii = (
        'optional_nested_message {\n  bb: 3\n}\n'
        'repeated_int32: [1]\n'
        'repeated_string: "Google"\n'
        'repeated_string: "Hello,World"\n'
        'repeated_nested_message {\n  bb: 21\n}\n'
        'repeated_nested_message {\n  bb: 32\n}\n'
        'repeated_foreign_enum: [FOREIGN_FOO, FOREIGN_BAR, FOREIGN_BAZ]\n')
    if as_one_line:
      expected_ascii = expected_ascii.replace('\n', ' ')
      expected_ascii = re.sub(r'\s+', ' ', expected_ascii)
      expected_ascii = re.sub(r'\s$', '', expected_ascii)

    actual_ascii = text_format.MessageToString(
        message, use_short_repeated_primitives=True,
        as_one_line=as_one_line)
    self.CompareToGoldenText(actual_ascii, expected_ascii)
    parsed_message = message_module.TestAllTypes()
    text_format.Parse(actual_ascii, parsed_message)
    self.assertEqual(parsed_message, message) 
Example 23
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintNestedNewLineInStringAsOneLine(self, message_module):
    message = message_module.TestAllTypes()
    message.optional_string = 'a\nnew\nline'
    self.CompareToGoldenText(
        text_format.MessageToString(message, as_one_line=True),
        'optional_string: "a\\nnew\\nline"') 
Example 24
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testRoundTripExoticAsOneLine(self, message_module):
    message = message_module.TestAllTypes()
    message.repeated_int64.append(-9223372036854775808)
    message.repeated_uint64.append(18446744073709551615)
    message.repeated_double.append(123.456)
    message.repeated_double.append(1.23e22)
    message.repeated_double.append(1.23e-18)
    message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
    message.repeated_string.append(u'\u00fc\ua71f')

    # Test as_utf8 = False.
    wire_text = text_format.MessageToString(message,
                                            as_one_line=True,
                                            as_utf8=False)
    parsed_message = message_module.TestAllTypes()
    r = text_format.Parse(wire_text, parsed_message)
    self.assertIs(r, parsed_message)
    self.assertEqual(message, parsed_message)

    # Test as_utf8 = True.
    wire_text = text_format.MessageToString(message,
                                            as_one_line=True,
                                            as_utf8=True)
    parsed_message = message_module.TestAllTypes()
    r = text_format.Parse(wire_text, parsed_message)
    self.assertIs(r, parsed_message)
    self.assertEqual(message, parsed_message,
                     '\n%s != %s' % (message, parsed_message)) 
Example 25
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintRawUtf8String(self, message_module):
    message = message_module.TestAllTypes()
    message.repeated_string.append(u'\u00fc\t\ua71f')
    text = text_format.MessageToString(message, as_utf8=True)
    golden_unicode = u'repeated_string: "\u00fc\\t\ua71f"\n'
    golden_text = golden_unicode if six.PY3 else golden_unicode.encode('utf-8')
    # MessageToString always returns a native str.
    self.CompareToGoldenText(text, golden_text)
    parsed_message = message_module.TestAllTypes()
    text_format.Parse(text, parsed_message)
    self.assertEqual(
        message, parsed_message, '\n%s != %s  (%s != %s)' %
        (message, parsed_message, message.repeated_string[0],
         parsed_message.repeated_string[0])) 
Example 26
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testParseAllFields(self, message_module):
    message = message_module.TestAllTypes()
    test_util.SetAllFields(message)
    ascii_text = text_format.MessageToString(message)

    parsed_message = message_module.TestAllTypes()
    text_format.Parse(ascii_text, parsed_message)
    self.assertEqual(message, parsed_message)
    if message_module is unittest_pb2:
      test_util.ExpectAllFieldsSet(self, message) 
Example 27
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testParseAndMergeUtf8(self, message_module):
    message = message_module.TestAllTypes()
    test_util.SetAllFields(message)
    ascii_text = text_format.MessageToString(message)
    ascii_text = ascii_text.encode('utf-8')

    parsed_message = message_module.TestAllTypes()
    text_format.Parse(ascii_text, parsed_message)
    self.assertEqual(message, parsed_message)
    if message_module is unittest_pb2:
      test_util.ExpectAllFieldsSet(self, message)

    parsed_message.Clear()
    text_format.Merge(ascii_text, parsed_message)
    self.assertEqual(message, parsed_message)
    if message_module is unittest_pb2:
      test_util.ExpectAllFieldsSet(self, message)

    msg2 = message_module.TestAllTypes()
    text = (u'optional_string: "café"')
    text_format.Merge(text, msg2)
    self.assertEqual(msg2.optional_string, u'café')
    msg2.Clear()
    self.assertEqual(msg2.optional_string, u'')
    text_format.Parse(text, msg2)
    self.assertEqual(msg2.optional_string, u'café') 
Example 28
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testParseOneof(self, message_module):
    m = message_module.TestAllTypes()
    m.oneof_uint32 = 11
    m2 = message_module.TestAllTypes()
    text_format.Parse(text_format.MessageToString(m), m2)
    self.assertEqual('oneof_uint32', m2.WhichOneof('oneof_field')) 
Example 29
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintAllFields(self):
    message = unittest_pb2.TestAllTypes()
    test_util.SetAllFields(message)
    self.CompareToGoldenFile(
        self.RemoveRedundantZeros(text_format.MessageToString(message)),
        'text_format_unittest_data_oneof_implemented.txt') 
Example 30
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintUnknownFields(self):
    message = unittest_pb2.TestAllTypes()
    message.optional_int32 = 101
    message.optional_double = 102.0
    message.optional_string = u'hello'
    message.optional_bytes = b'103'
    message.optionalgroup.a = 104
    message.optional_nested_message.bb = 105
    all_data = message.SerializeToString()
    empty_message = unittest_pb2.TestEmptyMessage()
    empty_message.ParseFromString(all_data)
    self.assertEqual('  1: 101\n'
                     '  12: 4636878028842991616\n'
                     '  14: "hello"\n'
                     '  15: "103"\n'
                     '  16 {\n'
                     '    17: 104\n'
                     '  }\n'
                     '  18 {\n'
                     '    1: 105\n'
                     '  }\n',
                     text_format.MessageToString(empty_message,
                                                 indent=2,
                                                 print_unknown_fields=True))
    self.assertEqual('1: 101 '
                     '12: 4636878028842991616 '
                     '14: "hello" '
                     '15: "103" '
                     '16 { 17: 104 } '
                     '18 { 1: 105 }',
                     text_format.MessageToString(empty_message,
                                                 print_unknown_fields=True,
                                                 as_one_line=True)) 
Example 31
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintMap(self):
    message = map_unittest_pb2.TestMap()

    message.map_int32_int32[-123] = -456
    message.map_int64_int64[-2**33] = -2**34
    message.map_uint32_uint32[123] = 456
    message.map_uint64_uint64[2**33] = 2**34
    message.map_string_string['abc'] = '123'
    message.map_int32_foreign_message[111].c = 5

    # Maps are serialized to text format using their underlying repeated
    # representation.
    self.CompareToGoldenText(
        text_format.MessageToString(message), 'map_int32_int32 {\n'
        '  key: -123\n'
        '  value: -456\n'
        '}\n'
        'map_int64_int64 {\n'
        '  key: -8589934592\n'
        '  value: -17179869184\n'
        '}\n'
        'map_uint32_uint32 {\n'
        '  key: 123\n'
        '  value: 456\n'
        '}\n'
        'map_uint64_uint64 {\n'
        '  key: 8589934592\n'
        '  value: 17179869184\n'
        '}\n'
        'map_string_string {\n'
        '  key: "abc"\n'
        '  value: "123"\n'
        '}\n'
        'map_int32_foreign_message {\n'
        '  key: 111\n'
        '  value {\n'
        '    c: 5\n'
        '  }\n'
        '}\n')

  # In cpp implementation, __str__ calls the cpp implementation of text format. 
Example 32
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testMapOrderEnforcement(self):
    message = map_unittest_pb2.TestMap()
    for letter in string.ascii_uppercase[13:26]:
      message.map_string_string[letter] = 'dummy'
    for letter in reversed(string.ascii_uppercase[0:13]):
      message.map_string_string[letter] = 'dummy'
    golden = ''.join(('map_string_string {\n  key: "%c"\n  value: "dummy"\n}\n'
                      % (letter,) for letter in string.ascii_uppercase))
    self.CompareToGoldenText(text_format.MessageToString(message), golden)

  # TODO(teboring): In c/137553523, not serializing default value for map entry
  # message has been fixed. This test needs to be disabled in order to submit
  # that cl. Add this back when c/137553523 has been submitted.
  # def testMapOrderSemantics(self):
  #   golden_lines = self.ReadGolden('map_test_data.txt')

  #   message = map_unittest_pb2.TestMap()
  #   text_format.ParseLines(golden_lines, message)
  #   candidate = text_format.MessageToString(message)
  #   # The Python implementation emits "1.0" for the double value that the C++
  #   # implementation emits as "1".
  #   candidate = candidate.replace('1.0', '1', 2)
  #   candidate = candidate.replace('0.0', '0', 2)
  #   self.assertMultiLineEqual(candidate, ''.join(golden_lines))


# Tests of proto2-only features (MessageSet, extensions, etc.). 
Example 33
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testExtensionInsideAnyMessage(self):
    message = test_extend_any.TestAny()
    text = ('value {\n'
            '  [type.googleapis.com/google.protobuf.internal.TestAny] {\n'
            '    [google.protobuf.internal.TestAnyExtension1.extension1] {\n'
            '      i: 10\n'
            '    }\n'
            '  }\n'
            '}\n')
    text_format.Merge(text, message, descriptor_pool=descriptor_pool.Default())
    self.CompareToGoldenText(
        text_format.MessageToString(
            message, descriptor_pool=descriptor_pool.Default()),
        text) 
Example 34
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintAllExtensions(self):
    message = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(message)
    self.CompareToGoldenFile(
        self.RemoveRedundantZeros(text_format.MessageToString(message)),
        'text_format_unittest_extensions_data.txt') 
Example 35
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintAllExtensionsPointy(self):
    message = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(message)
    self.CompareToGoldenFile(
        self.RemoveRedundantZeros(text_format.MessageToString(
            message, pointy_brackets=True)),
        'text_format_unittest_extensions_data_pointy.txt') 
Example 36
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testParseAllExtensions(self):
    message = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(message)
    ascii_text = text_format.MessageToString(message)

    parsed_message = unittest_pb2.TestAllExtensions()
    text_format.Parse(ascii_text, parsed_message)
    self.assertEqual(message, parsed_message) 
Example 37
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintMessageExpandAny(self):
    packed_message = unittest_pb2.OneString()
    packed_message.data = 'string'
    message = any_test_pb2.TestAny()
    message.any_value.Pack(packed_message)
    self.assertEqual(
        text_format.MessageToString(message,
                                    descriptor_pool=descriptor_pool.Default()),
        'any_value {\n'
        '  [type.googleapis.com/protobuf_unittest.OneString] {\n'
        '    data: "string"\n'
        '  }\n'
        '}\n') 
Example 38
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintMessageExpandAnyDescriptorPoolMissingType(self):
    packed_message = unittest_pb2.OneString()
    packed_message.data = 'string'
    message = any_test_pb2.TestAny()
    message.any_value.Pack(packed_message)
    empty_pool = descriptor_pool.DescriptorPool()
    self.assertEqual(
        text_format.MessageToString(message, descriptor_pool=empty_pool),
        'any_value {\n'
        '  type_url: "type.googleapis.com/protobuf_unittest.OneString"\n'
        '  value: "\\n\\006string"\n'
        '}\n') 
Example 39
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintMessageExpandAnyPointyBrackets(self):
    packed_message = unittest_pb2.OneString()
    packed_message.data = 'string'
    message = any_test_pb2.TestAny()
    message.any_value.Pack(packed_message)
    self.assertEqual(
        text_format.MessageToString(message,
                                    pointy_brackets=True),
        'any_value <\n'
        '  [type.googleapis.com/protobuf_unittest.OneString] <\n'
        '    data: "string"\n'
        '  >\n'
        '>\n') 
Example 40
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintMessageExpandAnyAsOneLine(self):
    packed_message = unittest_pb2.OneString()
    packed_message.data = 'string'
    message = any_test_pb2.TestAny()
    message.any_value.Pack(packed_message)
    self.assertEqual(
        text_format.MessageToString(message,
                                    as_one_line=True),
        'any_value {'
        ' [type.googleapis.com/protobuf_unittest.OneString]'
        ' { data: "string" } '
        '}') 
Example 41
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrintMessageExpandAnyAsOneLinePointyBrackets(self):
    packed_message = unittest_pb2.OneString()
    packed_message.data = 'string'
    message = any_test_pb2.TestAny()
    message.any_value.Pack(packed_message)
    self.assertEqual(
        text_format.MessageToString(message,
                                    as_one_line=True,
                                    pointy_brackets=True,
                                    descriptor_pool=descriptor_pool.Default()),
        'any_value <'
        ' [type.googleapis.com/protobuf_unittest.OneString]'
        ' < data: "string" > '
        '>') 
Example 42
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testUnknownEnums(self):
    message = unittest_proto3_arena_pb2.TestAllTypes()
    message2 = unittest_proto3_arena_pb2.TestAllTypes()
    message.optional_nested_enum = 999
    text_string = text_format.MessageToString(message)
    text_format.Parse(text_string, message2)
    self.assertEqual(999, message2.optional_nested_enum) 
Example 43
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrettyPrintNoMatch(self, message_module):

    def printer(message, indent, as_one_line):
      del message, indent, as_one_line
      return None

    message = message_module.TestAllTypes()
    msg = message.repeated_nested_message.add()
    msg.bb = 42
    self.CompareToGoldenText(
        text_format.MessageToString(
            message, as_one_line=True, message_formatter=printer),
        'repeated_nested_message { bb: 42 }') 
Example 44
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testPrettyPrintOneLine(self, message_module):

    def printer(m, indent, as_one_line):
      del indent, as_one_line
      if m.DESCRIPTOR == message_module.TestAllTypes.NestedMessage.DESCRIPTOR:
        return 'My lucky number is %s' % m.bb

    message = message_module.TestAllTypes()
    msg = message.repeated_nested_message.add()
    msg.bb = 42
    self.CompareToGoldenText(
        text_format.MessageToString(
            message, as_one_line=True, message_formatter=printer),
        'repeated_nested_message { My lucky number is 42 }') 
Example 45
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 5 votes vote down vote up
def testMessageToString(self):
    self.CompareToGoldenText(
        text_format.MessageToString(self.message),
        textwrap.dedent("""\
            child {
              payload {
                optional_string: "value"
              }
            }
            """)) 
Example 46
Project: bigquerylayers   Author: smandaric   File: python_message.py    GNU General Public License v3.0 5 votes vote down vote up
def _AddStrMethod(message_descriptor, cls):
  """Helper for _AddMessageMethods()."""
  def __str__(self):
    return text_format.MessageToString(self)
  cls.__str__ = __str__ 
Example 47
Project: bigquerylayers   Author: smandaric   File: python_message.py    GNU General Public License v3.0 5 votes vote down vote up
def _AddReprMethod(message_descriptor, cls):
  """Helper for _AddMessageMethods()."""
  def __repr__(self):
    return text_format.MessageToString(self)
  cls.__repr__ = __repr__ 
Example 48
Project: bigquerylayers   Author: smandaric   File: python_message.py    GNU General Public License v3.0 5 votes vote down vote up
def _AddUnicodeMethod(unused_message_descriptor, cls):
  """Helper for _AddMessageMethods()."""

  def __unicode__(self):
    return text_format.MessageToString(self, as_utf8=True).decode('utf-8')
  cls.__unicode__ = __unicode__ 
Example 49
Project: recipes-py   Author: luci   File: cmd.py    Apache License 2.0 5 votes vote down vote up
def main(args):
  logging.basicConfig()

  # defer to regenerate_docs for consistency between train and 'doc --kind gen'
  if args.kind == 'gen':
    print('Generating README.recipes.md')
    regenerate_docs(args.recipe_deps.main_repo)
    return 0

  if args.recipe:
    node = parse_recipe(args.recipe_deps.recipes[args.recipe])
  else:
    node = parse_repo(args.recipe_deps.main_repo)

  _set_known_objects(node)

  if args.kind == 'jsonpb':
    sys.stdout.write(jsonpb.MessageToJson(
      node, including_default_value_fields=True,
      preserving_proto_field_name=True))
  elif args.kind == 'binarypb':
    sys.stdout.write(node.SerializeToString())
  elif args.kind == 'textpb':
    sys.stdout.write(textpb.MessageToString(node))
  elif args.kind == 'markdown':
    doc_markdown.Emit(doc_markdown.Printer(sys.stdout), node)
  else:
    raise NotImplementedError('--kind=%s' % args.kind) 
Example 50
Project: RouteOptimization   Author: andre-le   File: python_message.py    MIT License 5 votes vote down vote up
def _AddStrMethod(message_descriptor, cls):
  """Helper for _AddMessageMethods()."""
  def __str__(self):
    return text_format.MessageToString(self)
  cls.__str__ = __str__ 
Example 51
Project: RouteOptimization   Author: andre-le   File: python_message.py    MIT License 5 votes vote down vote up
def _AddReprMethod(message_descriptor, cls):
  """Helper for _AddMessageMethods()."""
  def __repr__(self):
    return text_format.MessageToString(self)
  cls.__repr__ = __repr__ 
Example 52
Project: RouteOptimization   Author: andre-le   File: python_message.py    MIT License 5 votes vote down vote up
def _AddUnicodeMethod(unused_message_descriptor, cls):
  """Helper for _AddMessageMethods()."""

  def __unicode__(self):
    return text_format.MessageToString(self, as_utf8=True).decode('utf-8')
  cls.__unicode__ = __unicode__ 
Example 53
Project: deoplete-asm   Author: deoplete-plugins   File: python_message.py    MIT License 5 votes vote down vote up
def _AddStrMethod(message_descriptor, cls):
  """Helper for _AddMessageMethods()."""
  def __str__(self):
    return text_format.MessageToString(self)
  cls.__str__ = __str__ 
Example 54
Project: deoplete-asm   Author: deoplete-plugins   File: python_message.py    MIT License 5 votes vote down vote up
def _AddReprMethod(message_descriptor, cls):
  """Helper for _AddMessageMethods()."""
  def __repr__(self):
    return text_format.MessageToString(self)
  cls.__repr__ = __repr__ 
Example 55
Project: deoplete-asm   Author: deoplete-plugins   File: python_message.py    MIT License 5 votes vote down vote up
def _AddUnicodeMethod(unused_message_descriptor, cls):
  """Helper for _AddMessageMethods()."""

  def __unicode__(self):
    return text_format.MessageToString(self, as_utf8=True).decode('utf-8')
  cls.__unicode__ = __unicode__ 
Example 56
Project: tf-object-detection   Author: ndaidong   File: exporter.py    MIT License 5 votes vote down vote up
def export_inference_graph(input_type,
                           pipeline_config,
                           trained_checkpoint_prefix,
                           output_directory,
                           input_shape=None,
                           output_collection_name='inference_op',
                           additional_output_tensor_names=None):
  """Exports inference graph for the model specified in the pipeline config.

  Args:
    input_type: Type of input for the graph. Can be one of [`image_tensor`,
      `tf_example`].
    pipeline_config: pipeline_pb2.TrainAndEvalPipelineConfig proto.
    trained_checkpoint_prefix: Path to the trained checkpoint file.
    output_directory: Path to write outputs.
    input_shape: Sets a fixed shape for an `image_tensor` input. If not
      specified, will default to [None, None, None, 3].
    output_collection_name: Name of collection to add output tensors to.
      If None, does not add output tensors to a collection.
    additional_output_tensor_names: list of additional output
      tensors to include in the frozen graph.
  """
  detection_model = model_builder.build(pipeline_config.model,
                                        is_training=False)
  _export_inference_graph(input_type, detection_model,
                          pipeline_config.eval_config.use_moving_averages,
                          trained_checkpoint_prefix,
                          output_directory, additional_output_tensor_names,
                          input_shape, output_collection_name,
                          graph_hook_fn=None)
  pipeline_config.eval_config.use_moving_averages = False
  config_text = text_format.MessageToString(pipeline_config)
  with tf.gfile.Open(
      os.path.join(output_directory, 'pipeline.config'), 'wb') as f:
    f.write(config_text) 
Example 57
Project: tf-object-detection   Author: ndaidong   File: config_util_test.py    MIT License 5 votes vote down vote up
def _write_config(config, config_path):
  """Writes a config object to disk."""
  config_text = text_format.MessageToString(config)
  with tf.gfile.Open(config_path, "wb") as f:
    f.write(config_text) 
Example 58
Project: FUTU_Stop_Loss   Author: BigtoC   File: proto_builder_test.py    MIT License 5 votes vote down vote up
def testMakeSimpleProtoClass(self):
    """Test that we can create a proto class."""
    proto_cls = proto_builder.MakeSimpleProtoClass(
        self._fields,
        full_name='net.proto2.python.public.proto_builder_test.Test')
    proto = proto_cls()
    proto.foo = 12345
    proto.bar = 'asdf'
    self.assertMultiLineEqual(
        'bar: "asdf"\nfoo: 12345\n', text_format.MessageToString(proto)) 
Example 59
Project: FUTU_Stop_Loss   Author: BigtoC   File: proto_builder_test.py    MIT License 5 votes vote down vote up
def testOrderedFields(self):
    """Test that the field order is maintained when given an OrderedDict."""
    proto_cls = proto_builder.MakeSimpleProtoClass(
        self.ordered_fields,
        full_name='net.proto2.python.public.proto_builder_test.OrderedTest')
    proto = proto_cls()
    proto.foo = 12345
    proto.bar = 'asdf'
    self.assertMultiLineEqual(
        'foo: 12345\nbar: "asdf"\n', text_format.MessageToString(proto)) 
Example 60
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintExoticUnicodeSubclass(self, message_module):

    class UnicodeSub(six.text_type):
      pass

    message = message_module.TestAllTypes()
    message.repeated_string.append(UnicodeSub(u'\u00fc\ua71f'))
    self.CompareToGoldenText(
        text_format.MessageToString(message),
        'repeated_string: "\\303\\274\\352\\234\\237"\n') 
Example 61
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintNestedMessageAsOneLine(self, message_module):
    message = message_module.TestAllTypes()
    msg = message.repeated_nested_message.add()
    msg.bb = 42
    self.CompareToGoldenText(
        text_format.MessageToString(message, as_one_line=True),
        'repeated_nested_message { bb: 42 }') 
Example 62
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintNestedNewLineInStringAsOneLine(self, message_module):
    message = message_module.TestAllTypes()
    message.optional_string = 'a\nnew\nline'
    self.CompareToGoldenText(
        text_format.MessageToString(message, as_one_line=True),
        'optional_string: "a\\nnew\\nline"') 
Example 63
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testRoundTripExoticAsOneLine(self, message_module):
    message = message_module.TestAllTypes()
    message.repeated_int64.append(-9223372036854775808)
    message.repeated_uint64.append(18446744073709551615)
    message.repeated_double.append(123.456)
    message.repeated_double.append(1.23e22)
    message.repeated_double.append(1.23e-18)
    message.repeated_string.append('\000\001\a\b\f\n\r\t\v\\\'"')
    message.repeated_string.append(u'\u00fc\ua71f')

    # Test as_utf8 = False.
    wire_text = text_format.MessageToString(message,
                                            as_one_line=True,
                                            as_utf8=False)
    parsed_message = message_module.TestAllTypes()
    r = text_format.Parse(wire_text, parsed_message)
    self.assertIs(r, parsed_message)
    self.assertEqual(message, parsed_message)

    # Test as_utf8 = True.
    wire_text = text_format.MessageToString(message,
                                            as_one_line=True,
                                            as_utf8=True)
    parsed_message = message_module.TestAllTypes()
    r = text_format.Parse(wire_text, parsed_message)
    self.assertIs(r, parsed_message)
    self.assertEqual(message, parsed_message,
                     '\n%s != %s' % (message, parsed_message)) 
Example 64
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintRawUtf8String(self, message_module):
    message = message_module.TestAllTypes()
    message.repeated_string.append(u'\u00fc\ua71f')
    text = text_format.MessageToString(message, as_utf8=True)
    self.CompareToGoldenText(text, 'repeated_string: "\303\274\352\234\237"\n')
    parsed_message = message_module.TestAllTypes()
    text_format.Parse(text, parsed_message)
    self.assertEqual(message, parsed_message,
                     '\n%s != %s' % (message, parsed_message)) 
Example 65
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintFloatFormat(self, message_module):
    # Check that float_format argument is passed to sub-message formatting.
    message = message_module.NestedTestAllTypes()
    # We use 1.25 as it is a round number in binary.  The proto 32-bit float
    # will not gain additional imprecise digits as a 64-bit Python float and
    # show up in its str.  32-bit 1.2 is noisy when extended to 64-bit:
    #  >>> struct.unpack('f', struct.pack('f', 1.2))[0]
    #  1.2000000476837158
    #  >>> struct.unpack('f', struct.pack('f', 1.25))[0]
    #  1.25
    message.payload.optional_float = 1.25
    # Check rounding at 15 significant digits
    message.payload.optional_double = -.000003456789012345678
    # Check no decimal point.
    message.payload.repeated_float.append(-5642)
    # Check no trailing zeros.
    message.payload.repeated_double.append(.000078900)
    formatted_fields = ['optional_float: 1.25',
                        'optional_double: -3.45678901234568e-6',
                        'repeated_float: -5642', 'repeated_double: 7.89e-5']
    text_message = text_format.MessageToString(message, float_format='.15g')
    self.CompareToGoldenText(
        self.RemoveRedundantZeros(text_message),
        'payload {{\n  {0}\n  {1}\n  {2}\n  {3}\n}}\n'.format(
            *formatted_fields))
    # as_one_line=True is a separate code branch where float_format is passed.
    text_message = text_format.MessageToString(message,
                                               as_one_line=True,
                                               float_format='.15g')
    self.CompareToGoldenText(
        self.RemoveRedundantZeros(text_message),
        'payload {{ {0} {1} {2} {3} }}'.format(*formatted_fields)) 
Example 66
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testParseAndMergeUtf8(self, message_module):
    message = message_module.TestAllTypes()
    test_util.SetAllFields(message)
    ascii_text = text_format.MessageToString(message)
    ascii_text = ascii_text.encode('utf-8')

    parsed_message = message_module.TestAllTypes()
    text_format.Parse(ascii_text, parsed_message)
    self.assertEqual(message, parsed_message)
    if message_module is unittest_pb2:
      test_util.ExpectAllFieldsSet(self, message)

    parsed_message.Clear()
    text_format.Merge(ascii_text, parsed_message)
    self.assertEqual(message, parsed_message)
    if message_module is unittest_pb2:
      test_util.ExpectAllFieldsSet(self, message)

    if six.PY2:
      msg2 = message_module.TestAllTypes()
      text = (u'optional_string: "café"')
      text_format.Merge(text, msg2)
      self.assertEqual(msg2.optional_string, u'café')
      msg2.Clear()
      text_format.Parse(text, msg2)
      self.assertEqual(msg2.optional_string, u'café') 
Example 67
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testParseOneof(self, message_module):
    m = message_module.TestAllTypes()
    m.oneof_uint32 = 11
    m2 = message_module.TestAllTypes()
    text_format.Parse(text_format.MessageToString(m), m2)
    self.assertEqual('oneof_uint32', m2.WhichOneof('oneof_field')) 
Example 68
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintAllFieldsPointy(self):
    message = unittest_pb2.TestAllTypes()
    test_util.SetAllFields(message)
    self.CompareToGoldenFile(
        self.RemoveRedundantZeros(text_format.MessageToString(
            message, pointy_brackets=True)),
        'text_format_unittest_data_pointy_oneof.txt') 
Example 69
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintAllFields(self):
    message = unittest_pb2.TestAllTypes()
    test_util.SetAllFields(message)
    self.CompareToGoldenFile(
        self.RemoveRedundantZeros(text_format.MessageToString(message)),
        'text_format_unittest_data_oneof_implemented.txt') 
Example 70
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintMap(self):
    message = map_unittest_pb2.TestMap()

    message.map_int32_int32[-123] = -456
    message.map_int64_int64[-2**33] = -2**34
    message.map_uint32_uint32[123] = 456
    message.map_uint64_uint64[2**33] = 2**34
    message.map_string_string['abc'] = '123'
    message.map_int32_foreign_message[111].c = 5

    # Maps are serialized to text format using their underlying repeated
    # representation.
    self.CompareToGoldenText(
        text_format.MessageToString(message), 'map_int32_int32 {\n'
        '  key: -123\n'
        '  value: -456\n'
        '}\n'
        'map_int64_int64 {\n'
        '  key: -8589934592\n'
        '  value: -17179869184\n'
        '}\n'
        'map_uint32_uint32 {\n'
        '  key: 123\n'
        '  value: 456\n'
        '}\n'
        'map_uint64_uint64 {\n'
        '  key: 8589934592\n'
        '  value: 17179869184\n'
        '}\n'
        'map_string_string {\n'
        '  key: "abc"\n'
        '  value: "123"\n'
        '}\n'
        'map_int32_foreign_message {\n'
        '  key: 111\n'
        '  value {\n'
        '    c: 5\n'
        '  }\n'
        '}\n') 
Example 71
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testExtensionInsideAnyMessage(self):
    message = test_extend_any.TestAny()
    text = ('value {\n'
            '  [type.googleapis.com/google.protobuf.internal.TestAny] {\n'
            '    [google.protobuf.internal.TestAnyExtension1.extension1] {\n'
            '      i: 10\n'
            '    }\n'
            '  }\n'
            '}\n')
    text_format.Merge(text, message, descriptor_pool=descriptor_pool.Default())
    self.CompareToGoldenText(
        text_format.MessageToString(
            message, descriptor_pool=descriptor_pool.Default()),
        text) 
Example 72
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintAllExtensions(self):
    message = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(message)
    self.CompareToGoldenFile(
        self.RemoveRedundantZeros(text_format.MessageToString(message)),
        'text_format_unittest_extensions_data.txt') 
Example 73
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintAllExtensionsPointy(self):
    message = unittest_pb2.TestAllExtensions()
    test_util.SetAllExtensions(message)
    self.CompareToGoldenFile(
        self.RemoveRedundantZeros(text_format.MessageToString(
            message, pointy_brackets=True)),
        'text_format_unittest_extensions_data_pointy.txt') 
Example 74
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintMessageExpandAny(self):
    packed_message = unittest_pb2.OneString()
    packed_message.data = 'string'
    message = any_test_pb2.TestAny()
    message.any_value.Pack(packed_message)
    self.assertEqual(
        text_format.MessageToString(message,
                                    descriptor_pool=descriptor_pool.Default()),
        'any_value {\n'
        '  [type.googleapis.com/protobuf_unittest.OneString] {\n'
        '    data: "string"\n'
        '  }\n'
        '}\n') 
Example 75
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testTopAnyMessage(self):
    packed_msg = unittest_pb2.OneString()
    msg = any_pb2.Any()
    msg.Pack(packed_msg)
    text = text_format.MessageToString(msg)
    other_msg = text_format.Parse(text, any_pb2.Any())
    self.assertEqual(msg, other_msg) 
Example 76
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintMessageExpandAnyDescriptorPoolMissingType(self):
    packed_message = unittest_pb2.OneString()
    packed_message.data = 'string'
    message = any_test_pb2.TestAny()
    message.any_value.Pack(packed_message)
    empty_pool = descriptor_pool.DescriptorPool()
    self.assertEqual(
        text_format.MessageToString(message, descriptor_pool=empty_pool),
        'any_value {\n'
        '  type_url: "type.googleapis.com/protobuf_unittest.OneString"\n'
        '  value: "\\n\\006string"\n'
        '}\n') 
Example 77
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintMessageExpandAnyPointyBrackets(self):
    packed_message = unittest_pb2.OneString()
    packed_message.data = 'string'
    message = any_test_pb2.TestAny()
    message.any_value.Pack(packed_message)
    self.assertEqual(
        text_format.MessageToString(message,
                                    pointy_brackets=True),
        'any_value <\n'
        '  [type.googleapis.com/protobuf_unittest.OneString] <\n'
        '    data: "string"\n'
        '  >\n'
        '>\n') 
Example 78
Project: FUTU_Stop_Loss   Author: BigtoC   File: text_format_test.py    MIT License 5 votes vote down vote up
def testPrintMessageExpandAnyAsOneLinePointyBrackets(self):
    packed_message = unittest_pb2.OneString()
    packed_message.data = 'string'
    message = any_test_pb2.TestAny()
    message.any_value.Pack(packed_message)
    self.assertEqual(
        text_format.MessageToString(message,
                                    as_one_line=True,
                                    pointy_brackets=True,
                                    descriptor_pool=descriptor_pool.Default()),
        'any_value <'
        ' [type.googleapis.com/protobuf_unittest.OneString]'
        ' < data: "string" > '
        '>') 
Example 79
Project: bigquerylayers   Author: smandaric   File: text_format_test.py    GNU General Public License v3.0 4 votes vote down vote up
def testCustomOptions(self, message_module):
    message_descriptor = (unittest_custom_options_pb2.
                          TestMessageWithCustomOptions.DESCRIPTOR)
    message_proto = descriptor_pb2.DescriptorProto()
    message_descriptor.CopyToProto(message_proto)
    expected_text = (
        'name: "TestMessageWithCustomOptions"\n'
        'field {\n'
        '  name: "field1"\n'
        '  number: 1\n'
        '  label: LABEL_OPTIONAL\n'
        '  type: TYPE_STRING\n'
        '  options {\n'
        '    ctype: CORD\n'
        '    [protobuf_unittest.field_opt1]: 8765432109\n'
        '  }\n'
        '}\n'
        'field {\n'
        '  name: "oneof_field"\n'
        '  number: 2\n'
        '  label: LABEL_OPTIONAL\n'
        '  type: TYPE_INT32\n'
        '  oneof_index: 0\n'
        '}\n'
        'enum_type {\n'
        '  name: "AnEnum"\n'
        '  value {\n'
        '    name: "ANENUM_VAL1"\n'
        '    number: 1\n'
        '  }\n'
        '  value {\n'
        '    name: "ANENUM_VAL2"\n'
        '    number: 2\n'
        '    options {\n'
        '      [protobuf_unittest.enum_value_opt1]: 123\n'
        '    }\n'
        '  }\n'
        '  options {\n'
        '    [protobuf_unittest.enum_opt1]: -789\n'
        '  }\n'
        '}\n'
        'options {\n'
        '  message_set_wire_format: false\n'
        '  [protobuf_unittest.message_opt1]: -56\n'
        '}\n'
        'oneof_decl {\n'
        '  name: "AnOneof"\n'
        '  options {\n'
        '    [protobuf_unittest.oneof_opt1]: -99\n'
        '  }\n'
        '}\n')
    self.assertEqual(expected_text,
                     text_format.MessageToString(message_proto))
    parsed_proto = descriptor_pb2.DescriptorProto()
    text_format.Parse(expected_text, parsed_proto)
    self.assertEqual(message_proto, parsed_proto)