From 056b62a237252057d48b20b3d8d188fc6bdcb5ff Mon Sep 17 00:00:00 2001 From: Tomer Vromen Date: Thu, 19 May 2022 14:08:50 +0300 Subject: [PATCH] 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 --- python/google/protobuf/descriptor.py | 9 ++++++--- python/google/protobuf/internal/descriptor_test.py | 8 ++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/python/google/protobuf/descriptor.py b/python/google/protobuf/descriptor.py index f5a0caa6bd..fa7a5b96d5 100644 --- a/python/google/protobuf/descriptor.py +++ b/python/google/protobuf/descriptor.py @@ -873,11 +873,14 @@ class ServiceDescriptor(_NestedDescriptorBase): 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. diff --git a/python/google/protobuf/internal/descriptor_test.py b/python/google/protobuf/internal/descriptor_test.py index 6a8532c408..8c43e476f9 100644 --- a/python/google/protobuf/internal/descriptor_test.py +++ b/python/google/protobuf/internal/descriptor_test.py @@ -118,6 +118,14 @@ class DescriptorTest(unittest.TestCase): 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(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')