Python google.protobuf.json_format.MessageToJson() Examples

The following are 30 code examples of google.protobuf.json_format.MessageToJson(). 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 also want to check out all available functions/classes of the module google.protobuf.json_format , or try the search function .
Example #1
Source File: base_factorization_machine.py    From FATE with Apache License 2.0 6 votes vote down vote up
def _get_param(self):
        header = self.header
        LOGGER.debug("In get_param, header: {}".format(header))
        if header is None:
            param_protobuf_obj = fm_model_param_pb2.FMModelParam()
            return param_protobuf_obj
        if self.need_one_vs_rest:
            # one_vs_rest_class = list(map(str, self.one_vs_rest_obj.classes))
            one_vs_rest_result = self.one_vs_rest_obj.save(fm_model_param_pb2.SingleModel)
            single_result = {'header': header, 'need_one_vs_rest': True}
        else:
            one_vs_rest_result = None
            single_result = self.get_single_model_param()
            single_result['need_one_vs_rest'] = False
        single_result['one_vs_rest_result'] = one_vs_rest_result
        LOGGER.debug("in _get_param, single_result: {}".format(single_result))

        param_protobuf_obj = fm_model_param_pb2.FMModelParam(**single_result)
        json_result = json_format.MessageToJson(param_protobuf_obj)
        LOGGER.debug("json_result: {}".format(json_result))
        return param_protobuf_obj 
Example #2
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testListValueMessage(self):
    message = json_format_proto3_pb2.TestListValue()
    message.value.values.add().number_value = 11.1
    message.value.values.add().null_value = 0
    message.value.values.add().bool_value = True
    message.value.values.add().string_value = 'hello'
    message.value.values.add().struct_value['name'] = 'Jim'
    message.repeated_value.add().values.add().number_value = 1
    message.repeated_value.add()
    self.assertEqual(
        json.loads(json_format.MessageToJson(message, False)),
        json.loads(
            '{"value": [11.1, null, true, "hello", {"name": "Jim"}]\n,'
            '"repeatedValue": [[1], []]}'))
    parsed_message = json_format_proto3_pb2.TestListValue()
    self.CheckParseBack(message, parsed_message) 
Example #3
Source File: json_format_test.py    From lambda-packs with MIT License 6 votes vote down vote up
def testJsonEscapeString(self):
    message = json_format_proto3_pb2.TestMessage()
    if sys.version_info[0] < 3:
      message.string_value = '&\n<\"\r>\b\t\f\\\001/\xe2\x80\xa8\xe2\x80\xa9'
    else:
      message.string_value = '&\n<\"\r>\b\t\f\\\001/'
      message.string_value += (b'\xe2\x80\xa8\xe2\x80\xa9').decode('utf-8')
    self.assertEqual(
        json_format.MessageToJson(message),
        '{\n  "stringValue": '
        '"&\\n<\\\"\\r>\\b\\t\\f\\\\\\u0001/\\u2028\\u2029"\n}')
    parsed_message = json_format_proto3_pb2.TestMessage()
    self.CheckParseBack(message, parsed_message)
    text = '{"int32Value": "\u0031"}'
    json_format.Parse(text, message)
    self.assertEqual(message.int32_value, 1) 
Example #4
Source File: json_format_test.py    From lambda-packs with MIT License 6 votes vote down vote up
def testExtensionSerializationJsonMatchesProto3Spec(self):
    """See go/proto3-json-spec for spec.
    """
    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'
    message_text = json_format.MessageToJson(
        message
    )
    ext1_text = ('protobuf_unittest.TestMessageSetExtension1.'
                 'messageSetExtension')
    ext2_text = ('protobuf_unittest.TestMessageSetExtension2.'
                 'messageSetExtension')
    golden_text = ('{"messageSet": {'
                   '    "[%s]": {'
                   '        "i": 23'
                   '    },'
                   '    "[%s]": {'
                   '        "str": "foo"'
                   '    }'
                   '}}') % (ext1_text, ext2_text)
    self.assertEqual(json.loads(golden_text), json.loads(message_text)) 
Example #5
Source File: json_format_test.py    From lambda-packs with MIT License 6 votes vote down vote up
def testDurationMessage(self):
    message = json_format_proto3_pb2.TestDuration()
    message.value.seconds = 1
    message.repeated_value.add().seconds = 0
    message.repeated_value[0].nanos = 10
    message.repeated_value.add().seconds = -1
    message.repeated_value[1].nanos = -1000
    message.repeated_value.add().seconds = 10
    message.repeated_value[2].nanos = 11000000
    message.repeated_value.add().seconds = -315576000000
    message.repeated_value.add().seconds = 315576000000
    self.assertEqual(
        json.loads(json_format.MessageToJson(message, True)),
        json.loads('{'
                   '"value": "1s",'
                   '"repeatedValue": ['
                   '  "0.000000010s",'
                   '  "-1.000001s",'
                   '  "10.011s",'
                   '  "-315576000000s",'
                   '  "315576000000s"'
                   ']'
                   '}'))
    parsed_message = json_format_proto3_pb2.TestDuration()
    self.CheckParseBack(message, parsed_message) 
Example #6
Source File: earlystopping.py    From calamari with Apache License 2.0 6 votes vote down vote up
def make_checkpoint(self, base_dir, prefix, version=None):
        base_dir = os.path.abspath(base_dir)
        os.makedirs(base_dir, exist_ok=True)
        checkpoint_params = self.checkpoint_params
        if version:
            checkpoint_path = os.path.abspath(os.path.join(base_dir, "{}{}.ckpt".format(prefix, version)))
        else:
            checkpoint_path = os.path.abspath(os.path.join(base_dir, "{}{:08d}.ckpt".format(prefix, checkpoint_params.iter + 1)))
        print("Storing checkpoint to '{}'".format(checkpoint_path))
        self.model.save(checkpoint_path + '.h5', overwrite=True)
        checkpoint_params.version = Checkpoint.VERSION
        checkpoint_params.loss_stats[:] = self.vis_cb.loss_stats.values
        checkpoint_params.ler_stats[:] = self.vis_cb.ler_stats.values
        checkpoint_params.dt_stats[:] = self.vis_cb.dt_stats.values
        checkpoint_params.total_time = time.time() - self.train_start_time
        checkpoint_params.early_stopping_best_accuracy = self.early_stopping_best_accuracy
        checkpoint_params.early_stopping_best_cur_nbest = self.early_stopping_best_cur_nbest
        checkpoint_params.early_stopping_best_at_iter = self.early_stopping_best_at_iter

        with open(checkpoint_path + ".json", 'w') as f:
            f.write(json_format.MessageToJson(checkpoint_params))

        return checkpoint_path 
Example #7
Source File: pred_to_json.py    From calamari with Apache License 2.0 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--files", type=str, default=[], nargs="+", required=True,
                        help="Protobuf files to convert")
    parser.add_argument("--logits", action="store_true",
                        help="Do write logits")
    args = parser.parse_args()

    files = glob_all(args.files)
    for file in tqdm(files, desc="Converting"):
        predictions = Predictions()
        with open(file, 'rb') as f:
            predictions.ParseFromString(f.read())

        if not args.logits:
            for prediction in predictions.predictions:
                prediction.logits.rows = 0
                prediction.logits.cols = 0
                prediction.logits.data[:] = []

        out_json_path = split_all_ext(file)[0] + ".json"
        with open(out_json_path, 'w') as f:
            f.write(MessageToJson(predictions, including_default_value_fields=True)) 
Example #8
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testDurationMessage(self):
    message = json_format_proto3_pb2.TestDuration()
    message.value.seconds = 1
    message.repeated_value.add().seconds = 0
    message.repeated_value[0].nanos = 10
    message.repeated_value.add().seconds = -1
    message.repeated_value[1].nanos = -1000
    message.repeated_value.add().seconds = 10
    message.repeated_value[2].nanos = 11000000
    message.repeated_value.add().seconds = -315576000000
    message.repeated_value.add().seconds = 315576000000
    self.assertEqual(
        json.loads(json_format.MessageToJson(message, True)),
        json.loads('{'
                   '"value": "1s",'
                   '"repeatedValue": ['
                   '  "0.000000010s",'
                   '  "-1.000001s",'
                   '  "10.011s",'
                   '  "-315576000000s",'
                   '  "315576000000s"'
                   ']'
                   '}'))
    parsed_message = json_format_proto3_pb2.TestDuration()
    self.CheckParseBack(message, parsed_message) 
Example #9
Source File: tensorflow_model_loader.py    From sparkflow with MIT License 6 votes vote down vote up
def load_tensorflow_model(
        path,
        inputCol,
        tfInput,
        tfOutput,
        predictionCol='predicted',
        tfDropout=None,
        toKeepDropout=False):
    with tf.Session(graph=tf.Graph()) as sess:
        new_saver = tf.train.import_meta_graph(path + '.meta')
        split = path.split('/')
        if len(split) > 1:
            new_saver.restore(sess, tf.train.latest_checkpoint("/".join(split[:-1])))
        else:
            new_saver.restore(sess, tf.train.latest_checkpoint(split[0]))
        vs = tf.trainable_variables()
        weights = sess.run(vs)
        json_graph = json_format.MessageToJson(tf.train.export_meta_graph())

    weights = [w.tolist() for w in weights]
    json_weights = json.dumps(weights)
    return SparkAsyncDLModel(
        inputCol=inputCol, modelJson=json_graph, modelWeights=json_weights,
        tfInput=tfInput, tfOutput=tfOutput, predictionCol=predictionCol, tfDropout=tfDropout, toKeepDropout=toKeepDropout
    ) 
Example #10
Source File: stats_options.py    From data-validation with Apache License 2.0 6 votes vote down vote up
def to_json(self) -> Text:
    """Convert from an object to JSON representation of the __dict__ attribute.

    Custom generators and slice_functions are skipped, meaning that they will
    not be used when running TFDV in a setting where the stats options have been
    json-serialized, first. This will happen in the case where TFDV is run as a
    TFX component. The schema proto will be json_encoded.

    Returns:
      A JSON representation of a filtered version of __dict__.
    """
    options_dict = copy.copy(self.__dict__)
    options_dict['_slice_functions'] = None
    options_dict['_generators'] = None
    if self.schema:
      del options_dict['_schema']
      options_dict['schema_json'] = json_format.MessageToJson(self.schema)
    return json.dumps(options_dict) 
Example #11
Source File: json_format_test.py    From lambda-packs with MIT License 6 votes vote down vote up
def testPreservingProtoFieldNames(self):
    message = json_format_proto3_pb2.TestMessage()
    message.int32_value = 12345
    self.assertEqual('{\n  "int32Value": 12345\n}',
                     json_format.MessageToJson(message))
    self.assertEqual('{\n  "int32_value": 12345\n}',
                     json_format.MessageToJson(message, False, True))
    # When including_default_value_fields is True.
    message = json_format_proto3_pb2.TestTimestamp()
    self.assertEqual('{\n  "repeatedValue": []\n}',
                     json_format.MessageToJson(message, True, False))
    self.assertEqual('{\n  "repeated_value": []\n}',
                     json_format.MessageToJson(message, True, True))

    # Parsers accept both original proto field names and lowerCamelCase names.
    message = json_format_proto3_pb2.TestMessage()
    json_format.Parse('{"int32Value": 54321}', message)
    self.assertEqual(54321, message.int32_value)
    json_format.Parse('{"int32_value": 12345}', message)
    self.assertEqual(12345, message.int32_value) 
Example #12
Source File: base_logistic_regression.py    From FATE with Apache License 2.0 6 votes vote down vote up
def _get_param(self):
        header = self.header
        LOGGER.debug("In get_param, header: {}".format(header))
        if header is None:
            param_protobuf_obj = lr_model_param_pb2.LRModelParam()
            return param_protobuf_obj
        if self.need_one_vs_rest:
            # one_vs_rest_class = list(map(str, self.one_vs_rest_obj.classes))
            one_vs_rest_result = self.one_vs_rest_obj.save(lr_model_param_pb2.SingleModel)
            single_result = {'header': header, 'need_one_vs_rest': True}
        else:
            one_vs_rest_result = None
            single_result = self.get_single_model_param()
            single_result['need_one_vs_rest'] = False
        single_result['one_vs_rest_result'] = one_vs_rest_result
        LOGGER.debug("in _get_param, single_result: {}".format(single_result))

        param_protobuf_obj = lr_model_param_pb2.LRModelParam(**single_result)
        json_result = json_format.MessageToJson(param_protobuf_obj)
        LOGGER.debug("json_result: {}".format(json_result))
        return param_protobuf_obj 
Example #13
Source File: fake_recipe_deps.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
def edit_recipes_cfg_pb2(self):
    """Context manager for read/modify/write'ing the recipes.cfg file in this
    repo.

    Usage:

        with repo.edit_recipes_cfg_pb2() as pb:
          pb.deps['some_repo'].revision = 'abcdefg'

    Yields a recipes_cfg_pb2.RepoSpec object decoded from the current state of
    the recipes.cfg file. Any modifications done to this object will be recorded
    back to disk.
    """
    spec = self.recipes_cfg_pb2
    yield spec
    cfg_path = os.path.join(self.path, RECIPES_CFG_LOCATION_REL)
    with open(cfg_path, 'wb') as fil:
      fil.write(jsonpb.MessageToJson(spec, preserving_proto_field_name=True)) 
Example #14
Source File: homo_lr_host.py    From FATE with Apache License 2.0 6 votes vote down vote up
def _get_param(self):
        header = self.header

        weight_dict = {}
        intercept = 0
        if not self.use_encrypt:
            lr_vars = self.model_weights.coef_
            for idx, header_name in enumerate(header):
                coef_i = lr_vars[idx]
                weight_dict[header_name] = coef_i
            intercept = self.model_weights.intercept_

        param_protobuf_obj = lr_model_param_pb2.LRModelParam(iters=self.n_iter_,
                                                             loss_history=self.loss_history,
                                                             is_converged=self.is_converged,
                                                             weight=weight_dict,
                                                             intercept=intercept,
                                                             header=header)
        from google.protobuf import json_format
        json_result = json_format.MessageToJson(param_protobuf_obj)
        LOGGER.debug("json_result: {}".format(json_result))
        return param_protobuf_obj 
Example #15
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testJsonEscapeString(self):
    message = json_format_proto3_pb2.TestMessage()
    if sys.version_info[0] < 3:
      message.string_value = '&\n<\"\r>\b\t\f\\\001/\xe2\x80\xa8\xe2\x80\xa9'
    else:
      message.string_value = '&\n<\"\r>\b\t\f\\\001/'
      message.string_value += (b'\xe2\x80\xa8\xe2\x80\xa9').decode('utf-8')
    self.assertEqual(
        json_format.MessageToJson(message),
        '{\n  "stringValue": '
        '"&\\n<\\\"\\r>\\b\\t\\f\\\\\\u0001/\\u2028\\u2029"\n}')
    parsed_message = json_format_proto3_pb2.TestMessage()
    self.CheckParseBack(message, parsed_message)
    text = u'{"int32Value": "\u0031"}'
    json_format.Parse(text, message)
    self.assertEqual(message.int32_value, 1) 
Example #16
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def testStructMessage(self):
    message = json_format_proto3_pb2.TestStruct()
    message.value['name'] = 'Jim'
    message.value['age'] = 10
    message.value['attend'] = True
    message.value['email'] = None
    message.value.get_or_create_struct('address')['city'] = 'SFO'
    message.value['address']['house_number'] = 1024
    struct_list = message.value.get_or_create_list('list')
    struct_list.extend([6, 'seven', True, False, None])
    struct_list.add_struct()['subkey2'] = 9
    message.repeated_value.add()['age'] = 11
    message.repeated_value.add()
    self.assertEqual(
        json.loads(json_format.MessageToJson(message, False)),
        json.loads(
            '{'
            '  "value": {'
            '    "address": {'
            '      "city": "SFO", '
            '      "house_number": 1024'
            '    }, '
            '    "age": 10, '
            '    "name": "Jim", '
            '    "attend": true, '
            '    "email": null, '
            '    "list": [6, "seven", true, false, null, {"subkey2": 9}]'
            '  },'
            '  "repeatedValue": [{"age": 11}, {}]'
            '}'))
    parsed_message = json_format_proto3_pb2.TestStruct()
    self.CheckParseBack(message, parsed_message) 
Example #17
Source File: rib_api_service.py    From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_request(self, format=None, request_id=None):
        '''
            Returns Modify.ModifyRequest in one of given formats.
            Throws KeyError in case no such request is present.

            Args:
                format (str): json, proto, dict or string. Defaults to json.
                request_id (int): Modify.ModifyRequest.Request.id
        '''
        supported_formats = ['json', 'proto', 'dict', 'string']
        if format not in supported_formats:
            raise ValueError('{format} is not supported use one of {supported}'.format(
                                                                    format=format,
                                                                    supported=supported_formats))

        msg = rib.ModifyRequest(self.processed_request[request_id]['request'])
        if format == 'proto':
            return msg
        elif format == 'json':
            return json_format.MessageToJson(msg,
                                             including_default_value_fields=True,
                                             preserving_proto_field_name=True)
        elif format == 'dict':
            return json_format.MessageToDict(msg,
                                             including_default_value_fields=True,
                                             preserving_proto_field_name=True)
        elif format == 'str':
            return str(msg) 
Example #18
Source File: gnoi_cert.py    From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self):
        response = (
            json_format.MessageToJson(
                self.response,
                including_default_value_fields=True,
                preserving_proto_field_name=True,
            )
            if self.response
            else None
        )
        return ("Certificates:\n{response}\n\n" "ERROR:\n{error}\n").format(
            request=self.request, response=response, error=self.error
        ) 
Example #19
Source File: grpc_lib.py    From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serialize(self, target=None, msg=None, format=None):
        """Serialize message from python object to format.

        Returns messsage in given format or if target is speficied, the
        message is dumped to given path.

        Args:
            target (str): Path to file where serialized message will
                be stored. If none, the message will be returned.
            msg: Object which contains protobuf message.
            format: One of formats listed in Rpc.supported_formats

        """

        if format not in Rpc.supported_formats:
            raise ValueError('{format} is not supported, use one of {supported}'.format(
                            format= format, supported=Rpc.supported_formats))

        if format == 'string':
            result  = msg.SerializeToString()
        elif format == 'json':
            result = json_format.MessageToJson(msg,
                                including_default_value_fields=True,
                                preserving_proto_field_name=True)
        elif format == 'dict':
            result =  json_format.MessageToDict(msg,
                                    including_default_value_fields=True,
                                    preserving_proto_field_name=True)

        if target:
            with open(target, 'wb') as fd:
                if format in ['string', 'json']:
                    msg = fd.write(result)
                elif format in ['dict']:
                    msg = pickle.dump(result, fd)
        else:
            return result 
Example #20
Source File: rib_api_service.py    From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_response(self, format=None):
        '''
            Returns Modify.ModifyResponse in one of given formats.
            Throws KeyError in case no such request is present.

            Args:
                format (str): json, proto, dict or string. Defaults to json.
                request_id (int): Modify.ModifyResponse.Result.id
        '''
        supported_formats = ['json', 'proto', 'dict', 'string']
        if format not in supported_formats:
            raise ValueError('{format} is not supported, use one of {supported}'.format(
                                                                     format=format,
                                                                     supported=supported_formats))
        msg = rib.ModifyRequest(self.processed_request[request_id]['response'])
        if format == 'proto':
            return msg
        elif format == 'json':
            return json_format.MessageToJson(msg,
                                             including_default_value_fields=True,
                                             preserving_proto_field_name=True)
        elif format == 'dict':
            return json_format.MessageToDict(msg,
                                             including_default_value_fields=True,
                                             preserving_proto_field_name=True)
        elif format == 'str':
            return str(msg) 
Example #21
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def CheckParseBack(self, message, parsed_message):
    json_format.Parse(json_format.MessageToJson(message),
                      parsed_message)
    self.assertEqual(message, parsed_message) 
Example #22
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def testValueMessage(self):
    message = json_format_proto3_pb2.TestValue()
    message.value.string_value = 'hello'
    message.repeated_value.add().number_value = 11.1
    message.repeated_value.add().bool_value = False
    message.repeated_value.add().null_value = 0
    self.assertEqual(
        json.loads(json_format.MessageToJson(message, False)),
        json.loads(
            '{'
            '  "value": "hello",'
            '  "repeatedValue": [11.1, false, null]'
            '}'))
    parsed_message = json_format_proto3_pb2.TestValue()
    self.CheckParseBack(message, parsed_message)
    # Can't parse back if the Value message is not set.
    message.repeated_value.add()
    self.assertEqual(
        json.loads(json_format.MessageToJson(message, False)),
        json.loads(
            '{'
            '  "value": "hello",'
            '  "repeatedValue": [11.1, false, null, null]'
            '}'))
    message.Clear()
    json_format.Parse('{"value": null}', message)
    self.assertEqual(message.value.WhichOneof('kind'), 'null_value') 
Example #23
Source File: summary_ops.py    From lambda-packs with MIT License 5 votes vote down vote up
def tensor_summary(  # pylint: disable=invalid-name
    name,
    tensor,
    summary_description=None,
    collections=None):
  # pylint: disable=line-too-long
  """Outputs a `Summary` protocol buffer with a serialized tensor.proto.

  The generated
  [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto)
  has one summary value containing the input tensor.

  Args:
    name: A name for the generated node. Will also serve as the series name in
      TensorBoard.
    tensor: A tensor of any type and shape to serialize.
    summary_description: Optional summary_pb2.SummaryDescription()
    collections: Optional list of graph collections keys. The new summary op is
      added to these collections. Defaults to `[GraphKeys.SUMMARIES]`.

  Returns:
    A scalar `Tensor` of type `string`. The serialized `Summary` protocol
    buffer.
  """
  # pylint: enable=line-too-long

  if summary_description is None:
    summary_description = summary_pb2.SummaryDescription()

  description = json_format.MessageToJson(summary_description)
  with ops.name_scope(name, None, [tensor]) as scope:
    val = gen_logging_ops._tensor_summary(
        tensor=tensor,
        description=description,
        name=scope)
    _Collect(val, collections, [ops.GraphKeys.SUMMARIES])
  return val 
Example #24
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def testFieldMaskMessage(self):
    message = json_format_proto3_pb2.TestFieldMask()
    message.value.paths.append('foo.bar')
    message.value.paths.append('bar')
    self.assertEqual(
        json_format.MessageToJson(message, True),
        '{\n'
        '  "value": "foo.bar,bar"\n'
        '}')
    parsed_message = json_format_proto3_pb2.TestFieldMask()
    self.CheckParseBack(message, parsed_message) 
Example #25
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def testEmptyMessageToJson(self):
    message = json_format_proto3_pb2.TestMessage()
    self.assertEqual(json_format.MessageToJson(message),
                     '{}')
    parsed_message = json_format_proto3_pb2.TestMessage()
    self.CheckParseBack(message, parsed_message) 
Example #26
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def testPartialMessageToJson(self):
    message = json_format_proto3_pb2.TestMessage(
        string_value='test',
        repeated_int32_value=[89, 4])
    self.assertEqual(json.loads(json_format.MessageToJson(message)),
                     json.loads('{"stringValue": "test", '
                                '"repeatedInt32Value": [89, 4]}'))
    parsed_message = json_format_proto3_pb2.TestMessage()
    self.CheckParseBack(message, parsed_message) 
Example #27
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def testAllFieldsToJson(self):
    message = json_format_proto3_pb2.TestMessage()
    text = ('{"int32Value": 20, '
            '"int64Value": "-20", '
            '"uint32Value": 3120987654,'
            '"uint64Value": "12345678900",'
            '"floatValue": "-Infinity",'
            '"doubleValue": 3.1415,'
            '"boolValue": true,'
            '"stringValue": "foo",'
            '"bytesValue": "YmFy",'
            '"messageValue": {"value": 10},'
            '"enumValue": "BAR",'
            '"repeatedInt32Value": [2147483647, -2147483648],'
            '"repeatedInt64Value": ["9007199254740992", "-9007199254740992"],'
            '"repeatedUint32Value": [268435455, 134217727],'
            '"repeatedUint64Value": ["9007199254740992", "9007199254740991"],'
            '"repeatedFloatValue": [0],'
            '"repeatedDoubleValue": [1e-15, "Infinity"],'
            '"repeatedBoolValue": [true, false],'
            '"repeatedStringValue": ["Few symbols!#$,;", "bar"],'
            '"repeatedBytesValue": ["Zm9v", "YmFy"],'
            '"repeatedMessageValue": [{"value": 10}, {"value": 11}],'
            '"repeatedEnumValue": ["FOO", "BAR"]'
            '}')
    self.FillAllFields(message)
    self.assertEqual(
        json.loads(json_format.MessageToJson(message)),
        json.loads(text))
    parsed_message = json_format_proto3_pb2.TestMessage()
    json_format.Parse(text, parsed_message)
    self.assertEqual(message, parsed_message) 
Example #28
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def testTimestampMessage(self):
    message = json_format_proto3_pb2.TestTimestamp()
    message.value.seconds = 0
    message.value.nanos = 0
    message.repeated_value.add().seconds = 20
    message.repeated_value[0].nanos = 1
    message.repeated_value.add().seconds = 0
    message.repeated_value[1].nanos = 10000
    message.repeated_value.add().seconds = 100000000
    message.repeated_value[2].nanos = 0
    # Maximum time
    message.repeated_value.add().seconds = 253402300799
    message.repeated_value[3].nanos = 999999999
    # Minimum time
    message.repeated_value.add().seconds = -62135596800
    message.repeated_value[4].nanos = 0
    self.assertEqual(
        json.loads(json_format.MessageToJson(message, True)),
        json.loads('{'
                   '"value": "1970-01-01T00:00:00Z",'
                   '"repeatedValue": ['
                   '  "1970-01-01T00:00:20.000000001Z",'
                   '  "1970-01-01T00:00:00.000010Z",'
                   '  "1973-03-03T09:46:40Z",'
                   '  "9999-12-31T23:59:59.999999999Z",'
                   '  "0001-01-01T00:00:00Z"'
                   ']'
                   '}'))
    parsed_message = json_format_proto3_pb2.TestTimestamp()
    self.CheckParseBack(message, parsed_message)
    text = (r'{"value": "1970-01-01T00:00:00.01+08:00",'
            r'"repeatedValue":['
            r'  "1970-01-01T00:00:00.01+08:30",'
            r'  "1970-01-01T00:00:00.01-01:23"]}')
    json_format.Parse(text, parsed_message)
    self.assertEqual(parsed_message.value.seconds, -8 * 3600)
    self.assertEqual(parsed_message.value.nanos, 10000000)
    self.assertEqual(parsed_message.repeated_value[0].seconds, -8.5 * 3600)
    self.assertEqual(parsed_message.repeated_value[1].seconds, 3600 + 23 * 60) 
Example #29
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def testOneofFields(self):
    message = json_format_proto3_pb2.TestOneof()
    # Always print does not affect oneof fields.
    self.assertEqual(
        json_format.MessageToJson(message, True),
        '{}')
    message.oneof_int32_value = 0
    self.assertEqual(
        json_format.MessageToJson(message, True),
        '{\n'
        '  "oneofInt32Value": 0\n'
        '}')
    parsed_message = json_format_proto3_pb2.TestOneof()
    self.CheckParseBack(message, parsed_message) 
Example #30
Source File: json_format_test.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def testMapFields(self):
    message = json_format_proto3_pb2.TestMap()
    message.bool_map[True] = 1
    message.bool_map[False] = 2
    message.int32_map[1] = 2
    message.int32_map[2] = 3
    message.int64_map[1] = 2
    message.int64_map[2] = 3
    message.uint32_map[1] = 2
    message.uint32_map[2] = 3
    message.uint64_map[1] = 2
    message.uint64_map[2] = 3
    message.string_map['1'] = 2
    message.string_map['null'] = 3
    self.assertEqual(
        json.loads(json_format.MessageToJson(message, True)),
        json.loads('{'
                   '"boolMap": {"false": 2, "true": 1},'
                   '"int32Map": {"1": 2, "2": 3},'
                   '"int64Map": {"1": 2, "2": 3},'
                   '"uint32Map": {"1": 2, "2": 3},'
                   '"uint64Map": {"1": 2, "2": 3},'
                   '"stringMap": {"1": 2, "null": 3}'
                   '}'))
    parsed_message = json_format_proto3_pb2.TestMap()
    self.CheckParseBack(message, parsed_message)