2Work with the configuration files of the service in testsuite.
18from typing
import TypeAlias
24from pytest_userver
import fixture_markers
43USERVER_CONFIG_HOOKS = []
45ServiceConfigPatch: TypeAlias = Callable[[dict, dict],
None]
51logger = logging.getLogger(__name__)
54class _UserverConfigPlugin:
56 self._config_hooks = []
59 def userver_config_hooks(self):
60 return self._config_hooks
62 def pytest_plugin_registered(self, plugin, manager):
63 if not isinstance(plugin, types.ModuleType):
65 uhooks = getattr(plugin,
'USERVER_CONFIG_HOOKS',
None)
66 if uhooks
is not None:
67 self._config_hooks.extend(uhooks)
70@dataclasses.dataclass(frozen=True)
76def pytest_configure(config):
77 config.pluginmanager.register(_UserverConfigPlugin(),
'userver_config')
80def pytest_addoption(parser) -> None:
81 group = parser.getgroup(
'userver-config')
83 '--service-log-level',
85 choices=[
'trace',
'debug',
'info',
'warning',
'error',
'critical'],
90 help=
'Path to service.yaml file.',
93 '--service-config-vars',
95 help=
'Path to config_vars.yaml file.',
100 help=
'Path to secure_data.json file.',
105 help=
'Path to dynamic config fallback file.',
110 help=
'Dump config from binary before running tests',
117@pytest.fixture(scope='session')
120 Returns the path to service.yaml file set by command line
121 `--service-config` option.
123 Override this fixture to change the way path to the static config is provided.
125 @ingroup userver_testsuite_fixtures
127 if pytestconfig.option.dump_config:
131 pytestconfig.option.service_config,
133 return pytestconfig.option.service_config
136@pytest.fixture(scope='session')
139 Runs the service binary with `--dump-db-schema` argument, dumps the 0_db_schema.sql file with database schema and
142 Override this fixture to change the way to dump the database schema.
144 @ingroup userver_testsuite_fixtures
147 path = service_tmpdir.joinpath(
'schemas')
152 path /
'0_db_schema.sql',
157@pytest.fixture(scope='session')
160 Returns the path to config_vars.yaml file set by command line
161 `--service-config-vars` option.
163 Override this fixture to change the way path to config_vars.yaml is
166 @ingroup userver_testsuite_fixtures
168 return pytestconfig.option.service_config_vars
171@pytest.fixture(scope='session')
174 Returns the path to secure_data.json file set by command line
175 `--service-secdist` option.
177 Override this fixture to change the way path to secure_data.json is
180 @ingroup userver_testsuite_fixtures
182 return pytestconfig.option.service_secdist
185@pytest.fixture(scope='session')
188 Returns the path to dynamic config fallback file set by command line
189 `--config-fallback` option.
191 Override this fixture to change the way path to dynamic config fallback is
194 @ingroup userver_testsuite_fixtures
196 return pytestconfig.option.config_fallback
199@pytest.fixture(scope='session')
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
206 @ingroup userver_testsuite_fixtures
208 return tmp_path_factory.mktemp(
209 pathlib.Path(service_binary).name,
214@pytest.fixture(scope='session')
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.
225 @ingroup userver_testsuite_fixtures
227 dst_path = service_tmpdir /
'config.yaml'
229 service_config_yaml = dict(service_config_yaml)
230 if not service_config_vars:
231 service_config_yaml.pop(
'config_vars',
None)
233 config_vars_path = service_tmpdir /
'config_vars.yaml'
234 config_vars_text = yaml.dump(service_config_vars)
236 'userver fixture "service_config_path_temp" writes the patched static config vars to "%s":\n%s',
240 config_vars_path.write_text(config_vars_text)
241 service_config_yaml[
'config_vars'] = str(config_vars_path)
244 'userver fixture "service_config_path_temp" writes the patched static config to "%s" equivalent to:\n%s',
246 yaml.dump(service_config),
248 dst_path.write_text(yaml.dump(service_config_yaml))
253@pytest.fixture(scope='session')
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
261 @ingroup userver_testsuite_fixtures
263 return _service_config_hooked.config_yaml
266@pytest.fixture(scope='session')
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
274 @ingroup userver_testsuite_fixtures
276 return _service_config_hooked.config_vars
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)
286 if not value.startswith(
'$'):
289 new_value = service_config_vars.get(value[1:])
290 if new_value
is not None:
291 config[key] = new_value
294 env = config.get(f
'{key}#env')
297 new_value = service_env.get(env)
299 new_value = os.environ.get(env)
301 config[key] = new_value
304 fallback = config.get(f
'{key}#fallback')
306 config[key] = fallback
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)
317 if not value.startswith(
'$'):
320 new_value = service_config_vars.get(value[1:])
321 if new_value
is not None:
322 config[i] = new_value
325@pytest.fixture(scope='session')
328 A function that takes `config_yaml`, `config_vars` and applies all
329 substitutions just like the service would.
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
335 @warning The returned YAML is a clone, mutating it will not modify
336 the actual config while in a config hook!
338 @ingroup userver_testsuite_fixtures
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):
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.',
349 config = copy.deepcopy(config_yaml)
350 _substitute_values(config, config_vars, service_env)
356@pytest.fixture(scope='session')
360 substitute_config_vars,
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.
368 @ingroup userver_testsuite_fixtures
371 config.pop(
'config_vars',
None)
375@pytest.fixture(scope='session')
376def _original_service_config(
378 service_config_vars_path,
383 assert service_config_path
is not None,
'Please specify proper path to the static config file, not None'
385 with open(service_config_path, mode=
'rt')
as fp:
386 config_yaml = yaml.safe_load(fp)
388 if service_config_vars_path:
389 with open(service_config_vars_path, mode=
'rt')
as fp:
390 config_vars = yaml.safe_load(fp)
394 return _UserverConfig(config_yaml=config_yaml, config_vars=config_vars)
397@pytest.fixture(scope='session')
398def _service_config_hooked(
402 _original_service_config,
404 config_yaml = copy.deepcopy(_original_service_config.config_yaml)
405 config_vars = copy.deepcopy(_original_service_config.config_vars)
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', ())
411 for hook
in itertools.chain(plugin_hooks, mark_hooks, local_hooks):
412 if not callable(hook):
413 hook_func = request.getfixturevalue(hook)
416 hook_func(config_yaml, config_vars)
418 return _UserverConfig(config_yaml=config_yaml, config_vars=config_vars)
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(
'/'),
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
432@pytest.fixture(scope='session')
433@pytest_userver.config.patch
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).
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.
442 Unlike normal `config_vars`, substitution vars can also apply to a part of a string.
443 For example, for `config_vars` entry
446 frobnicator-url: $mockserver/frobnicator
449 a possible patching result is as follows:
452 frobnicator-url: http://127.0.0.1:1234/frobnicator
455 Currently, the following substitution vars are supported:
457 * `mockserver` - mockserver url
458 * `grpc_mockserver` - grpc mockserver endpoint
460 @ingroup userver_testsuite_fixtures
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)
473 def patch_config(config_yaml, config_vars):
474 for key, value
in config_vars.items():
475 _substitute(key, value, config_vars)
480@pytest.fixture(scope='session')
481@pytest_userver.config.patch
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"
491 @ingroup userver_testsuite_fixtures
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)
509 listener[
'port'] = new_port
514@pytest.fixture(scope='session')
517 By default, userver HTTP client is only allowed to talk to mockserver
518 when running in testsuite. This makes tests repeatable and encapsulated.
520 Override this fixture to whitelist some additional URLs.
521 It is still strongly advised to only talk to localhost in tests.
523 @ingroup userver_testsuite_fixtures
528@pytest.fixture(scope='session')
532 allowed_url_prefixes_extra,
535 Returns final list of allowed urls prefixes when running in testsuite.
537 For most of cases you DO NOT want to override this fixture. Use "allowed_url_prefixes_extra" instead.
539 @ingroup userver_testsuite_fixtures
541 allowed_urls: list[str] = [mockserver_info.base_url]
543 if mockserver_ssl_info:
544 allowed_urls.append(mockserver_ssl_info.base_url)
546 allowed_urls += allowed_url_prefixes_extra
549 allowed_urls.append(mockserver_info.ws_url(
'/'))
550 if mockserver_ssl_info:
551 allowed_urls.append(mockserver_ssl_info.ws_url(
'/'))
556@pytest.fixture(scope='session')
557@pytest_userver.config.patch
559 allowed_url_prefixes,
560) -> ServiceConfigPatch:
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.
565 @ingroup userver_testsuite_fixtures
568 def patch_config(config, config_vars) -> None:
569 components: dict = config[
'components_manager'][
'components']
570 if not {
'http-client-core',
'testsuite-support'}.issubset(
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'
580 http_client_core[
'testsuite-allowed-url-prefixes'] = allowed_url_prefixes
585@pytest.fixture(scope='session')
588 Default log level to use in userver if no command line option was provided.
592 @ingroup userver_testsuite_fixtures
597@pytest.fixture(scope='session')
600 Returns --service-log-level value if provided, otherwise returns
601 userver_default_log_level() value from fixture.
603 @ingroup userver_testsuite_fixtures
605 if pytestconfig.option.service_log_level:
606 return pytestconfig.option.service_log_level
607 return userver_default_log_level
610@pytest.fixture(scope='session')
611@pytest_userver.config.patch
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.
618 @ingroup userver_testsuite_fixtures
621 if _service_logfile_path:
622 default_file_path = str(_service_logfile_path)
624 default_file_path =
'@stderr'
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',
637 config_vars[
'logger_level'] = userver_log_level
642@pytest.fixture(scope='session')
643@pytest_userver.config.patch
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.
650 @ingroup userver_testsuite_fixtures
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
661@pytest.fixture(scope='session')
662@pytest_userver.config.patch
665 Returns a function that adjusts the static configuration file for testsuite.
667 Sets up `testsuite-support` component, which:
669 - increases timeouts for userver drivers
670 - disables periodic cache updates
671 - enables testsuite tasks
673 Sets the `testsuite-enabled` in config_vars.yaml to `True`; sets the
674 `tests-control.testpoint-url` to mockserver URL.
676 @ingroup userver_testsuite_fixtures
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
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'
689 def _disable_cache_periodic_update(testsuite_support: dict) ->
None:
690 testsuite_support[
'testsuite-periodic-update-enabled'] =
False
692 def patch_config(config, config_vars) -> None:
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:
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
715 config_vars[
'testsuite-enabled'] =
True
716 if 'tests-control' in components:
717 components[
'tests-control'][
'testpoint-url'] = mockserver_info.url(
724@pytest.fixture(scope='session')
725@pytest_userver.config.patch
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"
733 @ingroup userver_testsuite_fixtures
736 def _patch_config(config_yaml, config_vars):
737 if not service_secdist_path:
740 components = config_yaml[
'components_manager'][
'components']
741 if 'default-secdist-provider' not in components:
744 if not service_secdist_path.is_file():
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.',
750 components[
'default-secdist-provider'][
'config'] = str(
751 service_secdist_path,
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:
764 components = config_yaml[
'components_manager'][
'components']
765 if 'server' not in components:
768 pipeline_builder_name = components[
'server'].get(
769 'middleware-pipeline-builder',
'default-server-middleware-pipeline-builder'
771 pipeline_builder = components.setdefault(pipeline_builder_name, {})
772 middlewares = pipeline_builder.setdefault(
'append', [])
773 middlewares.append(
'testsuite-exceptions-handling-middleware')
778@pytest.fixture(scope='session')
780 """Whether testsuite middleware is enabled."""
784@pytest.fixture(scope='session')
785@pytest_userver.config.patch
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"
793 @ingroup userver_testsuite_fixtures
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
803@pytest.fixture(scope='session')
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`.
811 @ingroup userver_testsuite_fixtures