userver: /data/code/userver/testsuite/pytest_plugins/pytest_userver/plugins/dynamic_config.py Source File
Loading...
Searching...
No Matches
dynamic_config.py
1"""
2Supply dynamic configs for the service in testsuite.
3"""
4
5# pylint: disable=redefined-outer-name
6from collections.abc import Callable
7from collections.abc import Iterable
8import dataclasses
9import json
10import pathlib
11
12import pytest
13
14from pytest_userver import dynconf
16
17USERVER_CACHE_CONTROL_HOOKS = {
18 'dynamic-config-client-updater': '_userver_dynconfig_cache_control',
19}
20
21
22@pytest.fixture
24 request,
25 search_path,
26 object_substitute,
27 cache_invalidation_state,
28 _dynamic_config_defaults_storage,
29 config_service_defaults,
30 dynamic_config_changelog,
31 _dynconf_load_json_cached,
32 dynconf_cache_names,
33) -> dynconf.DynamicConfig:
34 """
35 Fixture that allows to control dynamic config values used by the service.
36
37 Example:
38
39 @snippet core/functional_tests/basic_chaos/tests-nonchaos/handlers/test_log_request_headers.py dynamic_config usage
40
41 Example with @ref kill_switches "kill switches":
42
43 @snippet core/functional_tests/dynamic_configs/tests/test_examples.py dynamic_config usage with kill switches
44
45 HTTP and gRPC client requests call `update_server_state` automatically before each request.
46
47 For main dynamic config documentation:
48
49 @see @ref dynamic_config_testsuite
50
51 See also other related fixtures:
52 * @ref pytest_userver.plugins.dynamic_config.dynamic_config "config_service_defaults"
53 * @ref pytest_userver.plugins.dynamic_config.dynamic_config "dynamic_config_fallback_patch"
54 * @ref pytest_userver.plugins.dynamic_config.dynamic_config "mock_configs_service"
55
56 @ingroup userver_testsuite_fixtures
57 """
58 config = dynconf.DynamicConfig(
59 initial_values=config_service_defaults,
60 defaults=_dynamic_config_defaults_storage.snapshot,
61 config_cache_components=dynconf_cache_names,
62 cache_invalidation_state=cache_invalidation_state,
63 changelog=dynamic_config_changelog,
64 )
65
66 with dynamic_config_changelog.rollback(config_service_defaults):
67 updates = {}
68 for path in reversed(list(search_path('config.json'))):
69 values = _dynconf_load_json_cached(path)
70 updates.update(values)
71 for marker in request.node.iter_markers('config'):
72 value_update_kwargs = {
73 key: value for key, value in marker.kwargs.items() if value is not dynconf.USE_STATIC_DEFAULT
74 }
75 value_updates_json = object_substitute(value_update_kwargs)
76 updates.update(value_updates_json)
77 config.set_values_unsafe(updates)
78
79 kill_switches_disabled = []
80 for marker in request.node.iter_markers('config'):
81 kill_switches_disabled.extend(
82 key for key, value in marker.kwargs.items() if value is dynconf.USE_STATIC_DEFAULT
83 )
84 config.switch_to_static_default(*kill_switches_disabled)
85
86 yield config
87
88
89# @cond
90
91
92def pytest_configure(config):
93 config.addinivalue_line(
94 'markers',
95 'config: per-test dynamic config values',
96 )
97 config.addinivalue_line(
98 'markers',
99 'disable_config_check: disable config mark keys check',
100 )
101
102
103# @endcond
104
105
106@pytest.fixture(scope='session')
107def dynconf_cache_names() -> Iterable[str]:
108 return tuple(USERVER_CACHE_CONTROL_HOOKS.keys())
109
110
111@pytest.fixture(scope='session')
112def _dynconf_json_cache():
113 return {}
114
115
116@pytest.fixture
117def _dynconf_load_json_cached(json_loads, _dynconf_json_cache):
118 def load(path: pathlib.Path):
119 if path not in _dynconf_json_cache:
120 _dynconf_json_cache[path] = json_loads(path.read_text())
121 return _dynconf_json_cache[path]
122
123 return load
124
125
126@pytest.fixture
127def taxi_config(dynamic_config) -> dynconf.DynamicConfig:
128 """
129 Deprecated, use `dynamic_config` instead.
130 """
131 return dynamic_config
132
133
134@pytest.fixture(scope='session')
135def dynamic_config_fallback_patch() -> dynconf.ConfigValuesDict:
136 """
137 Override this fixture to replace some dynamic config values specifically
138 for testsuite tests:
139
140 @code
141 @pytest.fixture(scope='session')
142 def dynamic_config_fallback_patch():
143 return {"MY_CONFIG_NAME": 42}
144 @endcode
145
146 @ingroup userver_testsuite_fixtures
147 """
148 return {}
149
150
151@pytest.fixture(scope='session')
153 config_fallback_path,
154 dynamic_config_fallback_patch,
155) -> dynconf.ConfigValuesDict:
156 """
157 Fixture that returns default values for dynamic config. You may override
158 it in your local conftest.py or fixture:
159
160 @code
161 @pytest.fixture(scope='session')
162 def config_service_defaults():
163 with open('defaults.json') as fp:
164 return json.load(fp)
165 @endcode
166
167 @ingroup userver_testsuite_fixtures
168 """
169 if not config_fallback_path:
170 return dynamic_config_fallback_patch
171
172 if pathlib.Path(config_fallback_path).exists():
173 with open(config_fallback_path, 'r', encoding='utf-8') as file:
174 fallback = json.load(file)
175 fallback.update(dynamic_config_fallback_patch)
176 return fallback
177
178 raise RuntimeError(
179 'Invalid path specified in config_fallback_path fixture. '
180 'Probably invalid path was passed in --config-fallback pytest option.',
181 )
182
183
184@dataclasses.dataclass(frozen=False)
186 snapshot: dynconf.ConfigValuesDict | None
187
188 async def update(self, client, dynamic_config) -> None:
189 if self.snapshot is None:
190 defaults = await client.get_dynamic_config_defaults()
191 if not isinstance(defaults, dict):
193 self.snapshot = defaults
194 # pylint:disable=protected-access
195 dynamic_config._defaults = defaults
196
197
198# config_service_defaults fetches the dynamic config overrides, e.g. specified
199# in the json file, then userver_config_dynconf_fallback forwards them
200# to the service so that it has the correct dynamic config defaults.
201#
202# Independently of that, it is useful to have values for all configs, even
203# unspecified in tests, on the testsuite side. For that, we ask the service
204# for the dynamic config defaults after it's launched. It's enough to update
205# defaults once per service launch.
206@pytest.fixture(scope='session')
207def _dynamic_config_defaults_storage() -> _ConfigDefaults:
208 return _ConfigDefaults(snapshot=None)
209
210
211@pytest.fixture(scope='session')
212@pytest_userver.config.patch
214 """
215 Returns a function that adjusts the static configuration file for
216 the testsuite.
217 Sets `dynamic-config.fs-cache-path` to a file that is reset after the tests
218 to avoid leaking dynamic config values between test sessions.
219
220 @ingroup userver_testsuite_fixtures
221 """
222
223 def patch_config(config, _config_vars) -> None:
224 components = config['components_manager']['components']
225 dynamic_config_component = components.get('dynamic-config', None) or {}
226 if dynamic_config_component.get('fs-cache-path', '') == '':
227 return
228
229 cache_path = service_tmpdir / 'configs' / 'config_cache.json'
230
231 if cache_path.is_file():
232 # To avoid leaking dynamic config values between test sessions
233 cache_path.unlink()
234
235 dynamic_config_component['fs-cache-path'] = str(cache_path)
236
237 return patch_config
238
239
240@pytest.fixture(scope='session')
241@pytest_userver.config.patch
242def userver_config_dynconf_fallback(config_service_defaults):
243 """
244 Returns a function that adjusts the static configuration file for
245 the testsuite.
246 Removes `dynamic-config.defaults-path`.
247 Updates `dynamic-config.defaults` with `config_service_defaults`.
248
249 @ingroup userver_testsuite_fixtures
250 """
251
252 def extract_defaults_dict(component_config, config_vars) -> dict:
253 defaults_field = component_config.get('defaults', None) or {}
254 if isinstance(defaults_field, dict):
255 return defaults_field
256 elif isinstance(defaults_field, str):
257 if defaults_field.startswith('$'):
258 return config_vars.get(defaults_field[1:], {})
259 assert False, f'Unexpected static config option `dynamic-config.defaults`: {defaults_field!r}'
260
261 def _patch_config(config_yaml, config_vars):
262 components = config_yaml['components_manager']['components']
263 if components.get('dynamic-config', None) is None:
264 components['dynamic-config'] = {}
265 dynconf_component = components['dynamic-config']
266
267 dynconf_component.pop('defaults-path', None)
268 defaults = dict(
269 extract_defaults_dict(dynconf_component, config_vars),
270 **config_service_defaults,
271 )
272 dynconf_component['defaults'] = defaults
273
274 return _patch_config
275
276
277@pytest.fixture(scope='session')
278@pytest_userver.config.patch
279def userver_config_dynconf_url(mockserver_info):
280 """
281 Returns a function that adjusts the static configuration file for
282 the testsuite.
283 Sets the `dynamic-config-client.config-url` to the value of mockserver
284 configs-service, so that the
285 @ref pytest_userver.plugins.dynamic_config.mock_configs_service
286 "mock_configs_service" fixture could work.
287
288 @ingroup userver_testsuite_fixtures
289 """
290
291 def _patch_config(config, _config_vars) -> None:
292 components = config['components_manager']['components']
293 client = components.get('dynamic-config-client', None)
294 if client:
295 client['config-url'] = mockserver_info.url('configs-service')
296 client['append-path-to-url'] = True
297
298 return _patch_config
299
300
301# @cond
302
303
304# TODO publish dynconf._Changelog and document how to use it in custom config service
305# mocks.
306@pytest.fixture(scope='session')
307def dynamic_config_changelog() -> dynconf._Changelog:
308 return dynconf._Changelog()
309
310
311# @endcond
312
313
314@pytest.fixture
316 mockserver,
317 dynamic_config: dynconf.DynamicConfig,
318 dynamic_config_changelog: dynconf._Changelog,
319) -> None:
320 """
321 Adds a mockserver handler that forwards dynamic_config to service's
322 `dynamic-config-client` component.
323
324 @ingroup userver_testsuite_fixtures
325 """
326
327 @mockserver.json_handler('/configs-service/configs/values')
328 def _mock_configs(request):
329 updates = dynamic_config_changelog.get_updated_since(
330 dynconf._create_config_dict(
331 dynamic_config.get_values_unsafe(),
332 dynamic_config.get_kill_switches_disabled_unsafe(),
333 ),
334 request.json.get('updated_since', ''),
335 request.json.get('ids'),
336 )
337 response = {'configs': updates.values, 'updated_at': updates.timestamp}
338 if updates.removed:
339 response['removed'] = updates.removed
340 if updates.kill_switches_disabled:
341 response['kill_switches_disabled'] = updates.kill_switches_disabled
342 return response
343
344 @mockserver.json_handler('/configs-service/configs/status')
345 def _mock_configs_status(_request):
346 return {
347 'updated_at': dynamic_config_changelog.timestamp.strftime(
348 '%Y-%m-%dT%H:%M:%SZ',
349 ),
350 }
351
352
353@pytest.fixture
354def _userver_dynconfig_cache_control(dynamic_config_changelog: dynconf._Changelog):
355 def cache_control(updater, timestamp):
356 entry = dynamic_config_changelog.commit()
357 if entry.timestamp == timestamp:
358 updater.exclude()
359 else:
360 updater.incremental()
361 return entry.timestamp
362
363 return cache_control
364
365
366_CHECK_CONFIG_ERROR = (
367 'Your are trying to override config value using '
368 '@pytest.mark.config({}) '
369 'that does not seem to be used by your service.\n\n'
370 'In case you really need to disable this check please add the '
371 'following mark to your testcase:\n\n'
372 '@pytest.mark.disable_config_check'
373)
374
375
376# Should be invoked after _dynamic_config_defaults_storage is filled.
377@pytest.fixture
378def _check_config_marks(
379 request,
380 _dynamic_config_defaults_storage,
381) -> Callable[[], None]:
382 def check():
383 config_defaults = _dynamic_config_defaults_storage.snapshot
384 assert config_defaults is not None
385
386 if request.node.get_closest_marker('disable_config_check'):
387 return
388
389 unknown_configs = [
390 key for marker in request.node.iter_markers('config') for key in marker.kwargs if key not in config_defaults
391 ]
392
393 if unknown_configs:
394 message = _CHECK_CONFIG_ERROR.format(
395 ', '.join(f'{key}=...' for key in sorted(unknown_configs)),
396 )
397 raise dynconf.UnknownConfigError(message)
398
399 return check