2import concurrent.futures
14from pytest_userver
import sql
21if hasattr(yaml,
'CLoader'):
22 _YamlLoader = yaml.CLoader
24 _YamlLoader = yaml.Loader
28@pytest_userver.service.dependency
29def ydb(_ydb_client, _ydb_init) -> client.YdbClient:
33 Also automatically prepares YDB server before the userver service is started.
35 @ingroup userver_testsuite_fixtures
40@pytest.fixture(scope='session')
41def _ydb_client(_ydb_client_pool):
42 with _ydb_client_pool()
as ydb_client:
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,
54 @contextlib.contextmanager
57 ydb_client = pool.pop()
59 ydb_client = client.YdbClient(
61 ydb_service_settings.database,
66 pool.append(ydb_client)
71def pytest_service_register(register_service):
72 register_service(
'ydb', service.create_ydb_service)
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:
79 ensure_service_started(
'ydb', settings=ydb_service_settings)
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')
88 host, grpc_port = endpoint_from_env.split(
':', 1)
89 return service.ServiceSettings(
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,
105 wait_time=pytestconfig.option.ydb_wait_time,
107 settings = service.get_service_settings()
108 return dataclasses.replace(settings, wait_time=pytestconfig.option.ydb_wait_time)
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])
117@pytest.fixture(scope='session')
118def ydb_settings_substitute(ydb_service_settings):
119 def secdist_settings(*args, **kwargs):
121 'endpoint':
'{}:{}'.format(
122 ydb_service_settings.host,
123 ydb_service_settings.grpc_port,
125 'database':
'/{}'.format(ydb_service_settings.database),
129 return {
'ydb_settings': secdist_settings}
132@pytest.fixture(scope='session')
142@pytest.fixture(scope='session')
143def ydb_migration_dir(service_source_dir) -> pathlib.Path:
145 Directory with migration files
147 @ingroup userver_testsuite_fixtures
149 return service_source_dir /
'ydb' /
'migrations'
152YDB_MIGRATION_TABLE =
'goose_db_version'
155def _ydb_migrate(ydb_service_settings, ydb_migration_dir, goose_binary_path):
156 if not ydb_migration_dir.exists():
158 if not list(ydb_migration_dir.iterdir()):
161 host = ydb_service_settings.host
162 port = ydb_service_settings.grpc_port
165 str(goose_binary_path),
167 str(ydb_migration_dir),
171 (f
'grpc://{host}:{port}/local?go_query_mode=scripting&go_fake_tx=scripting&go_query_bind=declare,numeric'),
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}')
180@pytest.fixture(scope='session')
181def goose_binary_path() -> pathlib.Path:
183 Path to 'goose' migration tool.
185 Override this fixture to change the way 'goose' binary is discovered.
187 @ingroup userver_testsuite_fixtures
192 return yatest.common.runtime.binary_path(
193 'contrib/go/patched/goose/cmd/goose/goose',
199def _ydb_fetch_table_names(ydb_service_settings, ydb_cli) -> list[str]:
201 host = ydb_service_settings.host
202 port = ydb_service_settings.grpc_port
203 output = subprocess.check_output(
207 f
'grpc://{host}:{port}',
218 for line
in output.split(
'\n'):
219 if ' table ' not in line:
223 if YDB_MIGRATION_TABLE
in line:
225 path = line.split(
'│')[6].strip()
228 except subprocess.CalledProcessError
as exc:
229 raise Exception(f
'Could not fetch table names:\n{exc}')
232@pytest.fixture(scope='session')
233def ydb_cli() -> pathlib.Path:
235 Path to YDB CLI executable.
237 Override this fixture to change the way YDB CLI is discovered.
239 @ingroup userver_testsuite_fixtures
244 return yatest.common.runtime.binary_path(
'contrib/ydb/apps/ydb/ydb')
249@pytest.fixture(scope='session')
252 _ydb_service_schemas,
253 ydb_service_settings,
258 if _ydb_service_schemas
and ydb_migration_dir.exists():
260 'Both ydb/schema and ydb/migrations exist, which are mutually exclusive',
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'])
273 _ydb_migrate(ydb_service_settings, ydb_migration_dir, goose_binary_path)
275 _ydb_state.init =
True
278@pytest.fixture(scope='session')
279def _ydb_tables(_ydb_state, _ydb_prepare, ydb_service_settings, ydb_cli):
282 *_ydb_fetch_table_names(ydb_service_settings, ydb_cli),
284 return tuple(sorted(tables))
292 ydb_service_settings,
298 def ydb_mark_queries(files=(), queries=()):
301 result_queries.append(load(path))
302 result_queries.extend(queries)
303 return result_queries
305 def drop_table(table):
306 with _ydb_client_pool()
as ydb_client:
307 ydb_client.execute(
'DELETE FROM `{}`'.format(table))
310 with concurrent.futures.ThreadPoolExecutor(
311 max_workers=len(_ydb_tables),
313 list(executer.map(drop_table, _ydb_tables))
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)
322def userver_ydb_trx(testpoint) -> sql.RegisteredTrx:
324 The fixture maintains transaction fault injection state using
327 @see pytest_userver.sql.RegisteredTrx
329 @snippet integration_tests/tests/test_trx_failure.py fault injection
331 @ingroup userver_testsuite_fixtures
334 registered = sql.RegisteredTrx()
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}
344@pytest.fixture(scope='session')
345@pytest_userver.config.patch
346def userver_config_ydb(ydb_service_settings):
348 Returns a function that adjusts the static configuration file for testsuite.
350 For all `ydb.databases`, sets `endpoint` and `database` to the local test
353 @ingroup userver_testsuite_fixtures
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
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