Skip to content

Commit

Permalink
Nextgen Proto Pythonic API: Add any.py
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 664995003
  • Loading branch information
anandolee authored and copybara-github committed Aug 19, 2024
1 parent ebd9838 commit dd95e5b
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
39 changes: 39 additions & 0 deletions python/google/protobuf/any.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd

"""Contains the Any helper APIs."""

from typing import Optional

from google.protobuf import descriptor
from google.protobuf.message import Message

from google.protobuf.any_pb2 import Any


def pack(
msg: Message,
type_url_prefix: Optional[str] = 'type.googleapis.com/',
deterministic: Optional[bool] = None,
) -> Any:
any_msg = Any()
any_msg.Pack(
msg=msg, type_url_prefix=type_url_prefix, deterministic=deterministic
)
return any_msg


def unpack(any_msg: Any, msg: Message) -> bool:
return any_msg.Unpack(msg=msg)


def type_name(any_msg: Any) -> str:
return any_msg.TypeName()


def is_type(any_msg: Any, des: descriptor.Descriptor) -> bool:
return any_msg.Is(des)
47 changes: 47 additions & 0 deletions python/google/protobuf/internal/any_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd

"""Tests proto Any APIs."""

import unittest

from google.protobuf import any

from google.protobuf import any_pb2
from google.protobuf import unittest_pb2


class AnyTest(unittest.TestCase):

def test_pack_unpack(self):
all_types = unittest_pb2.TestAllTypes()
any_msg = any.pack(all_types)
all_descriptor = all_types.DESCRIPTOR
self.assertEqual(
any_msg.type_url, 'type.googleapis.com/%s' % all_descriptor.full_name
)
unpacked_message = unittest_pb2.TestAllTypes()
self.assertTrue(any.unpack(any_msg, unpacked_message))

def test_type_name(self):
all_types = unittest_pb2.TestAllTypes()
any_msg = any.pack(all_types)
self.assertEqual(any.type_name(any_msg), 'protobuf_unittest.TestAllTypes')

def test_is_type(self):
all_types = unittest_pb2.TestAllTypes()
any_msg = any.pack(all_types)
all_descriptor = all_types.DESCRIPTOR
self.assertTrue(any.is_type(any_msg, all_descriptor))

empty_any = any_pb2.Any()
self.assertFalse(any.is_type(empty_any, all_descriptor))


if __name__ == '__main__':
unittest.main()

0 comments on commit dd95e5b

Please sign in to comment.