userver: /data/code/userver/testsuite/pytest_plugins/pytest_userver/plugins/ydb/ydbsupport.py Source File
Loading...
Searching...
No Matches
ydbsupport.py
1# pylint: disable=redefined-outer-name
2import concurrent.futures
3import contextlib
4import dataclasses
5import os
6import pathlib
7import subprocess
8
9import pytest
10import yaml
11
12from testsuite.environment import shell
13
14from pytest_userver import sql
17from . import client
18from . import discover
19from . import service
20
21if hasattr(yaml, 'CLoader'):
22 _YamlLoader = yaml.CLoader # type: ignore
23else:
24 _YamlLoader = yaml.Loader # type: ignore
25
26
27@pytest.fixture
28@pytest_userver.service.dependency
29def ydb(_ydb_client, _ydb_init) -> client.YdbClient:
30 """
31 YDB client fixture.
32
33 Also automatically prepares YDB server before the userver service is started.
34
35 @ingroup userver_testsuite_fixtures
36 """
37 return _ydb_client
38
39
40@pytest.fixture(scope='session')
41def _ydb_client(_ydb_client_pool):
42 with _ydb_client_pool() as ydb_client:
43 yield ydb_client
44
45
46@pytest.fixture(scope='session')
47def _ydb_client_pool(_ydb_service, ydb_service_settings):
48 endpoint = '{}:{}'.format(
49 ydb_service_settings.host,
50 ydb_service_settings.grpc_port,
51 )
52 pool = []
53
54 @contextlib.contextmanager
55 def get_client():
56 try:
57 ydb_client = pool.pop()
58 except IndexError:
59 ydb_client = client.YdbClient(
60 endpoint,
61 ydb_service_settings.database,
62 )
63 try:
64 yield ydb_client
65 finally:
66 pool.append(ydb_client)
67
68 return get_client
69
70
71def pytest_service_register(register_service):
72 register_service('ydb', service.create_ydb_service)
73
74
75@pytest.fixture(scope='session')
76def _ydb_service(pytestconfig, ensure_service_started, ydb_service_settings):
77 if os.environ.get('YDB_ENDPOINT') or pytestconfig.option.ydb_host:
78 return
79 ensure_service_started('ydb', settings=ydb_service_settings)
80
81
82@pytest.fixture(scope='session')
83def ydb_service_settings(pytestconfig) -> service.ServiceSettings:
84 endpoint_from_env = os.environ.get('YDB_ENDPOINT')
85 database = os.environ.get('YDB_DATABASE', 'local')
86
87 if endpoint_from_env:
88 host, grpc_port = endpoint_from_env.split(':', 1)
89 return service.ServiceSettings(
90 host=host,
91 grpc_port=grpc_port,
92 mon_port=None,
93 ic_port=None,
94 database=database,
95 wait_time=0,
96 )
97
98 if pytestconfig.option.ydb_host:
99 return service.ServiceSettings(
100 host=pytestconfig.option.ydb_host,
101 grpc_port=pytestconfig.option.ydb_grpc_port,
102 mon_port=pytestconfig.option.ydb_mon_port,
103 ic_port=pytestconfig.option.ydb_ic_port,
104 database=database,
105 wait_time=pytestconfig.option.ydb_wait_time,
106 )
107 settings = service.get_service_settings()
108 return dataclasses.replace(settings, wait_time=pytestconfig.option.ydb_wait_time)
109
110
111@pytest.fixture(scope='session')
112def _ydb_service_schemas(service_source_dir):
113 service_schemas_ydb = service_source_dir / 'ydb' / 'schemas'
114 return discover.find_schemas([service_schemas_ydb])
115
116
117@pytest.fixture(scope='session')
118def ydb_settings_substitute(ydb_service_settings):
119 def secdist_settings(*args, **kwargs):
120 return {
121 'endpoint': '{}:{}'.format(
122 ydb_service_settings.host,
123 ydb_service_settings.grpc_port,
124 ),
125 'database': '/{}'.format(ydb_service_settings.database),
126 'token': '',
127 }
128
129 return {'ydb_settings': secdist_settings}
130
131
132@pytest.fixture(scope='session')
133def _ydb_state():
134 class State:
135 def __init__(self):
136 self.init = False
137 self.tables = []
138
139 return State()
140
141
142@pytest.fixture(scope='session')
143def ydb_migration_dir(service_source_dir) -> pathlib.Path:
144 """
145 Directory with migration files
146
147 @ingroup userver_testsuite_fixtures
148 """
149 return service_source_dir / 'ydb' / 'migrations'
150
151
152YDB_MIGRATION_TABLE = 'goose_db_version'
153
154
155def _ydb_migrate(ydb_service_settings, ydb_migration_dir, goose_binary_path):
156 if not ydb_migration_dir.exists():
157 return
158 if not list(ydb_migration_dir.iterdir()):
159 return
160
161 host = ydb_service_settings.host
162 port = ydb_service_settings.grpc_port
163
164 command = [
165 str(goose_binary_path),
166 '-dir',
167 str(ydb_migration_dir),
168 '-table',
169 YDB_MIGRATION_TABLE,
170 'ydb',
171 (f'grpc://{host}:{port}/local?go_query_mode=scripting&go_fake_tx=scripting&go_query_bind=declare,numeric'),
172 'up',
173 ]
174 try:
175 shell.execute(command, verbose=True, command_alias='ydb/migrations')
176 except shell.SubprocessFailed as exc:
177 raise Exception(f'YDB run migration failed:\n{exc}')
178
179
180@pytest.fixture(scope='session')
181def goose_binary_path() -> pathlib.Path:
182 """
183 Path to 'goose' migration tool.
184
185 Override this fixture to change the way 'goose' binary is discovered.
186
187 @ingroup userver_testsuite_fixtures
188 """
189 try:
190 import yatest
191
192 return yatest.common.runtime.binary_path(
193 'contrib/go/patched/goose/cmd/goose/goose',
194 )
195 except ImportError:
196 return 'goose'
197
198
199def _ydb_fetch_table_names(ydb_service_settings, ydb_cli) -> list[str]:
200 try:
201 host = ydb_service_settings.host
202 port = ydb_service_settings.grpc_port
203 output = subprocess.check_output(
204 [
205 str(ydb_cli),
206 '-e',
207 f'grpc://{host}:{port}',
208 '-d',
209 '/local',
210 'scheme',
211 'ls',
212 '-lR',
213 ],
214 encoding='utf-8',
215 )
216 tables = []
217
218 for line in output.split('\n'):
219 if ' table ' not in line:
220 continue
221 if '.sys' in line:
222 continue
223 if YDB_MIGRATION_TABLE in line:
224 continue
225 path = line.split('│')[6].strip()
226 tables.append(path)
227 return tables
228 except subprocess.CalledProcessError as exc:
229 raise Exception(f'Could not fetch table names:\n{exc}')
230
231
232@pytest.fixture(scope='session')
233def ydb_cli() -> pathlib.Path:
234 """
235 Path to YDB CLI executable.
236
237 Override this fixture to change the way YDB CLI is discovered.
238
239 @ingroup userver_testsuite_fixtures
240 """
241 try:
242 import yatest
243
244 return yatest.common.runtime.binary_path('contrib/ydb/apps/ydb/ydb')
245 except ImportError:
246 return 'ydb'
247
248
249@pytest.fixture(scope='session')
250def _ydb_prepare(
251 _ydb_client,
252 _ydb_service_schemas,
253 ydb_service_settings,
254 _ydb_state,
255 ydb_migration_dir,
256 goose_binary_path,
257):
258 if _ydb_service_schemas and ydb_migration_dir.exists():
259 raise Exception(
260 'Both ydb/schema and ydb/migrations exist, which are mutually exclusive',
261 )
262
263 # testsuite legacy
264 for schema_path in _ydb_service_schemas:
265 with open(schema_path) as fp:
266 tables_schemas = yaml.load(fp.read(), Loader=_YamlLoader)
267 for table_schema in tables_schemas:
268 client.drop_table(_ydb_client, table_schema['path'])
269 client.create_table(_ydb_client, table_schema)
270 _ydb_state.tables.append(table_schema['path'])
271
272 # goose
273 _ydb_migrate(ydb_service_settings, ydb_migration_dir, goose_binary_path)
274
275 _ydb_state.init = True
276
277
278@pytest.fixture(scope='session')
279def _ydb_tables(_ydb_state, _ydb_prepare, ydb_service_settings, ydb_cli):
280 tables = {
281 *_ydb_state.tables,
282 *_ydb_fetch_table_names(ydb_service_settings, ydb_cli),
283 }
284 return tuple(sorted(tables))
285
286
287@pytest.fixture
288def _ydb_init(
289 request,
290 _ydb_client,
291 _ydb_state,
292 ydb_service_settings,
293 _ydb_prepare,
294 _ydb_tables,
295 _ydb_client_pool,
296 load,
297):
298 def ydb_mark_queries(files=(), queries=()):
299 result_queries = []
300 for path in files:
301 result_queries.append(load(path))
302 result_queries.extend(queries)
303 return result_queries
304
305 def drop_table(table):
306 with _ydb_client_pool() as ydb_client:
307 ydb_client.execute('DELETE FROM `{}`'.format(table))
308
309 if _ydb_tables:
310 with concurrent.futures.ThreadPoolExecutor(
311 max_workers=len(_ydb_tables),
312 ) as executer:
313 list(executer.map(drop_table, _ydb_tables))
314
315 for mark in request.node.iter_markers('ydb'):
316 queries = ydb_mark_queries(**mark.kwargs)
317 for query in queries:
318 _ydb_client.execute(query)
319
320
321@pytest.fixture
322def userver_ydb_trx(testpoint) -> sql.RegisteredTrx:
323 """
324 The fixture maintains transaction fault injection state using
325 RegisteredTrx class.
326
327 @see pytest_userver.sql.RegisteredTrx
328
329 @snippet integration_tests/tests/test_trx_failure.py fault injection
330
331 @ingroup userver_testsuite_fixtures
332 """
333
334 registered = sql.RegisteredTrx()
335
336 @testpoint('ydb_trx_commit')
337 def _pg_trx_tp(data):
338 should_fail = registered.is_failure_enabled(data['trx_name'])
339 return {'trx_should_fail': should_fail}
340
341 return registered
342
343
344@pytest.fixture(scope='session')
345@pytest_userver.config.patch
346def userver_config_ydb(ydb_service_settings):
347 """
348 Returns a function that adjusts the static configuration file for testsuite.
349
350 For all `ydb.databases`, sets `endpoint` and `database` to the local test
351 YDB instance.
352
353 @ingroup userver_testsuite_fixtures
354 """
355
356 endpoint = f'{ydb_service_settings.host}:{ydb_service_settings.grpc_port}'
357 database = ('' if ydb_service_settings.database.startswith('/') else '/') + ydb_service_settings.database
358
359 def patch_config(config, config_vars):
360 ydb_component = config['components_manager']['components']['ydb']
361 if isinstance(ydb_component, str):
362 ydb_component = config_vars[ydb_component[1:]]
363 databases = ydb_component['databases']
364 for dbconfig in databases.values():
365 dbconfig['endpoint'] = endpoint
366 dbconfig['database'] = database
367
368 return patch_config