150 def __call__(self, servicer_method, /) -> MockDecorator:
152 Returns a decorator to mock the specified gRPC service method implementation.
156 @snippet samples/grpc_service/testsuite/test_grpc.py Prepare modules
157 @snippet samples/grpc_service/testsuite/test_grpc.py grpc client test
159 servicer_class = _get_class_from_method(servicer_method)
161 return mock.install_handler(servicer_method.__name__)
163 def mock_factory(self, servicer_class, /) -> Callable[[str], MockDecorator]:
165 Allows to create a fixture as a shorthand for mocking methods of the specified gRPC service.
169 @snippet grpc/functional_tests/metrics/tests/conftest.py Prepare modules
170 @snippet grpc/functional_tests/metrics/tests/conftest.py Prepare server mock
171 @snippet grpc/functional_tests/metrics/tests/test_metrics.py grpc client test
174 def factory(method_name):
175 method = getattr(servicer_class, method_name,
None)
177 raise ValueError(f
'No method "{method_name}" in servicer class "{servicer_class.__name__}"')
180 _check_is_servicer_class(servicer_class)
185 Installs as a mock `servicer`, the class of which should inherit from a generated `*Servicer` class.
187 1. Write a service implementation:
189 @snippet grpc/functional_tests/middleware_client/tests/test_install_servicer.py servicer
191 @note Inheritance from multiple `*Servicer` classes at once is allowed.
193 2. Install servicer instance:
195 @snippet grpc/functional_tests/middleware_client/tests/test_install_servicer.py install servicer
199 @snippet grpc/functional_tests/middleware_client/tests/test_install_servicer.py use mock
201 base_servicer_classes = [cls
for cls
in inspect.getmro(type(servicer))
if _is_servicer_class(cls)]
202 if not base_servicer_classes:
203 raise ValueError(f
"Given object's type ({type(servicer)}) is not inherited from any grpc *Servicer class")
204 proxy = _MockProxy(servicer)
205 for servicer_class
in base_servicer_classes:
208 for python_method_name
in mock.known_methods:
209 if _get_class_that_defined_method(type(servicer), python_method_name)
not in base_servicer_classes:
210 handler_func: types.MethodType = getattr(servicer, python_method_name)
211 callqueue = mock.install_handler(python_method_name)(handler_func)
212 object.__setattr__(proxy, python_method_name, callqueue)
213 return typing.cast(Servicer, proxy)
219async def _stop_server(server: grpc.aio.Server, /) ->
None:
220 async def stop_server():
221 await server.stop(grace=
None)
222 await server.wait_for_termination()
224 stop_server_task = asyncio.shield(asyncio.create_task(stop_server()))
228 await stop_server_task
229 except asyncio.CancelledError:
230 await stop_server_task
235def _get_class_from_method(method) -> type:
237 assert inspect.isfunction(method), f
'Expected an unbound method: foo(ClassName.MethodName), got: {method}'
238 class_name = method.__qualname__.split(
'.<locals>', 1)[0].rsplit(
'.', 1)[0]
240 cls = getattr(inspect.getmodule(method), class_name)
241 except AttributeError:
242 cls = method.__globals__.get(class_name)
243 assert isinstance(cls, type)
247def _get_class_that_defined_method(cls: type, method_name: str) -> type |
None:
248 for cls
in inspect.getmro(cls):
249 if method_name
in cls.__dict__:
255def _is_servicer_class(cls: type) -> bool:
257 return '_pb2_grpc.' in inspect.getfile(cls)
262class _MockProxy(Generic[Servicer]):
263 def __init__(self, wrapped_servicer: Servicer) ->
None:
264 object.__setattr__(self,
'_wrapped_servicer', wrapped_servicer)
266 def __getattr__(self, name: str) -> Any:
267 servicer: Servicer = object.__getattribute__(self,
'_wrapped_servicer')
268 return getattr(servicer, name)
270 def __setattr__(self, name: str, value: Any) ->
None:
271 servicer: Servicer = object.__getattribute__(self,
'_wrapped_servicer')
272 setattr(servicer, name, value)