Raise KeyError in Python ServiceDescriptor.FindMethodByName (#9592)

* Align Python version with C-extension version
  (python/google/protobuf/pyext/descriptor.cc)
* Update documentation accordingly
* Add unit test
pull/9998/head
Tomer Vromen 3 years ago committed by Tomer Vromen
parent 3380463ff8
commit 056b62a237
  1. 9
      python/google/protobuf/descriptor.py
  2. 8
      python/google/protobuf/internal/descriptor_test.py

@ -873,11 +873,14 @@ class ServiceDescriptor(_NestedDescriptorBase):
Args: Args:
name (str): Name of the method. name (str): Name of the method.
Returns: Returns:
MethodDescriptor or None: the descriptor for the requested method, if MethodDescriptor: The descriptor for the requested method.
found.
Raises:
KeyError: if the method cannot be found in the service.
""" """
return self.methods_by_name.get(name, None) return self.methods_by_name[name]
def CopyToProto(self, proto): def CopyToProto(self, proto):
"""Copies this to a descriptor_pb2.ServiceDescriptorProto. """Copies this to a descriptor_pb2.ServiceDescriptorProto.

@ -118,6 +118,14 @@ class DescriptorTest(unittest.TestCase):
def GetDescriptorPool(self): def GetDescriptorPool(self):
return symbol_database.Default().pool return symbol_database.Default().pool
def testFindMethodByName(self):
service_descriptor = (unittest_custom_options_pb2.
TestServiceWithCustomOptions.DESCRIPTOR)
method_descriptor = service_descriptor.FindMethodByName('Foo')
self.assertEqual(method_descriptor.name, 'Foo')
with self.assertRaises(KeyError):
service_descriptor.FindMethodByName('MethodDoesNotExist')
def testEnumValueName(self): def testEnumValueName(self):
self.assertEqual(self.my_message.EnumValueName('ForeignEnum', 4), self.assertEqual(self.my_message.EnumValueName('ForeignEnum', 4),
'FOREIGN_FOO') 'FOREIGN_FOO')

Loading…
Cancel
Save