userver: /data/code/userver/testsuite/pytest_plugins/pytest_userver/plugins/service.py Source File
Loading...
Searching...
No Matches
service.py
1"""
2Start the service in testsuite.
3"""
4
5# pylint: disable=redefined-outer-name
6from collections.abc import Awaitable
7from collections.abc import Callable
8from collections.abc import Iterable
9import logging
10import pathlib
11import time
12import typing
13from typing import Any
14
15import pytest
16
17from testsuite.utils import url_util
18
19from pytest_userver import fixture_markers
21from pytest_userver.utils import net
22
23logger = logging.getLogger(__name__)
24
25
26def pytest_addoption(parser) -> None:
27 group = parser.getgroup('userver')
28 group.addoption(
29 '--service-logs-file',
30 type=pathlib.Path,
31 help='Write service output to specified file',
32 )
33 group.addoption(
34 '--service-logs-pretty',
35 action='store_true',
36 help='Enable pretty print and colorize service logs',
37 )
38 group.addoption(
39 '--service-logs-pretty-verbose',
40 dest='service_logs_pretty',
41 action='store_const',
42 const='verbose',
43 help='Enable pretty print and colorize service logs in verbose mode',
44 )
45 group.addoption(
46 '--service-logs-pretty-disable',
47 action='store_false',
48 dest='service_logs_pretty',
49 help='Disable pretty print and colorize service logs',
50 )
51
52
53@pytest.fixture(scope='session')
54def service_env() -> dict[str, str]:
55 """
56 Override this to pass extra environment variables to the service.
57
58 @snippet samples/redis_service/testsuite/conftest.py service_env
59 @ingroup userver_testsuite_fixtures
60 """
61 return {}
62
63
64@pytest.fixture(scope='session')
65async def service_http_ping_url(service_config, service_baseurl) -> str | None:
66 """
67 Returns the service HTTP ping URL that is used by the testsuite to detect
68 that the service is ready to work. Returns None if there's no such URL.
69
70 By default, attempts to find server::handlers::Ping component by
71 "handler-ping" name in static config. Override this fixture to change the
72 behavior.
73
74 @ingroup userver_testsuite_fixtures
75 """
76 components = service_config['components_manager']['components']
77 ping_handler = components.get('handler-ping')
78 if ping_handler:
79 return url_util.join(service_baseurl, ping_handler['path'])
80 return None
81
82
83@pytest.fixture(scope='session')
84def service_non_http_health_checks( # pylint: disable=invalid-name
85 service_config,
86) -> net.HealthChecks:
87 """
88 Returns a health checks info.
89
90 By default, returns pytest_userver.utils.net.get_health_checks_info().
91
92 Override this fixture to change the way testsuite detects the tested
93 service being alive.
94
95 @ingroup userver_testsuite_fixtures
96 """
97
98 return net.get_health_checks_info(service_config)
99
100
101@pytest.fixture(scope='session')
103 """
104 Returns service start timeout in seconds.
105
106 Override this fixture to change the service start timeout.
107
108 @ingroup userver_testsuite_fixtures
109 """
110
111 return 100.0
112
113
114@pytest.fixture(scope='session')
116 """
117 If non-empty, defines a list of arguments starting with executable
118 that is used instead of `service_binary`. The final argument list consists of
119 `service_binary_launcher` plus the common service cmdline.
120
121 Can be used for:
122 - resource limiting (rlimit, cgroup)
123 - security limiting (capabilities, LSM)
124 - resource profiling (perf)
125 - tracing (strace, ltrace)
126
127 @see @ref pytest_userver.plugins.service.service_daemon_instance "service_daemon_instance"
128 @ingroup userver_testsuite_fixtures
129 """
130 return []
131
132
133@pytest.fixture(scope='session')
135 service_http_ping_url,
136 service_non_http_health_checks,
137) -> Callable[..., Awaitable[bool]] | None:
138 """
139 Returns the health check function used by
140 @ref pytest_userver.plugins.service.service_daemon_scope "service_daemon_scope"
141 to detect that the service has started and is ready to accept requests.
142
143 Returns None when service_http_ping_url is set, in which case
144 create_daemon_scope uses the ping URL directly. Otherwise returns a checker
145 based on the service_non_http_health_checks info.
146
147 Override this fixture to change the way the service readiness is detected.
148
149 @ingroup userver_testsuite_fixtures
150 """
151 assert service_http_ping_url or service_non_http_health_checks.tcp, (
152 '"service_http_ping_url" and "create_health_checker" fixtures '
153 'returned None. Testsuite is unable to detect if the service is ready '
154 'to accept requests.',
155 )
156
157 if service_http_ping_url:
158 return None
159
160 logger.debug(
161 'userver fixture "service_health_check" would check for "%s"',
162 service_non_http_health_checks,
163 )
164
165 class LocalCounters:
166 last_log_time = 0.0
167 attempts = 0
168
169 async def _checker(*, session, process) -> bool:
170 LocalCounters.attempts += 1
171 new_log_time = time.monotonic()
172 if new_log_time - LocalCounters.last_log_time > 1.0:
173 LocalCounters.last_log_time = new_log_time
174 logger.debug(
175 'userver fixture "service_health_check" checking "%s", attempt %s',
176 service_non_http_health_checks,
177 LocalCounters.attempts,
178 )
179
180 return await net.check_availability(service_non_http_health_checks)
181
182 return _checker
183
184
185@pytest.fixture(scope='session')
187 create_daemon_scope,
188 daemon_scoped_mark,
189 service_env,
190 service_http_ping_url,
191 service_config_path_temp,
192 service_binary,
193 service_binary_launcher,
194 service_health_check,
195 service_start_timeout,
196):
197 """
198 Prepares the start of the service daemon.
199 Configures the health checking via the service_health_check fixture.
200
201 @see @ref pytest_userver.plugins.service.service_daemon_instance "service_daemon_instance"
202 @ingroup userver_testsuite_fixtures
203 """
204 # In yandex-taxi-testsuite, each poll retry duration is 0.05 seconds.
205 poll_retries = int(service_start_timeout / 0.05)
206
207 async with create_daemon_scope(
208 args=service_binary_launcher + [str(service_binary), '--config', str(service_config_path_temp)],
209 ping_url=service_http_ping_url,
210 health_check=service_health_check,
211 env=service_env,
212 poll_retries=poll_retries,
213 ) as scope:
214 yield scope
215
216
217@pytest.fixture
218def extra_client_deps() -> None:
219 """
220 Legacy service client dependencies hook.
221
222 Prefer marking fixtures with
223 @ref pytest_userver.service.dependency "pytest_userver.service.dependency"
224 instead of overriding this fixture.
225
226 Example of the legacy override:
227
228 @code
229 @pytest.fixture
230 def extra_client_deps(some_fixtures_to_wait_before_service_start):
231 pass
232 @endcode
233
234 @ingroup userver_testsuite_fixtures
235 """
236
237
238@pytest.fixture
239def _mark_service_deps(request: pytest.FixtureRequest) -> None:
240 infos = fixture_markers.get_infos(request, pytest_userver.service._ServiceDependencyInfo)
241 for fixture_name in infos:
242 request.getfixturevalue(fixture_name)
243
244
245@pytest.fixture
246def auto_client_deps(request) -> None:
247 """
248 Ensures that the following fixtures, if available, are run before service start:
249
250 * `pgsql`
251 * `mongodb`
252 * `clickhouse`
253 * `rabbitmq`
254 * kafka (`kafka_producer`, `kafka_consumer`)
255 * `redis_store`
256 * `mysql`
257 * @ref pytest_userver.plugins.scylla.scylla "scylla"
258
259 To add other dependencies prefer
260 @ref pytest_userver.service.dependency "dependency".
261 Overriding
262 @ref pytest_userver.plugins.service.extra_client_deps "extra_client_deps"
263 is a legacy alternative.
264
265 @ingroup userver_testsuite_fixtures
266 """
267 known_deps = {
268 'pgsql',
269 'mongodb',
270 'clickhouse',
271 'rabbitmq',
272 'kafka_producer',
273 'kafka_consumer',
274 'redis_store',
275 'mysql',
276 'scylla',
277 }
278
279 try:
280 fixture_lookup_error = pytest.FixtureLookupError
281 except AttributeError:
282 # support for an older version of the pytest
283 import _pytest.fixtures
284
285 fixture_lookup_error = _pytest.fixtures.FixtureLookupError
286
287 resolved_deps = []
288 for dep in known_deps:
289 try:
290 request.getfixturevalue(dep)
291 resolved_deps.append(dep)
292 except fixture_lookup_error:
293 pass
294
295 logger.debug(
296 'userver fixture "auto_client_deps" resolved dependencies %s',
297 resolved_deps,
298 )
299
300
301@pytest.fixture
303 testpoint,
304 cleanup_userver_dumps,
305 userver_log_capture,
306 dynamic_config,
307 mock_configs_service,
308):
309 """
310 Service client dependencies hook, like
311 @ref pytest_userver.plugins.service.extra_client_deps "extra_client_deps".
312
313 Feel free to override globally in a more specific pytest plugin
314 (one that comes after userver plugins),
315 but make sure to depend on the original fixture:
316
317 @code
318 @pytest.fixture(name='builtin_client_deps')
319 def _builtin_client_deps(builtin_client_deps, some_extra_fixtures):
320 pass
321 @endcode
322
323 @ingroup userver_testsuite_fixtures
324 """
325
326
327@pytest.fixture
329 ensure_daemon_started,
330 service_daemon_scope,
331 # Lists of various fixtures required for the service to start. Fixtures are requested top-to-bottom.
332 # Lower fixtures can indirectly use the environment setup by the upper fixtures (although not recommended).
333 # {
334 builtin_client_deps,
335 auto_client_deps,
336 _mark_service_deps,
337 extra_client_deps,
338 # }
339):
340 """
341 Calls `ensure_daemon_started` on
342 @ref pytest_userver.plugins.service.service_daemon_scope "service_daemon_scope"
343 to actually start the service. Makes sure that all the dependencies are prepared
344 before the service starts.
345
346 Requests service dependency fixtures from the following groups:
347 * @ref pytest_userver.plugins.service.builtin_client_deps "builtin_client_deps"
348 * @ref pytest_userver.plugins.service.auto_client_deps "auto_client_deps"
349 * fixtures marked with @ref pytest_userver.service.dependency "dependency"
350 * @ref pytest_userver.plugins.service.extra_client_deps "extra_client_deps"
351
352 @ingroup userver_testsuite_fixtures
353 """
354 # TODO also run userver_client_cleanup here
355 return await ensure_daemon_started(service_daemon_scope)
356
357
358@pytest.fixture(scope='session')
359def daemon_scoped_mark(request) -> dict[str, Any] | None:
360 """
361 Depend on this fixture directly or transitively to make your fixture a per-daemon fixture.
362
363 Example:
364
365 @code
366 @pytest.fixture(scope='session')
367 def users_cache_state(daemon_scoped_mark, ...):
368 return UsersCacheState(users_list=[])
369 @endcode
370
371 For tests marked with `@pytest.mark.uservice_oneshot(...)`, the service will be restarted,
372 and all the per-daemon fixtures will be recreated.
373
374 This fixture returns kwargs passed to the `uservice_oneshot` mark (which may be an empty dict).
375 For normal tests, this fixture returns `None`.
376
377 @ingroup userver_testsuite_fixtures
378 """
379 # === How daemon-scoped fixtures work ===
380 # pytest always keeps no more than 1 instance of each parametrized fixture.
381 # When a parametrized fixture is requested, FixtureDef checks using __eq__ whether the current value
382 # of fixture param equals the cached value. If they differ, then the fixture and all the dependent fixtures
383 # are torn down (in reverse-dependency order), then the fixture is set up again.
384 # TLDR: when the param changes, the whole tree of daemon-specific fixtures is torn down.
385 return getattr(request, 'param', None)
386
387
388# @cond
389
390
391def pytest_configure(config):
392 config.addinivalue_line(
393 'markers',
394 'uservice_oneshot: use a per-test service daemon instance',
395 )
396
397
398def _contains_oneshot_marker(parametrize: Iterable[pytest.Mark]) -> bool:
399 """
400 Check if at least one of 'parametrize' marks is of the form:
401
402 @pytest.mark.parametrize(
403 "foo, bar",
404 [
405 ("a", 10),
406 pytest.param("b", 20, marks=pytest.mark.uservice_oneshot), # <====
407 ]
408 )
409 """
410 return any(
411 True
412 for parametrize_mark in parametrize
413 if len(parametrize_mark.args) >= 2
414 for parameter_set in parametrize_mark.args[1]
415 if hasattr(parameter_set, 'marks')
416 for mark in parameter_set.marks
417 if mark.name == 'uservice_oneshot'
418 )
419
420
421def pytest_generate_tests(metafunc: pytest.Metafunc) -> None:
422 oneshot_marker = metafunc.definition.get_closest_marker('uservice_oneshot')
423 parametrize_markers = metafunc.definition.iter_markers('parametrize')
424 if oneshot_marker is not None or _contains_oneshot_marker(parametrize_markers):
425 # Set a dummy parameter value. Actual param is patched in pytest_collection_modifyitems.
426 metafunc.parametrize(
427 (daemon_scoped_mark.__name__,),
428 [(None,)],
429 indirect=True,
430 # TODO use pytest.HIDDEN_PARAM after it becomes available
431 # https://github.com/pytest-dev/pytest/issues/13228
432 ids=['uservice_oneshot'],
433 scope='function',
434 )
435
436
437# TODO use dependent parametrize instead of patching param value after it becomes available
438# https://github.com/pytest-dev/pytest/issues/13233
439def pytest_collection_modifyitems(items: list[pytest.Item]):
440 for item in items:
441 oneshot_marker = item.get_closest_marker('uservice_oneshot')
442 if oneshot_marker and isinstance(item, pytest.Function):
443 func_item = typing.cast(pytest.Function, item)
444 func_item.callspec.params[daemon_scoped_mark.__name__] = dict(oneshot_marker.kwargs, function=func_item)
445
446
447# @endcond