2import concurrent.futures
12from testsuite.environment
import shell
14from pytest_userver
import sql
19if hasattr(yaml,
'CLoader'):
20 _YamlLoader = yaml.CLoader
22 _YamlLoader = yaml.Loader
24USERVER_CONFIG_HOOKS = [
'userver_config_ydb']
28def ydb(_ydb_client, _ydb_init):
32@pytest.fixture(scope='session')
33def _ydb_client(_ydb_client_pool):
34 with _ydb_client_pool()
as ydb_client:
38@pytest.fixture(scope='session')
39def _ydb_client_pool(_ydb_service, ydb_service_settings):
40 endpoint =
'{}:{}'.format(
41 ydb_service_settings.host,
42 ydb_service_settings.grpc_port,
46 @contextlib.contextmanager
49 ydb_client = pool.pop()
51 ydb_client = client.YdbClient(
53 ydb_service_settings.database,
58 pool.append(ydb_client)
63def pytest_service_register(register_service):
64 register_service(
'ydb', service.create_ydb_service)
67@pytest.fixture(scope='session')
68def _ydb_service(pytestconfig, ensure_service_started, ydb_service_settings):
69 if os.environ.get(
'YDB_ENDPOINT')
or pytestconfig.option.ydb_host:
71 ensure_service_started(
'ydb', settings=ydb_service_settings)
74@pytest.fixture(scope='session')
75def ydb_service_settings(pytestconfig) -> service.ServiceSettings:
76 endpoint_from_env = os.environ.get(
'YDB_ENDPOINT')
77 database = os.environ.get(
'YDB_DATABASE',
'local')
80 host, grpc_port = endpoint_from_env.split(
':', 1)
81 return service.ServiceSettings(
89 if pytestconfig.option.ydb_host:
90 return service.ServiceSettings(
91 host=pytestconfig.option.ydb_host,
92 grpc_port=pytestconfig.option.ydb_grpc_port,
93 mon_port=pytestconfig.option.ydb_mon_port,
94 ic_port=pytestconfig.option.ydb_ic_port,
97 return service.get_service_settings()
100@pytest.fixture(scope='session')
101def _ydb_service_schemas(service_source_dir):
102 service_schemas_ydb = service_source_dir /
'ydb' /
'schemas'
103 return discover.find_schemas([service_schemas_ydb])
106@pytest.fixture(scope='session')
107def ydb_settings_substitute(ydb_service_settings):
108 def secdist_settings(*args, **kwargs):
110 'endpoint':
'{}:{}'.format(
111 ydb_service_settings.host,
112 ydb_service_settings.grpc_port,
114 'database':
'/{}'.format(ydb_service_settings.database),
118 return {
'ydb_settings': secdist_settings}
121@pytest.fixture(scope='session')
131@pytest.fixture(scope='session')
132def ydb_migration_dir(service_source_dir) -> pathlib.Path:
134 Directory with migration files
136 @ingroup userver_testsuite_fixtures
138 return service_source_dir /
'ydb' /
'migrations'
141YDB_MIGRATION_TABLE =
'goose_db_version'
144def _ydb_migrate(ydb_service_settings, ydb_migration_dir, goose_binary_path):
145 if not ydb_migration_dir.exists():
147 if not list(ydb_migration_dir.iterdir()):
150 host = ydb_service_settings.host
151 port = ydb_service_settings.grpc_port
154 str(goose_binary_path),
156 str(ydb_migration_dir),
160 (f
'grpc://{host}:{port}/local?go_query_mode=scripting&go_fake_tx=scripting&go_query_bind=declare,numeric'),
164 shell.execute(command, verbose=
True, command_alias=
'ydb/migrations')
165 except shell.SubprocessFailed
as exc:
166 raise Exception(f
'YDB run migration failed:\n{exc}')
169@pytest.fixture(scope='session')
170def goose_binary_path() -> pathlib.Path:
172 Path to 'goose' migration tool.
174 Override this fixture to change the way 'goose' binary is discovered.
176 @ingroup userver_testsuite_fixtures
181 return yatest.common.runtime.binary_path(
182 'contrib/go/patched/goose/cmd/goose/goose',
188def _ydb_fetch_table_names(ydb_service_settings, ydb_cli) -> List[str]:
190 host = ydb_service_settings.host
191 port = ydb_service_settings.grpc_port
192 output = subprocess.check_output(
196 f
'grpc://{host}:{port}',
207 for line
in output.split(
'\n'):
208 if ' table ' not in line:
212 if YDB_MIGRATION_TABLE
in line:
214 path = line.split(
'│')[6].strip()
217 except subprocess.CalledProcessError
as exc:
218 raise Exception(f
'Could not fetch table names:\n{exc}')
221@pytest.fixture(scope='session')
222def ydb_cli() -> pathlib.Path:
224 Path to YDB CLI executable.
226 Override this fixture to change the way YDB CLI is discovered.
228 @ingroup userver_testsuite_fixtures
233 return yatest.common.runtime.binary_path(
'contrib/ydb/apps/ydb/ydb')
238@pytest.fixture(scope='session')
241 _ydb_service_schemas,
242 ydb_service_settings,
247 if _ydb_service_schemas
and ydb_migration_dir.exists():
249 'Both ydb/schema and ydb/migrations exist, which are mutually exclusive',
253 for schema_path
in _ydb_service_schemas:
254 with open(schema_path)
as fp:
255 tables_schemas = yaml.load(fp.read(), Loader=_YamlLoader)
256 for table_schema
in tables_schemas:
257 client.drop_table(_ydb_client, table_schema[
'path'])
258 client.create_table(_ydb_client, table_schema)
259 _ydb_state.tables.append(table_schema[
'path'])
262 _ydb_migrate(ydb_service_settings, ydb_migration_dir, goose_binary_path)
264 _ydb_state.init =
True
267@pytest.fixture(scope='session')
268def _ydb_tables(_ydb_state, _ydb_prepare, ydb_service_settings, ydb_cli):
271 *_ydb_fetch_table_names(ydb_service_settings, ydb_cli),
273 return tuple(sorted(tables))
281 ydb_service_settings,
287 def ydb_mark_queries(files=(), queries=()):
290 result_queries.append(load(path))
291 result_queries.extend(queries)
292 return result_queries
294 def drop_table(table):
295 with _ydb_client_pool()
as ydb_client:
296 ydb_client.execute(
'DELETE FROM `{}`'.format(table))
299 with concurrent.futures.ThreadPoolExecutor(
300 max_workers=len(_ydb_tables),
302 executer.map(drop_table, _ydb_tables)
304 for mark
in request.node.iter_markers(
'ydb'):
305 queries = ydb_mark_queries(**mark.kwargs)
306 for query
in queries:
307 _ydb_client.execute(query)
311def userver_ydb_trx(testpoint) -> sql.RegisteredTrx:
313 The fixture maintains transaction fault injection state using
316 @see pytest_userver.sql.RegisteredTrx
318 @snippet integration_tests/tests/test_trx_failure.py fault injection
320 @ingroup userver_testsuite_fixtures
323 registered = sql.RegisteredTrx()
325 @testpoint('ydb_trx_commit')
326 def _pg_trx_tp(data):
327 should_fail = registered.is_failure_enabled(data[
'trx_name'])
328 return {
'trx_should_fail': should_fail}
333@pytest.fixture(scope='session')
334def userver_config_ydb(ydb_service_settings):
336 Returns a function that adjusts the static configuration file for testsuite.
338 For all `ydb.databases`, sets `endpoint` and `database` to the local test
341 @ingroup userver_testsuite_fixtures
344 endpoint = f
'{ydb_service_settings.host}:{ydb_service_settings.grpc_port}'
345 database = (
'' if ydb_service_settings.database.startswith(
'/')
else '/') + ydb_service_settings.database
347 def patch_config(config, config_vars):
348 ydb_component = config[
'components_manager'][
'components'][
'ydb']
349 if isinstance(ydb_component, str):
350 ydb_component = config_vars[ydb_component[1:]]
351 databases = ydb_component[
'databases']
352 for dbname, dbconfig
in databases.items():
353 dbconfig[
'endpoint'] = endpoint
354 dbconfig[
'database'] = database