Skip to content

Commit

Permalink
Raise KeyError in Python ServiceDescriptor.FindMethodByName (protocol…
Browse files Browse the repository at this point in the history
…buffers#9592)

* Align Python version with C-extension version
  (python/google/protobuf/pyext/descriptor.cc)
* Update documentation accordingly
* Add unit test
  • Loading branch information
tomerv authored and Tomer_Vromen committed May 19, 2022
1 parent fd3b5a3 commit 7290cc1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
9 changes: 6 additions & 3 deletions python/google/protobuf/descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -873,11 +873,14 @@ def FindMethodByName(self, name):
Args:
name (str): Name of the method.
Returns:
MethodDescriptor or None: the descriptor for the requested method, if
found.
MethodDescriptor: The descriptor for the requested method.
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):
"""Copies this to a descriptor_pb2.ServiceDescriptorProto.
Expand Down
9 changes: 9 additions & 0 deletions python/google/protobuf/internal/descriptor_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,15 @@ def setUp(self):
def GetDescriptorPool(self):
return symbol_database.Default().pool

def testFindMethodByName(self):
service_descriptor = (unittest_custom_options_pb2.
TestServiceWithCustomOptions.DESCRIPTOR)
method_descriptor = service_descriptor.FindMethodByName('Foo')
self.assertEqual(type(method_descriptor), descriptor.MethodDescriptor)
self.assertEqual(method_descriptor.name, 'Foo')
with self.assertRaises(KeyError):
service_descriptor.FindMethodByName('MethodDoesNotExist')

def testEnumValueName(self):
self.assertEqual(self.my_message.EnumValueName('ForeignEnum', 4),
'FOREIGN_FOO')
Expand Down

0 comments on commit 7290cc1

Please sign in to comment.