userver: /data/code/service_template/third_party/userver/testsuite/pytest_plugins/pytest_userver/plugins/postgresql.py Source File
Loading...
Searching...
No Matches
postgresql.py
1"""
2Plugin that imports the required fixtures to start the database
3and adjusts the PostgreSQL "dbconnection" static config value.
4"""
5
6import typing
7
8import pytest
9
10from pytest_userver import sql
11
12
13pytest_plugins = [
14 'testsuite.databases.pgsql.pytest_plugin',
15 'pytest_userver.plugins.core',
16]
17
18
19USERVER_CONFIG_HOOKS = ['userver_pg_config']
20
21
22@pytest.fixture(scope='session')
23def userver_pg_config(pgsql_local):
24 """
25 Returns a function that adjusts the static configuration file for
26 the testsuite.
27 Sets the `dbconnection` to the testsuite started PostgreSQL credentials
28 if there's only one `dbconnection` in static config.
29
30 @ingroup userver_testsuite_fixtures
31 """
32
33 if not pgsql_local:
34 raise ValueError(
35 'Override the "pgsql_local" fixture so that testsuite knowns how '
36 'to start the PostgreSQL database',
37 )
38
39 if len(pgsql_local) > 1:
40 raise ValueError(
41 f'Found more than one entry in "pgsql_local": '
42 f'{list(pgsql_local.keys())}. '
43 f'The "userver_pg_config" fixture supports '
44 f'only one entry in "pgsql_local" fixture. The '
45 f'"userver_pg_config" fixture should be overridden and '
46 f'the "dbconnection" for the components::Postgres '
47 f'components should be adjusted via the overridden fixture.',
48 )
49
50 uri = list(pgsql_local.values())[0].get_uri()
51
52 def _patch_config(config_yaml, config_vars):
53 components = config_yaml['components_manager']['components']
54 postgre_dbs = {
55 name: params
56 for name, params in components.items()
57 if params
58 and ('dbconnection' in params or 'dbconnection#env' in params)
59 }
60
61 if len(postgre_dbs) > 1:
62 raise ValueError(
63 f'Found more than one components with "dbconnection": '
64 f'{list(postgre_dbs.keys())}. '
65 f'The "userver_pg_config" fixture should be overridden and '
66 f'the "dbconnection" for the components::Postgres '
67 f'components should be adjusted via the overridden fixture.',
68 )
69
70 for config in postgre_dbs.values():
71 config['dbconnection'] = uri
72 config.pop('dbalias', None)
73
74 return _patch_config
75
76
77@pytest.fixture
79 testpoint,
80) -> typing.Generator[sql.RegisteredTrx, None, None]:
81 """
82 The fixture maintains transaction fault injection state using
83 RegisteredTrx class.
84
85 @see pytest_userver.sql.RegisteredTrx
86
87 @snippet postgresql/functional_tests/integration_tests/tests/test_trx_failure.py fault injection
88
89 @ingroup userver_testsuite_fixtures
90 """ # noqa: E501
91
92 registered = sql.RegisteredTrx()
93
94 @testpoint('pg_trx_commit')
95 def _pg_trx_tp(data):
96 should_fail = registered.is_failure_enabled(data['trx_name'])
97 return {'trx_should_fail': should_fail}
98
99 yield registered