Python google.protobuf.text_format.MessageToString() Examples

The following are 30 code examples for showing how to use google.protobuf.text_format.MessageToString(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module google.protobuf.text_format , or try the search function .

Example 1
Project: recipes-py   Author: luci   File: build.py    License: Apache License 2.0 7 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 2
Project: gftools   Author: googlefonts   File: gftools-add-font.py    License: 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, as_utf8=True)

  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 3
Project: vehicle_counting_tensorflow   Author: ahmetozlu   File: config_util.py    License: 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 4
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: 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('\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 5
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: 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('\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 6
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: 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 7
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: 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 8
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: 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 9
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: MIT License 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 10
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: MIT License 6 votes vote down vote up
def testPrettyPrintMultipleParts(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
      return None

    message = message_module.TestAllTypes()
    message.optional_int32 = 61
    msg = message.repeated_nested_message.add()
    msg.bb = 42
    msg = message.repeated_nested_message.add()
    msg.bb = 99
    msg = message.optional_nested_message
    msg.bb = 1
    self.CompareToGoldenText(
        text_format.MessageToString(
            message, as_one_line=True, message_formatter=printer),
        ('optional_int32: 61 '
         'optional_nested_message { My lucky number is 1 } '
         'repeated_nested_message { My lucky number is 42 } '
         'repeated_nested_message { My lucky number is 99 }')) 
Example 11
Project: lambda-packs   Author: ryfeus   File: __init__.py    License: MIT License 6 votes vote down vote up
def visualize_embeddings(summary_writer, config):
  """Stores a config file used by the embedding projector.

  Args:
    summary_writer: The summary writer used for writting events.
    config: `tf.contrib.tensorboard.plugins.projector.ProjectorConfig`
      proto that holds the configuration for the projector such as paths to
      checkpoint files and metadata files for the embeddings. If
      `config.model_checkpoint_path` is none, it defaults to the
      `logdir` used by the summary_writer.

  Raises:
    ValueError: If the summary writer does not have a `logdir`.
  """
  logdir = summary_writer.get_logdir()

  # Sanity checks.
  if logdir is None:
    raise ValueError('Summary writer must have a logdir')

  # Saving the config file in the logdir.
  config_pbtxt = text_format.MessageToString(config)
  file_io.write_string_to_file(
      os.path.join(logdir, projector_plugin.PROJECTOR_FILENAME), config_pbtxt) 
Example 12
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: text_format_test.py    License: 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 13
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: text_format_test.py    License: 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 14
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: text_format_test.py    License: MIT License 6 votes vote down vote up
def testPrintInIndexOrder(self):
    message = unittest_pb2.TestFieldOrderings()
    message.my_string = '115'
    message.my_int = 101
    message.my_float = 111
    message.optional_nested_message.oo = 0
    message.optional_nested_message.bb = 1
    self.CompareToGoldenText(
        self.RemoveRedundantZeros(text_format.MessageToString(
            message, use_index_order=True)),
        'my_string: \"115\"\nmy_int: 101\nmy_float: 111\n'
        'optional_nested_message {\n  oo: 0\n  bb: 1\n}\n')
    self.CompareToGoldenText(
        self.RemoveRedundantZeros(text_format.MessageToString(message)),
        'my_int: 101\nmy_string: \"115\"\nmy_float: 111\n'
        'optional_nested_message {\n  bb: 1\n  oo: 0\n}\n') 
Example 15
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: text_format_test.py    License: MIT License 6 votes vote down vote up
def testMapOrderSemantics(self):
    golden_lines = self.ReadGolden('map_test_data.txt')
    # The C++ implementation emits defaulted-value fields, while the Python
    # implementation does not.  Adjusting for this is awkward, but it is
    # valuable to test against a common golden file.
    line_blacklist = ('  key: 0\n', '  value: 0\n', '  key: false\n',
                      '  value: false\n')
    golden_lines = [line for line in golden_lines if line not in line_blacklist]

    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)
    self.assertMultiLineEqual(candidate, ''.join(golden_lines))


# Tests of proto2-only features (MessageSet, extensions, etc.). 
Example 16
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: text_format_test.py    License: 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 17
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: text_format_test.py    License: 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 18
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: text_format_test.py    License: 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,
                                    descriptor_pool=descriptor_pool.Default()),
        '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 19
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: __init__.py    License: MIT License 6 votes vote down vote up
def visualize_embeddings(summary_writer, config):
  """Stores a config file used by the embedding projector.

  Args:
    summary_writer: The summary writer used for writting events.
    config: `tf.contrib.tensorboard.plugins.projector.ProjectorConfig`
      proto that holds the configuration for the projector such as paths to
      checkpoint files and metadata files for the embeddings. If
      `config.model_checkpoint_path` is none, it defaults to the
      `logdir` used by the summary_writer.

  Raises:
    ValueError: If the summary writer does not have a `logdir`.
  """
  logdir = summary_writer.get_logdir()

  # Sanity checks.
  if logdir is None:
    raise ValueError('Summary writer must have a logdir')

  # Saving the config file in the logdir.
  config_pbtxt = text_format.MessageToString(config)
  file_io.write_string_to_file(
      os.path.join(logdir, PROJECTOR_FILENAME), config_pbtxt) 
Example 20
Project: recipes-py   Author: luci   File: cmd.py    License: Apache License 2.0 5 votes vote down vote up
def main(args):
  logging.basicConfig()

  # defer to regenerate_doc for consistency between train and 'doc --kind gen'
  repo = args.recipe_deps.main_repo
  if repo.recipes_cfg_pb2.no_docs:
    LOGGER.warn('"no_docs" is set in recipes.cfg, generating docs anyway')

  if args.kind == 'gen':
    print('Generating README.recipes.md')
    with open(repo.readme_path, 'wb') as f:
      regenerate_doc(repo, f)
    return 0

  if args.recipe:
    node = parse_recipe(args.recipe_deps.recipes[args.recipe])
  else:
    node = parse_repo(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 21
Project: vehicle_counting_tensorflow   Author: ahmetozlu   File: config_util_test.py    License: 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 22
Project: deepchem   Author: deepchem   File: test_utils.py    License: MIT License 5 votes vote down vote up
def testParseCheckpoint(self):
    # parse CheckpointState proto
    with tempfile.NamedTemporaryFile(mode='w+') as f:
      cp = checkpoint_state_pb2.CheckpointState()
      cp.model_checkpoint_path = 'my-checkpoint'
      f.write(text_format.MessageToString(cp))
      f.file.flush()
      self.assertEqual(utils.ParseCheckpoint(f.name), 'my-checkpoint')
    # parse path to actual checkpoint
    with tempfile.NamedTemporaryFile(mode='w+') as f:
      f.write('This is not a CheckpointState proto.')
      f.file.flush()
      self.assertEqual(utils.ParseCheckpoint(f.name), f.name) 
Example 23
Project: lingvo   Author: tensorflow   File: saver.py    License: Apache License 2.0 5 votes vote down vote up
def _SetState(self, state):
    file_io.atomic_write_string_to_file(self._state_file,
                                        text_format.MessageToString(state)) 
Example 24
Project: lambda-packs   Author: ryfeus   File: proto_builder_test.py    License: 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 25
Project: lambda-packs   Author: ryfeus   File: proto_builder_test.py    License: 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 26
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: 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('\u00fc\ua71f'))
    self.CompareToGoldenText(
        text_format.MessageToString(message),
        'repeated_string: "\\303\\274\\352\\234\\237"\n') 
Example 27
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: 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 28
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: 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 29
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: 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('\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 30
Project: lambda-packs   Author: ryfeus   File: text_format_test.py    License: MIT License 5 votes vote down vote up
def testPrintRawUtf8String(self, message_module):
    message = message_module.TestAllTypes()
    message.repeated_string.append('\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))