36 Allows to install mocks that are kept active between tests, see
37 @ref pytest_userver.plugins.grpc.mockserver.grpc_mockserver_session "grpc_mockserver_session".
39 @warning This is a sharp knife, use with caution! For most use-cases, prefer
40 @ref pytest_userver.plugins.grpc.mockserver.grpc_mockserver "grpc_mockserver" instead.
43 def __init__(self, *, server: grpc.aio.Server, experimental: bool =
False) ->
None:
45 @warning This initializer is an **experimental API**, likely to break in the future. Consider using
46 @ref pytest_userver.plugins.grpc.mockserver.grpc_mockserver_session "grpc_mockserver_session" instead.
48 Initializes `MockserverSession`. Takes ownership of `server`.
49 To properly start and stop the server, use `MockserverSession` as an async contextmanager:
52 async with pytest_userver.grpc.mockserver.MockserverSession(server=server) as mockserver:
56 @note `MockserverSession` is usually obtained from
57 @ref pytest_userver.plugins.grpc.mockserver.grpc_mockserver_session "grpc_mockserver_session".
43 def __init__(self, *, server: grpc.aio.Server, experimental: bool =
False) ->
None:
…
64 def _get_auto_service_mock(self, servicer_class: type, /) -> _ServiceMock:
68 new_mock = _create_servicer_mock(servicer_class)
71 new_mock.add_to_server(self.
_server)
74 def _set_asyncexc_append(self, asyncexc_append: Optional[AsyncExcAppend], /) ->
None:
77 mock.set_asyncexc_append(asyncexc_append)
81 @brief Removes all mocks for this mockserver that have been installed using
82 `MockserverSession` or @ref pytest_userver.grpc.Mockserver "Mockserver" API.
83 @note Mocks installed manually using @ref MockserverSession.server will not be removed, though.
88 @contextlib.contextmanager
91 Sets testsuite's `asyncexc_append` for use in the returned scope.
102 The underlying [grpc.aio.Server](https://grpc.github.io/grpc/python/grpc_asyncio.html#grpc.aio.Server).
109 @note Prefer starting mockserver using the async contextmanager syntax if possible.
115 Stops the server properly. Prefer this method to stopping `server` manually.
117 await _stop_server(self.
_server)
119 async def __aenter__(self) -> MockserverSession:
123 async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
129 Allows to install mocks that are reset between tests, see
130 @ref pytest_userver.plugins.grpc.mockserver.grpc_mockserver "grpc_mockserver".
133 def __init__(self, *, mockserver_session: MockserverSession, experimental: bool =
False) ->
None:
135 @warning This initializer is an **experimental API**, likely to break in the future. Consider using
136 @ref pytest_userver.plugins.grpc.mockserver.grpc_mockserver "grpc_mockserver" instead.
138 Initializes Mockserver.
140 @note `Mockserver` is usually obtained from
141 @ref pytest_userver.plugins.grpc.mockserver.grpc_mockserver "grpc_mockserver".
133 def __init__(self, *, mockserver_session: MockserverSession, experimental: bool =
False) ->
None:
…
146 def __call__(self, servicer_method, /) -> MockDecorator:
148 Returns a decorator to mock the specified gRPC service method implementation.
152 @snippet samples/grpc_service/testsuite/test_grpc.py Prepare modules
153 @snippet samples/grpc_service/testsuite/test_grpc.py grpc client test
155 servicer_class = _get_class_from_method(servicer_method)
157 return mock.install_handler(servicer_method.__name__)
146 def __call__(self, servicer_method, /) -> MockDecorator:
…
159 def mock_factory(self, servicer_class, /) -> Callable[[str], MockDecorator]:
161 Allows to create a fixture as a shorthand for mocking methods of the specified gRPC service.
165 @snippet grpc/functional_tests/metrics/tests/conftest.py Prepare modules
166 @snippet grpc/functional_tests/metrics/tests/conftest.py Prepare server mock
167 @snippet grpc/functional_tests/metrics/tests/test_metrics.py grpc client test
170 def factory(method_name):
171 method = getattr(servicer_class, method_name,
None)
173 raise ValueError(f
'No method "{method_name}" in servicer class "{servicer_class.__name__}"')
176 _check_is_servicer_class(servicer_class)
159 def mock_factory(self, servicer_class, /) -> Callable[[str], MockDecorator]:
…
179 def install_servicer(self, servicer: object, /) ->
None:
181 Installs as a mock `servicer`, the class of which should inherit from a generated `*Servicer` class.
183 For example, @ref grpc/functional_tests/basic_chaos/tests-grpcclient/service.py "this servicer class"
184 can be installed as follows:
186 @snippet grpc/functional_tests/basic_chaos/tests-grpcclient/conftest.py installing mockserver servicer
188 @note Inheritance from multiple `*Servicer` classes at once is allowed.
190 @example grpc/functional_tests/basic_chaos/tests-grpcclient/service.py
192 base_servicer_classes = [cls
for cls
in inspect.getmro(type(servicer))[1:]
if cls.__name__.endswith(
'Servicer')]
193 if not base_servicer_classes:
194 raise ValueError(f
"Given object's type ({type(servicer)}) is not inherited from any grpc *Servicer class")
195 for servicer_class
in base_servicer_classes:
198 for python_method_name
in mock.known_methods:
199 handler_func = getattr(servicer, python_method_name)
200 mock.install_handler(python_method_name)(handler_func)
206async def _stop_server(server: grpc.aio.Server, /) ->
None:
207 async def stop_server():
208 await server.stop(grace=
None)
209 await server.wait_for_termination()
211 stop_server_task = asyncio.shield(asyncio.create_task(stop_server()))
215 await stop_server_task
216 except asyncio.CancelledError:
217 await stop_server_task
222def _get_class_from_method(method) -> type:
224 assert inspect.isfunction(method), f
'Expected an unbound method: foo(ClassName.MethodName), got: {method}'
225 class_name = method.__qualname__.split(
'.<locals>', 1)[0].rsplit(
'.', 1)[0]
227 cls = getattr(inspect.getmodule(method), class_name)
228 except AttributeError:
229 cls = method.__globals__.get(class_name)
230 assert isinstance(cls, type)