userver: /data/code/userver/testsuite/pytest_plugins/pytest_userver/plugins/grpc/mockserver.py Source File
Loading...
Searching...
No Matches
mockserver.py
1"""
2Mocks for the gRPC servers.
3
4@sa @ref scripts/docs/en/userver/tutorial/grpc_service.md
5"""
6
7from collections.abc import AsyncIterator
8from collections.abc import Iterator
9
10import grpc
11import pytest
12
16
17# @cond
18
19
20DEFAULT_PORT = 8091
21
22
23# @endcond
24
25
26@pytest.fixture(scope='session')
27def grpc_mockserver_endpoint(pytestconfig, get_free_port) -> str:
28 """
29 Returns the gRPC endpoint to start the mocking server that is set by
30 command line `--grpc-mockserver-host` and `--grpc-mockserver-port` options.
31
32 For port 0, picks some free port.
33
34 Override this fixture to customize the endpoint used by gRPC mockserver.
35
36 @snippet grpc/functional_tests/basic_chaos/tests-grpcclient/conftest.py grpc_mockserver_endpoint example
37 @ingroup userver_testsuite_fixtures
38 """
39 port = pytestconfig.option.grpc_mockserver_port
40 if pytestconfig.option.service_wait or pytestconfig.option.service_disable:
41 port = port or DEFAULT_PORT
42 if port == 0:
43 port = get_free_port()
44 return f'{pytestconfig.option.grpc_mockserver_host}:{port}'
45
46
47@pytest.fixture(scope='session')
48async def grpc_mockserver_session(grpc_mockserver_endpoint) -> AsyncIterator[pytest_userver.grpc.MockserverSession]:
49 """
50 Returns the gRPC mocking server.
51
52 @warning This is a sharp knife, use with caution! For most use-cases, prefer
53 @ref pytest_userver.plugins.grpc.mockserver.grpc_mockserver "grpc_mockserver" instead.
54
55 @ingroup userver_testsuite_fixtures
56 """
57 server = grpc.aio.server(options=[('grpc.http2.max_ping_strikes', 0)])
58 server.add_insecure_port(grpc_mockserver_endpoint)
59
60 async with pytest_userver.grpc.MockserverSession(server=server, experimental=True) as mockserver:
61 yield mockserver
62
63
64@pytest.fixture
65@pytest_userver.service.dependency
66def grpc_mockserver(grpc_mockserver_session, asyncexc_append) -> Iterator[pytest_userver.grpc.Mockserver]:
67 """
68 Returns the gRPC mocking server.
69 In order for gRPC clients in your service to work, mock handlers need to be installed for them using this fixture.
70
71 Example:
72
73 @snippet samples/grpc_service/testsuite/test_grpc.py Prepare modules
74 @snippet samples/grpc_service/testsuite/test_grpc.py grpc client test
75
76 Alternatively, you can create a shorthand for mocking frequently-used services:
77
78 @snippet grpc/functional_tests/metrics/tests/conftest.py Prepare modules
79 @snippet grpc/functional_tests/metrics/tests/conftest.py Prepare server mock
80 @snippet grpc/functional_tests/metrics/tests/test_metrics.py grpc client test
81
82 Mocks are only active within tests after their respective handler functions are created, not between tests.
83 If the service needs the mock during startup, decorate the fixture that defines your mock with
84 @ref pytest_userver.service.dependency "dependency".
85
86 To return an error status instead of response, use `context` (see
87 [ServicerContext](https://grpc.github.io/grpc/python/grpc_asyncio.html#grpc.aio.ServicerContext)
88 docs):
89
90 @snippet grpc/functional_tests/middleware_client/tests/test_error_status.py Mocked error status
91
92 To trigger special exceptions in the service's gRPC client, raise these mocked errors from the mock handler:
93
94 * @ref pytest_userver.grpc._mocked_errors.TimeoutError "pytest_userver.grpc.TimeoutError"
95 * @ref pytest_userver.grpc._mocked_errors.NetworkError "pytest_userver.grpc.NetworkError"
96
97 @ingroup userver_testsuite_fixtures
98 """
99 with grpc_mockserver_session.asyncexc_append_scope(asyncexc_append):
101 mockserver_session=grpc_mockserver_session,
102 experimental=True,
103 ) as mockserver:
104 yield mockserver
105
106
107@pytest.fixture(scope='session')
108@pytest_userver.config.patch
110 """
111 Returns a function that adjusts the static config for testsuite.
112 Finds `grpc-client-middleware-pipeline` in config_yaml and
113 enables `grpc-client-middleware-testsuite`.
114
115 @ingroup userver_testsuite_fixtures
116 """
117
118 def get_dict_field(parent: dict, field_name: str) -> dict:
119 if parent.setdefault(field_name, {}) is None:
120 parent[field_name] = {}
121
122 return parent[field_name]
123
124 def patch_config(config_yaml, _config_vars):
125 components = config_yaml['components_manager']['components']
126 if components.get('grpc-client-common', None) is not None:
127 client_middlewares_pipeline = get_dict_field(components, 'grpc-client-middlewares-pipeline')
128 middlewares = get_dict_field(client_middlewares_pipeline, 'middlewares')
129 testsuite_middleware = get_dict_field(middlewares, 'grpc-client-middleware-testsuite')
130 testsuite_middleware['enabled'] = True
131
132 return patch_config
133
134
135# @cond
136
137
138def pytest_addoption(parser):
139 group = parser.getgroup('grpc-mockserver')
140 group.addoption(
141 '--grpc-mockserver-host',
142 default='[::]',
143 help='gRPC mockserver hostname, default is [::]',
144 )
145 group.addoption(
146 '--grpc-mockserver-port',
147 type=int,
148 default=0,
149 help='gRPC mockserver port, by default random port is used',
150 )
151
152
153# @endcond