userver: /data/code/userver/testsuite/pytest_plugins/pytest_userver/plugins/config.py Source File
Loading...
Searching...
No Matches
config.py
1"""
2Work with the configuration files of the service in testsuite.
3"""
4
5# pylint: disable=redefined-outer-name
6import copy
7import dataclasses
8import itertools
9import logging
10import os
11import pathlib
12import string
13import subprocess
14import types
15from collections.abc import Callable
16from collections.abc import Mapping
17from typing import Any
18from typing import TypeAlias
19
20import pytest
21import yaml
22
24from pytest_userver import fixture_markers
25
26# flake8: noqa E266
27
43USERVER_CONFIG_HOOKS = []
44
45ServiceConfigPatch: TypeAlias = Callable[[dict, dict], None]
46
47
48# @cond
49
50
51logger = logging.getLogger(__name__)
52
53
54class _UserverConfigPlugin:
55 def __init__(self):
56 self._config_hooks = []
57
58 @property
59 def userver_config_hooks(self):
60 return self._config_hooks
61
62 def pytest_plugin_registered(self, plugin, manager):
63 if not isinstance(plugin, types.ModuleType):
64 return
65 uhooks = getattr(plugin, 'USERVER_CONFIG_HOOKS', None)
66 if uhooks is not None:
67 self._config_hooks.extend(uhooks)
68
69
70@dataclasses.dataclass(frozen=True)
71class _UserverConfig:
72 config_yaml: dict
73 config_vars: dict
74
75
76def pytest_configure(config):
77 config.pluginmanager.register(_UserverConfigPlugin(), 'userver_config')
78
79
80def pytest_addoption(parser) -> None:
81 group = parser.getgroup('userver-config')
82 group.addoption(
83 '--service-log-level',
84 type=str.lower,
85 choices=['trace', 'debug', 'info', 'warning', 'error', 'critical'],
86 )
87 group.addoption(
88 '--service-config',
89 type=pathlib.Path,
90 help='Path to service.yaml file.',
91 )
92 group.addoption(
93 '--service-config-vars',
94 type=pathlib.Path,
95 help='Path to config_vars.yaml file.',
96 )
97 group.addoption(
98 '--service-secdist',
99 type=pathlib.Path,
100 help='Path to secure_data.json file.',
101 )
102 group.addoption(
103 '--config-fallback',
104 type=pathlib.Path,
105 help='Path to dynamic config fallback file.',
106 )
107 group.addoption(
108 '--dump-config',
109 action='store_true',
110 help='Dump config from binary before running tests',
111 )
112
113
114# @endcond
115
116
117@pytest.fixture(scope='session')
118def service_config_path(pytestconfig, service_binary) -> pathlib.Path:
119 """
120 Returns the path to service.yaml file set by command line
121 `--service-config` option.
122
123 Override this fixture to change the way path to the static config is provided.
124
125 @ingroup userver_testsuite_fixtures
126 """
127 if pytestconfig.option.dump_config:
128 subprocess.run([
129 service_binary,
130 '--dump-config',
131 pytestconfig.option.service_config,
132 ])
133 return pytestconfig.option.service_config
134
135
136@pytest.fixture(scope='session')
137def db_dump_schema_path(service_binary, service_tmpdir) -> pathlib.Path:
138 """
139 Runs the service binary with `--dump-db-schema` argument, dumps the 0_db_schema.sql file with database schema and
140 returns path to it.
141
142 Override this fixture to change the way to dump the database schema.
143
144 @ingroup userver_testsuite_fixtures
145
146 """
147 path = service_tmpdir.joinpath('schemas')
148 os.mkdir(path)
149 subprocess.run([
150 service_binary,
151 '--dump-db-schema',
152 path / '0_db_schema.sql',
153 ])
154 return path
155
156
157@pytest.fixture(scope='session')
158def service_config_vars_path(pytestconfig) -> pathlib.Path | None:
159 """
160 Returns the path to config_vars.yaml file set by command line
161 `--service-config-vars` option.
162
163 Override this fixture to change the way path to config_vars.yaml is
164 provided.
165
166 @ingroup userver_testsuite_fixtures
167 """
168 return pytestconfig.option.service_config_vars
169
170
171@pytest.fixture(scope='session')
172def service_secdist_path(pytestconfig) -> pathlib.Path | None:
173 """
174 Returns the path to secure_data.json file set by command line
175 `--service-secdist` option.
176
177 Override this fixture to change the way path to secure_data.json is
178 provided.
179
180 @ingroup userver_testsuite_fixtures
181 """
182 return pytestconfig.option.service_secdist
183
184
185@pytest.fixture(scope='session')
186def config_fallback_path(pytestconfig) -> pathlib.Path:
187 """
188 Returns the path to dynamic config fallback file set by command line
189 `--config-fallback` option.
190
191 Override this fixture to change the way path to dynamic config fallback is
192 provided.
193
194 @ingroup userver_testsuite_fixtures
195 """
196 return pytestconfig.option.config_fallback
197
198
199@pytest.fixture(scope='session')
200def service_tmpdir(service_binary, tmp_path_factory):
201 """
202 Returns the path for temporary files. The path is the same for the whole
203 session and files are not removed (at least by this fixture) between
204 tests.
205
206 @ingroup userver_testsuite_fixtures
207 """
208 return tmp_path_factory.mktemp(
209 pathlib.Path(service_binary).name,
210 numbered=False,
211 )
212
213
214@pytest.fixture(scope='session')
216 service_tmpdir,
217 service_config,
218 service_config_yaml,
219 service_config_vars,
220) -> pathlib.Path:
221 """
222 Dumps the contents of the service_config_yaml and service_config_vars into a static config for
223 testsuite and returns the path to the config file.
224
225 @ingroup userver_testsuite_fixtures
226 """
227 dst_path = service_tmpdir / 'config.yaml'
228
229 service_config_yaml = dict(service_config_yaml)
230 if not service_config_vars:
231 service_config_yaml.pop('config_vars', None)
232 else:
233 config_vars_path = service_tmpdir / 'config_vars.yaml'
234 config_vars_text = yaml.dump(service_config_vars)
235 logger.debug(
236 'userver fixture "service_config_path_temp" writes the patched static config vars to "%s":\n%s',
237 config_vars_path,
238 config_vars_text,
239 )
240 config_vars_path.write_text(config_vars_text)
241 service_config_yaml['config_vars'] = str(config_vars_path)
242
243 logger.debug(
244 'userver fixture "service_config_path_temp" writes the patched static config to "%s" equivalent to:\n%s',
245 dst_path,
246 yaml.dump(service_config),
247 )
248 dst_path.write_text(yaml.dump(service_config_yaml))
249
250 return dst_path
251
252
253@pytest.fixture(scope='session')
254def service_config_yaml(_service_config_hooked) -> dict:
255 """
256 Returns the static config values after config patches were applied
257 (@ref pytest_userver.config.patch "config.patch" and legacy
258 USERVER_CONFIG_HOOKS). Prefer using
259 pytest_userver.plugins.config.service_config
260
261 @ingroup userver_testsuite_fixtures
262 """
263 return _service_config_hooked.config_yaml
264
265
266@pytest.fixture(scope='session')
267def service_config_vars(_service_config_hooked) -> dict:
268 """
269 Returns the static config variables (config_vars.yaml) values after config
270 patches were applied (@ref pytest_userver.config.patch "config.patch" and
271 legacy USERVER_CONFIG_HOOKS). Prefer using
272 pytest_userver.plugins.config.service_config
273
274 @ingroup userver_testsuite_fixtures
275 """
276 return _service_config_hooked.config_vars
277
278
279def _substitute_values(config, service_config_vars: dict, service_env) -> None:
280 if isinstance(config, dict):
281 for key, value in config.items():
282 if not isinstance(value, str):
283 _substitute_values(value, service_config_vars, service_env)
284 continue
285
286 if not value.startswith('$'):
287 continue
288
289 new_value = service_config_vars.get(value[1:])
290 if new_value is not None:
291 config[key] = new_value
292 continue
293
294 env = config.get(f'{key}#env')
295 if env:
296 if service_env:
297 new_value = service_env.get(env)
298 if not new_value:
299 new_value = os.environ.get(env)
300 if new_value:
301 config[key] = new_value
302 continue
303
304 fallback = config.get(f'{key}#fallback')
305 if fallback:
306 config[key] = fallback
307 continue
308
309 config[key] = None
310
311 if isinstance(config, list):
312 for i, value in enumerate(config):
313 if not isinstance(value, str):
314 _substitute_values(value, service_config_vars, service_env)
315 continue
316
317 if not value.startswith('$'):
318 continue
319
320 new_value = service_config_vars.get(value[1:])
321 if new_value is not None:
322 config[i] = new_value
323
324
325@pytest.fixture(scope='session')
326def substitute_config_vars(service_env) -> Callable[[Any, dict], Any]:
327 """
328 A function that takes `config_yaml`, `config_vars` and applies all
329 substitutions just like the service would.
330
331 Useful when patching the service config. It's a good idea to pass
332 a component's config instead of the whole `config_yaml` to avoid
333 unnecessary work.
334
335 @warning The returned YAML is a clone, mutating it will not modify
336 the actual config while in a config hook!
337
338 @ingroup userver_testsuite_fixtures
339 """
340
341 def substitute(config_yaml, config_vars, /):
342 if config_yaml is not None and not isinstance(config_yaml, dict) and not isinstance(config_yaml, list):
343 raise TypeError(
344 f'{substitute_config_vars.__name__} can only be meaningfully '
345 'called with dict and list nodes of config_yaml, while given: '
346 f'{config_yaml!r}. Pass a containing object instead.',
347 )
348
349 config = copy.deepcopy(config_yaml)
350 _substitute_values(config, config_vars, service_env)
351 return config
352
353 return substitute
354
355
356@pytest.fixture(scope='session')
358 service_config_yaml,
359 service_config_vars,
360 substitute_config_vars,
361) -> dict:
362 """
363 Returns the static config values after config patches were applied
364 (@ref pytest_userver.config.patch "config.patch" and legacy
365 USERVER_CONFIG_HOOKS) and with all the '$', environment and fallback
366 variables substituted.
367
368 @ingroup userver_testsuite_fixtures
369 """
370 config = substitute_config_vars(service_config_yaml, service_config_vars)
371 config.pop('config_vars', None)
372 return config
373
374
375@pytest.fixture(scope='session')
376def _original_service_config(
377 service_config_path,
378 service_config_vars_path,
379) -> _UserverConfig:
380 config_vars: dict
381 config_yaml: dict
382
383 assert service_config_path is not None, 'Please specify proper path to the static config file, not None'
384
385 with open(service_config_path, mode='rt') as fp:
386 config_yaml = yaml.safe_load(fp)
387
388 if service_config_vars_path:
389 with open(service_config_vars_path, mode='rt') as fp:
390 config_vars = yaml.safe_load(fp)
391 else:
392 config_vars = {}
393
394 return _UserverConfig(config_yaml=config_yaml, config_vars=config_vars)
395
396
397@pytest.fixture(scope='session')
398def _service_config_hooked(
399 daemon_scoped_mark,
400 pytestconfig,
401 request,
402 _original_service_config,
403) -> _UserverConfig:
404 config_yaml = copy.deepcopy(_original_service_config.config_yaml)
405 config_vars = copy.deepcopy(_original_service_config.config_vars)
406
407 plugin_hooks = pytestconfig.pluginmanager.get_plugin('userver_config').userver_config_hooks
408 mark_hooks = fixture_markers.get_infos(request, pytest_userver.config._ConfigPatchInfo).keys()
409 local_hooks = (daemon_scoped_mark or {}).get('config_hooks', ())
410
411 for hook in itertools.chain(plugin_hooks, mark_hooks, local_hooks):
412 if not callable(hook):
413 hook_func = request.getfixturevalue(hook)
414 else:
415 hook_func = hook
416 hook_func(config_yaml, config_vars)
417
418 return _UserverConfig(config_yaml=config_yaml, config_vars=config_vars)
419
420
421@pytest.fixture(scope='session')
422def _service_config_substitution_vars(request, mockserver_info) -> Mapping[str, str]:
423 substitution_vars = {
424 'mockserver': mockserver_info.base_url.removesuffix('/'),
425 }
426 if request.config.pluginmanager.hasplugin('pytest_userver.plugins.grpc.mockserver'):
427 grpc_mockserver_endpoint = request.getfixturevalue('grpc_mockserver_endpoint')
428 substitution_vars['grpc_mockserver'] = grpc_mockserver_endpoint
429 return substitution_vars
430
431
432@pytest.fixture(scope='session')
433@pytest_userver.config.patch
434def userver_config_substitutions(_service_config_substitution_vars) -> ServiceConfigPatch:
435 """
436 Replaces substitution vars in all strings within `config_vars` using
437 [string.Template.substitute](https://docs.python.org/3/library/string.html#string.Template.substitute).
438
439 Substitution vars can be used as a shorthand for writing a full-fledged @ref SERVICE_CONFIG_HOOKS "config hook"
440 in many common cases.
441
442 Unlike normal `config_vars`, substitution vars can also apply to a part of a string.
443 For example, for `config_vars` entry
444
445 @code{.yaml}
446 frobnicator-url: $mockserver/frobnicator
447 @endcode
448
449 a possible patching result is as follows:
450
451 @code{.yaml}
452 frobnicator-url: http://127.0.0.1:1234/frobnicator
453 @endcode
454
455 Currently, the following substitution vars are supported:
456
457 * `mockserver` - mockserver url
458 * `grpc_mockserver` - grpc mockserver endpoint
459
460 @ingroup userver_testsuite_fixtures
461 """
462
463 def _substitute(key, value, parent: list | dict) -> None:
464 if isinstance(value, str):
465 parent[key] = string.Template(value).safe_substitute(_service_config_substitution_vars)
466 elif isinstance(value, dict):
467 for child_key, child_value in value.items():
468 _substitute(child_key, child_value, value)
469 elif isinstance(value, list):
470 for child_key, child_value in enumerate(value):
471 _substitute(child_key, child_value, value)
472
473 def patch_config(config_yaml, config_vars):
474 for key, value in config_vars.items():
475 _substitute(key, value, config_vars)
476
477 return patch_config
478
479
480@pytest.fixture(scope='session')
481@pytest_userver.config.patch
482def userver_config_http_server(service_port, monitor_port, choose_free_port) -> ServiceConfigPatch:
483 """
484 Returns a function that adjusts the static configuration file for testsuite.
485 Sets the `server.listener.port` to listen on
486 @ref pytest_userver.plugins.base.service_port "service_port" fixture value;
487 sets the `server.listener-monitor.port` to listen on
488 @ref pytest_userver.plugins.base.monitor_port "monitor_port"
489 fixture value.
490
491 @ingroup userver_testsuite_fixtures
492 """
493
494 def _patch_config(config_yaml, config_vars):
495 components = config_yaml['components_manager']['components']
496 if server := components.get('server'):
497 for listener_name, new_port in [('listener', service_port), ('listener-monitor', monitor_port)]:
498 if listener := server.get(listener_name):
499 ports = listener.get('ports')
500 if ports and 'port' in ports[0]:
501 ports[0]['port'] = new_port
502 for entry in ports[1:]:
503 if 'port' in entry and 'unix-socket' not in entry and 'listen-socket-fd' not in entry:
504 port_hint = entry['port']
505 if isinstance(port_hint, str) and port_hint.startswith('$'):
506 port_hint = config_vars.get(port_hint[1:]) or entry.get('port#fallback')
507 entry['port'] = choose_free_port(port_hint)
508 else:
509 listener['port'] = new_port
510
511 return _patch_config
512
513
514@pytest.fixture(scope='session')
515def allowed_url_prefixes_extra() -> list[str]:
516 """
517 By default, userver HTTP client is only allowed to talk to mockserver
518 when running in testsuite. This makes tests repeatable and encapsulated.
519
520 Override this fixture to whitelist some additional URLs.
521 It is still strongly advised to only talk to localhost in tests.
522
523 @ingroup userver_testsuite_fixtures
524 """
525 return []
526
527
528@pytest.fixture(scope='session')
530 mockserver_info,
531 mockserver_ssl_info,
532 allowed_url_prefixes_extra,
533) -> list[str]:
534 """
535 Returns final list of allowed urls prefixes when running in testsuite.
536
537 For most of cases you DO NOT want to override this fixture. Use "allowed_url_prefixes_extra" instead.
538
539 @ingroup userver_testsuite_fixtures
540 """
541 allowed_urls: list[str] = [mockserver_info.base_url]
542
543 if mockserver_ssl_info:
544 allowed_urls.append(mockserver_ssl_info.base_url)
545
546 allowed_urls += allowed_url_prefixes_extra
547
548 # Add WebSocket prefixes (ws:// and wss://) alongside HTTP prefixes
549 allowed_urls.append(mockserver_info.ws_url('/'))
550 if mockserver_ssl_info:
551 allowed_urls.append(mockserver_ssl_info.ws_url('/'))
552
553 return allowed_urls
554
555
556@pytest.fixture(scope='session')
557@pytest_userver.config.patch
559 allowed_url_prefixes,
560) -> ServiceConfigPatch:
561 """
562 Returns a function that adjusts the static configuration file for testsuite.
563 Sets increased timeout and limits allowed URLs for `http-client-core` component.
564
565 @ingroup userver_testsuite_fixtures
566 """
567
568 def patch_config(config, config_vars) -> None:
569 components: dict = config['components_manager']['components']
570 if not {'http-client-core', 'testsuite-support'}.issubset(
571 components.keys(),
572 ):
573 return
574 if components['http-client-core'] is None:
575 components['http-client-core'] = {}
576 http_client_core = components['http-client-core']
577 http_client_core['testsuite-enabled'] = True
578 http_client_core['testsuite-timeout'] = '10s'
579
580 http_client_core['testsuite-allowed-url-prefixes'] = allowed_url_prefixes
581
582 return patch_config
583
584
585@pytest.fixture(scope='session')
587 """
588 Default log level to use in userver if no command line option was provided.
589
590 Returns 'debug'.
591
592 @ingroup userver_testsuite_fixtures
593 """
594 return 'debug'
595
596
597@pytest.fixture(scope='session')
598def userver_log_level(pytestconfig, userver_default_log_level) -> str:
599 """
600 Returns --service-log-level value if provided, otherwise returns
601 userver_default_log_level() value from fixture.
602
603 @ingroup userver_testsuite_fixtures
604 """
605 if pytestconfig.option.service_log_level:
606 return pytestconfig.option.service_log_level
607 return userver_default_log_level
608
609
610@pytest.fixture(scope='session')
611@pytest_userver.config.patch
612def userver_config_logging(userver_log_level, _service_logfile_path) -> ServiceConfigPatch:
613 """
614 Returns a function that adjusts the static configuration file for testsuite.
615 Sets the `logging.loggers.default` to log to `@stderr` with level set
616 from `--service-log-level` pytest configuration option.
617
618 @ingroup userver_testsuite_fixtures
619 """
620
621 if _service_logfile_path:
622 default_file_path = str(_service_logfile_path)
623 else:
624 default_file_path = '@stderr'
625
626 def _patch_config(config_yaml, config_vars):
627 components = config_yaml['components_manager']['components']
628 if 'logging' in components:
629 loggers = components['logging'].setdefault('loggers', {})
630 for logger in loggers.values():
631 logger['file_path'] = '@null'
632 loggers['default'] = {
633 'file_path': default_file_path,
634 'level': userver_log_level,
635 'overflow_behavior': 'discard',
636 }
637 config_vars['logger_level'] = userver_log_level
638
639 return _patch_config
640
641
642@pytest.fixture(scope='session')
643@pytest_userver.config.patch
644def userver_config_logging_otlp() -> ServiceConfigPatch:
645 """
646 Returns a function that adjusts the static configuration file for testsuite.
647 Sets the `otlp-logger.load-enabled` to `false` to disable OTLP logging and
648 leave the default file logger.
649
650 @ingroup userver_testsuite_fixtures
651 """
652
653 def _patch_config(config_yaml, config_vars):
654 components = config_yaml['components_manager']['components']
655 if 'otlp-logger' in components:
656 components['otlp-logger']['load-enabled'] = False
657
658 return _patch_config
659
660
661@pytest.fixture(scope='session')
662@pytest_userver.config.patch
663def userver_config_testsuite(pytestconfig, mockserver_info) -> ServiceConfigPatch:
664 """
665 Returns a function that adjusts the static configuration file for testsuite.
666
667 Sets up `testsuite-support` component, which:
668
669 - increases timeouts for userver drivers
670 - disables periodic cache updates
671 - enables testsuite tasks
672
673 Sets the `testsuite-enabled` in config_vars.yaml to `True`; sets the
674 `tests-control.testpoint-url` to mockserver URL.
675
676 @ingroup userver_testsuite_fixtures
677 """
678
679 def _set_postgresql_options(testsuite_support: dict) -> None:
680 testsuite_support['testsuite-pg-execute-timeout'] = '35s'
681 testsuite_support['testsuite-pg-statement-timeout'] = '30s'
682 testsuite_support['testsuite-pg-readonly-master-expected'] = True
683
684 def _set_redis_timeout(testsuite_support: dict) -> None:
685 testsuite_support['testsuite-redis-timeout-connect'] = '40s'
686 testsuite_support['testsuite-redis-timeout-single'] = '30s'
687 testsuite_support['testsuite-redis-timeout-all'] = '30s'
688
689 def _disable_cache_periodic_update(testsuite_support: dict) -> None:
690 testsuite_support['testsuite-periodic-update-enabled'] = False
691
692 def patch_config(config, config_vars) -> None:
693 # Don't delay tests teardown unnecessarily.
694 config['components_manager'].pop('graceful_shutdown_interval', None)
695 config['components_manager'].pop('graceful_shutdown_continue_accepting_requests_interval', None)
696 config['components_manager'].pop('graceful_shutdown_pending_requests_completion_interval', None)
697 components: dict = config['components_manager']['components']
698 if 'testsuite-support' not in components:
699 return
700 if components['testsuite-support'] is None:
701 components['testsuite-support'] = {}
702 testsuite_support = components['testsuite-support']
703 testsuite_support['testsuite-increased-timeout'] = '30s'
704 testsuite_support['testsuite-grpc-is-tls-enabled'] = False
705 testsuite_support['testsuite-mysql-is-tls-enabled'] = False
706 _set_postgresql_options(testsuite_support)
707 _set_redis_timeout(testsuite_support)
708 service_runner = pytestconfig.option.service_runner_mode
709 if not service_runner:
710 _disable_cache_periodic_update(testsuite_support)
711 testsuite_support['testsuite-tasks-enabled'] = not service_runner
712 testsuite_support['testsuite-periodic-dumps-enabled'] = '$userver-dumps-periodic'
713 components['testsuite-support'] = testsuite_support
714
715 config_vars['testsuite-enabled'] = True
716 if 'tests-control' in components:
717 components['tests-control']['testpoint-url'] = mockserver_info.url(
718 'testpoint',
719 )
720
721 return patch_config
722
723
724@pytest.fixture(scope='session')
725@pytest_userver.config.patch
726def userver_config_secdist(service_secdist_path) -> ServiceConfigPatch:
727 """
728 Returns a function that adjusts the static configuration file for testsuite.
729 Sets the `default-secdist-provider.config` to the value of
730 @ref pytest_userver.plugins.config.service_secdist_path "service_secdist_path"
731 fixture.
732
733 @ingroup userver_testsuite_fixtures
734 """
735
736 def _patch_config(config_yaml, config_vars):
737 if not service_secdist_path:
738 return
739
740 components = config_yaml['components_manager']['components']
741 if 'default-secdist-provider' not in components:
742 return
743
744 if not service_secdist_path.is_file():
745 raise ValueError(
746 f'"{service_secdist_path}" is not a file. Provide a '
747 f'"--service-secdist" pytest option or override the '
748 f'"service_secdist_path" fixture.',
749 )
750 components['default-secdist-provider']['config'] = str(
751 service_secdist_path,
752 )
753
754 return _patch_config
755
756
757@pytest.fixture(scope='session')
758@pytest_userver.config.patch
759def userver_config_testsuite_middleware(userver_testsuite_middleware_enabled: bool) -> ServiceConfigPatch:
760 def patch_config(config_yaml, config_vars):
761 if not userver_testsuite_middleware_enabled:
762 return
763
764 components = config_yaml['components_manager']['components']
765 if 'server' not in components:
766 return
767
768 pipeline_builder_name = components['server'].get(
769 'middleware-pipeline-builder', 'default-server-middleware-pipeline-builder'
770 )
771 pipeline_builder = components.setdefault(pipeline_builder_name, {})
772 middlewares = pipeline_builder.setdefault('append', [])
773 middlewares.append('testsuite-exceptions-handling-middleware')
774
775 return patch_config
776
777
778@pytest.fixture(scope='session')
780 """Whether testsuite middleware is enabled."""
781 return True
782
783
784@pytest.fixture(scope='session')
785@pytest_userver.config.patch
786def userver_config_deadlock_detector(userver_deadlock_detector_mode: str) -> ServiceConfigPatch:
787 """
788 Returns a function that adjusts the static configuration file for testsuite.
789 Sets the `deadlock_detector` parameter of the `coro_pool` component to the value of
790 @ref pytest_userver.plugins.config.userver_deadlock_detector_mode "userver_deadlock_detector_mode"
791 fixture.
792
793 @ingroup userver_testsuite_fixtures
794 """
795
796 def patch_config(config_yaml, config_vars):
797 coro_pool = config_yaml['components_manager'].setdefault('coro_pool', {})
798 coro_pool['deadlock_detector'] = userver_deadlock_detector_mode
799
800 return patch_config
801
802
803@pytest.fixture(scope='session')
805 """
806 Returns Deadlock detector mode for testsuite.
807 Override this fixture to modify the deadlock detector settings.
808 By default, it operates in `detect-only` mode. For a full list of available options, refer to the
809 `coro_pool.deadlock_detector` parameter in the `components::ManagerControllerComponent`.
810
811 @ingroup userver_testsuite_fixtures
812 """
813 return 'detect-only'