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, ydb_service_settings.grpc_port,
45 @contextlib.contextmanager
48 ydb_client = pool.pop()
50 ydb_client = client.YdbClient(
51 endpoint, ydb_service_settings.database,
56 pool.append(ydb_client)
61def pytest_service_register(register_service):
62 register_service(
'ydb', service.create_ydb_service)
65@pytest.fixture(scope='session')
66def _ydb_service(pytestconfig, ensure_service_started, ydb_service_settings):
67 if os.environ.get(
'YDB_ENDPOINT')
or pytestconfig.option.ydb_host:
69 ensure_service_started(
'ydb', settings=ydb_service_settings)
72@pytest.fixture(scope='session')
73def ydb_service_settings(pytestconfig) -> service.ServiceSettings:
74 endpoint_from_env = os.environ.get(
'YDB_ENDPOINT')
75 database = os.environ.get(
'YDB_DATABASE',
'local')
78 host, grpc_port = endpoint_from_env.split(
':', 1)
79 return service.ServiceSettings(
87 if pytestconfig.option.ydb_host:
88 return service.ServiceSettings(
89 host=pytestconfig.option.ydb_host,
90 grpc_port=pytestconfig.option.ydb_grpc_port,
91 mon_port=pytestconfig.option.ydb_mon_port,
92 ic_port=pytestconfig.option.ydb_ic_port,
95 return service.get_service_settings()
98@pytest.fixture(scope='session')
99def _ydb_service_schemas(service_source_dir):
100 service_schemas_ydb = service_source_dir /
'ydb' /
'schemas'
101 return discover.find_schemas([service_schemas_ydb])
104@pytest.fixture(scope='session')
105def ydb_settings_substitute(ydb_service_settings):
106 def secdist_settings(*args, **kwargs):
108 'endpoint':
'{}:{}'.format(
109 ydb_service_settings.host, ydb_service_settings.grpc_port,
111 'database':
'/{}'.format(ydb_service_settings.database),
115 return {
'ydb_settings': secdist_settings}
118@pytest.fixture(scope='session')
128@pytest.fixture(scope='session')
129def ydb_migration_dir(service_source_dir) -> pathlib.Path:
131 Directory with migration files
133 @ingroup userver_testsuite_fixtures
135 return service_source_dir /
'ydb' /
'migrations'
138YDB_MIGRATION_TABLE =
'goose_db_version'
141def _ydb_migrate(ydb_service_settings, ydb_migration_dir, goose_binary_path):
142 if not ydb_migration_dir.exists():
144 if not list(ydb_migration_dir.iterdir()):
147 host = ydb_service_settings.host
148 port = ydb_service_settings.grpc_port
151 str(goose_binary_path),
153 str(ydb_migration_dir),
158 f
'grpc://{host}:{port}/local?go_query_mode=scripting&'
159 '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, '
250 'which are mutually exclusive',
254 for schema_path
in _ydb_service_schemas:
255 with open(schema_path)
as fp:
256 tables_schemas = yaml.load(fp.read(), Loader=_YamlLoader)
257 for table_schema
in tables_schemas:
258 client.drop_table(_ydb_client, table_schema[
'path'])
259 client.create_table(_ydb_client, table_schema)
260 _ydb_state.tables.append(table_schema[
'path'])
263 _ydb_migrate(ydb_service_settings, ydb_migration_dir, goose_binary_path)
265 _ydb_state.init =
True
268@pytest.fixture(scope='session')
269def _ydb_tables(_ydb_state, _ydb_prepare, ydb_service_settings, ydb_cli):
272 *_ydb_fetch_table_names(ydb_service_settings, ydb_cli),
274 return tuple(sorted(tables))
282 ydb_service_settings,
288 def ydb_mark_queries(files=(), queries=()):
291 result_queries.append(load(path))
292 result_queries.extend(queries)
293 return result_queries
295 def drop_table(table):
296 with _ydb_client_pool()
as ydb_client:
297 ydb_client.execute(
'DELETE FROM `{}`'.format(table))
300 with concurrent.futures.ThreadPoolExecutor(
301 max_workers=len(_ydb_tables),
303 executer.map(drop_table, _ydb_tables)
305 for mark
in request.node.iter_markers(
'ydb'):
306 queries = ydb_mark_queries(**mark.kwargs)
307 for query
in queries:
308 _ydb_client.execute(query)
312def userver_ydb_trx(testpoint) -> sql.RegisteredTrx:
314 The fixture maintains transaction fault injection state using
317 @see pytest_userver.sql.RegisteredTrx
319 @snippet integration_tests/tests/test_trx_failure.py fault injection
321 @ingroup userver_testsuite_fixtures
324 registered = sql.RegisteredTrx()
326 @testpoint('ydb_trx_commit')
327 def _pg_trx_tp(data):
328 should_fail = registered.is_failure_enabled(data[
'trx_name'])
329 return {
'trx_should_fail': should_fail}
334@pytest.fixture(scope='session')
335def userver_config_ydb(ydb_service_settings):
337 Returns a function that adjusts the static configuration file for testsuite.
339 For all `ydb.databases`, sets `endpoint` and `database` to the local test
342 @ingroup userver_testsuite_fixtures
345 endpoint = f
'{ydb_service_settings.host}:{ydb_service_settings.grpc_port}'
347 '' if ydb_service_settings.database.startswith(
'/')
else '/'
348 ) + ydb_service_settings.database
350 def patch_config(config, config_vars):
351 ydb_component = config[
'components_manager'][
'components'][
'ydb']
352 if isinstance(ydb_component, str):
353 ydb_component = config_vars[ydb_component[1:]]
354 databases = ydb_component[
'databases']
355 for dbname, dbconfig
in databases.items():
356 dbconfig[
'endpoint'] = endpoint
357 dbconfig[
'database'] = database