userver: /data/code/service_template/third_party/userver/testsuite/pytest_plugins/pytest_userver/plugins/postgresql.py Source File
⚠️ This is the documentation for an old userver version. Click here to switch to the latest version.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
postgresql.py
1"""
2Plugin that imports the required fixtures to start the database
3and adjusts the PostgreSQL "dbconnection" static config value.
4"""
5
6import pytest
7
8
9pytest_plugins = [
10 'testsuite.databases.pgsql.pytest_plugin',
11 'pytest_userver.plugins.core',
12]
13
14
15USERVER_CONFIG_HOOKS = ['userver_pg_config']
16
17
18@pytest.fixture(scope='session')
19def userver_pg_config(pgsql_local):
20 """
21 Returns a function that adjusts the static configuration file for
22 the testsuite.
23 Sets the `dbconnection` to the testsuite started PostgreSQL credentials
24 if there's only one `dbconnection` in static config.
25
26 @ingroup userver_testsuite_fixtures
27 """
28
29 if not pgsql_local:
30 raise ValueError(
31 'Override the "pgsql_local" fixture so that testsuite knowns how '
32 'to start the PostgreSQL database',
33 )
34
35 if len(pgsql_local) > 1:
36 raise ValueError(
37 f'Found more than one entry in "pgsql_local": '
38 f'{list(pgsql_local.keys())}. '
39 f'The "userver_pg_config" fixture supports '
40 f'only one entry in "pgsql_local" fixture. The '
41 f'"userver_pg_config" fixture should be overridden and '
42 f'the "dbconnection" for the components::Postgres '
43 f'components should be adjusted via the overridden fixture.',
44 )
45
46 uri = list(pgsql_local.values())[0].get_uri()
47
48 def _patch_config(config_yaml, config_vars):
49 components = config_yaml['components_manager']['components']
50 postgre_dbs = {
51 name: params
52 for name, params in components.items()
53 if params and 'dbconnection' in params
54 }
55
56 if len(postgre_dbs) > 1:
57 raise ValueError(
58 f'Found more than one components with "dbconnection": '
59 f'{list(postgre_dbs.keys())}. '
60 f'The "userver_pg_config" fixture should be overridden and '
61 f'the "dbconnection" for the components::Postgres '
62 f'components should be adjusted via the overridden fixture.',
63 )
64
65 for config in postgre_dbs.values():
66 config['dbconnection'] = uri
67 config.pop('dbalias', None)
68
69 return _patch_config