We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Pytest ckan_config does not override configurations from test.ini
## CKAN version
2.9, master

## Describe the bug
By configuring some variable in test.ini like `ckan.plugins` reduces duplication in tests themselves. However if test requires some other variable like different plugins, using `ckan_config` decorator does not override the variable from test.ini

### Steps to reproduce
Create tests with ckan.plugins set to something in test.ini
Implement a test with decorator:
@pytest.mark.ckan_config('ckan.plugins', 'some_plugin')

### Expected behavior
Test should use plugin given in decorator and not in test.ini




--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `ckan/config/environment.py`
Content:
```
1 # encoding: utf-8
2 '''CKAN environment configuration'''
3 from __future__ import annotations
4 
5 import os
6 import logging
7 import warnings
8 import pytz
9 
10 from typing import Union, cast
11 
12 import sqlalchemy
13 import sqlalchemy.exc
14 
15 import ckan.model as model
16 import ckan.plugins as p
17 import ckan.lib.plugins as lib_plugins
18 import ckan.lib.helpers as helpers
19 import ckan.lib.app_globals as app_globals
20 from ckan.lib.redis import is_redis_available
21 import ckan.lib.search as search
22 import ckan.logic as logic
23 import ckan.authz as authz
24 from ckan.lib.webassets_tools import webassets_init
25 from ckan.lib.i18n import build_js_translations
26 
27 from ckan.common import CKANConfig, config, config_declaration
28 from ckan.exceptions import CkanConfigurationException
29 from ckan.types import Config
30 
31 log = logging.getLogger(__name__)
32 
33 # Suppress benign warning 'Unbuilt egg for setuptools'
34 warnings.simplefilter('ignore', UserWarning)
35 
36 
37 def load_environment(conf: Union[Config, CKANConfig]):
38     """
39     Configure the Pylons environment via the ``pylons.config`` object. This
40     code should only need to be run once.
41     """
42     os.environ['CKAN_CONFIG'] = cast(str, conf['__file__'])
43 
44     valid_base_public_folder_names = ['public', 'public-bs3']
45     static_files = conf.get('ckan.base_public_folder', 'public')
46     conf['ckan.base_public_folder'] = static_files
47 
48     if static_files not in valid_base_public_folder_names:
49         raise CkanConfigurationException(
50             'You provided an invalid value for ckan.base_public_folder. '
51             'Possible values are: "public" and "public-bs3".'
52         )
53 
54     log.info('Loading static files from %s' % static_files)
55 
56     # Initialize main CKAN config object
57     config.update(conf)
58 
59     # Setup the SQLAlchemy database engine
60     # Suppress a couple of sqlalchemy warnings
61     msgs = ['^Unicode type received non-unicode bind param value',
62             "^Did not recognize type 'BIGINT' of column 'size'",
63             "^Did not recognize type 'tsvector' of column 'search_vector'"
64             ]
65     for msg in msgs:
66         warnings.filterwarnings('ignore', msg, sqlalchemy.exc.SAWarning)
67 
68     # load all CKAN plugins
69     p.load_all()
70 
71     # Check Redis availability
72     if not is_redis_available():
73         log.critical('Could not connect to Redis.')
74 
75     app_globals.reset()
76 
77     # Build JavaScript translations. Must be done after plugins have
78     # been loaded.
79     build_js_translations()
80 
81 
82 # A mapping of config settings that can be overridden by env vars.
83 # Note: Do not remove the following lines, they are used in the docs
84 # Start CONFIG_FROM_ENV_VARS
85 CONFIG_FROM_ENV_VARS: dict[str, str] = {
86     'sqlalchemy.url': 'CKAN_SQLALCHEMY_URL',
87     'ckan.datastore.write_url': 'CKAN_DATASTORE_WRITE_URL',
88     'ckan.datastore.read_url': 'CKAN_DATASTORE_READ_URL',
89     'ckan.redis.url': 'CKAN_REDIS_URL',
90     'solr_url': 'CKAN_SOLR_URL',
91     'solr_user': 'CKAN_SOLR_USER',
92     'solr_password': 'CKAN_SOLR_PASSWORD',
93     'ckan.site_id': 'CKAN_SITE_ID',
94     'ckan.site_url': 'CKAN_SITE_URL',
95     'ckan.storage_path': 'CKAN_STORAGE_PATH',
96     'ckan.datapusher.url': 'CKAN_DATAPUSHER_URL',
97     'smtp.server': 'CKAN_SMTP_SERVER',
98     'smtp.starttls': 'CKAN_SMTP_STARTTLS',
99     'smtp.user': 'CKAN_SMTP_USER',
100     'smtp.password': 'CKAN_SMTP_PASSWORD',
101     'smtp.mail_from': 'CKAN_SMTP_MAIL_FROM',
102     'ckan.max_resource_size': 'CKAN_MAX_UPLOAD_SIZE_MB'
103 }
104 # End CONFIG_FROM_ENV_VARS
105 
106 
107 def update_config() -> None:
108     ''' This code needs to be run when the config is changed to take those
109     changes into account. It is called whenever a plugin is loaded as the
110     plugin might have changed the config values (for instance it might
111     change ckan.site_url) '''
112 
113     config_declaration.setup()
114     config_declaration.make_safe(config)
115     config_declaration.normalize(config)
116 
117     webassets_init()
118 
119     for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))):
120         # must do update in place as this does not work:
121         # config = plugin.update_config(config)
122         plugin.update_config(config)
123 
124     for option in CONFIG_FROM_ENV_VARS:
125         from_env = os.environ.get(CONFIG_FROM_ENV_VARS[option], None)
126         if from_env:
127             config[option] = from_env
128 
129     _, errors = config_declaration.validate(config)
130     if errors:
131         if config.get("config.mode") == "strict":
132             msg = "\n".join(
133                 "{}: {}".format(key, "; ".join(issues))
134                 for key, issues in errors.items()
135             )
136             msg = "Invalid configuration values provided:\n" + msg
137             raise CkanConfigurationException(msg)
138         else:
139             for key, issues in errors.items():
140                 log.warning(
141                     "Invalid value for %s (%s): %s",
142                     key,
143                     config.get(key),
144                     "; ".join(issues)
145                 )
146 
147     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
148 
149     site_url = config.get('ckan.site_url')
150     if not site_url:
151         raise RuntimeError(
152             'ckan.site_url is not configured and it must have a value.'
153             ' Please amend your .ini file.')
154     if not site_url.lower().startswith('http'):
155         raise RuntimeError(
156             'ckan.site_url should be a full URL, including the schema '
157             '(http or https)')
158     # Remove backslash from site_url if present
159     config['ckan.site_url'] = site_url.rstrip('/')
160 
161     display_timezone = config.get('ckan.display_timezone')
162     if (display_timezone and
163             display_timezone != 'server' and
164             display_timezone not in pytz.all_timezones):
165         raise CkanConfigurationException(
166             "ckan.display_timezone is not 'server' or a valid timezone"
167         )
168 
169     # Init SOLR settings and check if the schema is compatible
170     # from ckan.lib.search import SolrSettings, check_solr_schema_version
171 
172     # lib.search is imported here as we need the config enabled and parsed
173     search.SolrSettings.init(config.get('solr_url'),
174                              config.get('solr_user'),
175                              config.get('solr_password'))
176     search.check_solr_schema_version()
177 
178     lib_plugins.reset_package_plugins()
179     lib_plugins.register_package_plugins()
180     lib_plugins.reset_group_plugins()
181     lib_plugins.register_group_plugins()
182 
183     # initialise the globals
184     app_globals.app_globals._init()
185 
186     helpers.load_plugin_helpers()
187 
188     # Templates and CSS loading from configuration
189     valid_base_templates_folder_names = ['templates', 'templates-bs3']
190     templates = config.get('ckan.base_templates_folder')
191     config['ckan.base_templates_folder'] = templates
192 
193     if templates not in valid_base_templates_folder_names:
194         raise CkanConfigurationException(
195             'You provided an invalid value for ckan.base_templates_folder. '
196             'Possible values are: "templates" and "templates-bs3".'
197         )
198 
199     jinja2_templates_path = os.path.join(root, templates)
200     log.info('Loading templates from %s' % jinja2_templates_path)
201     template_paths = [jinja2_templates_path]
202 
203     extra_template_paths = config.get('extra_template_paths')
204     if 'plugin_template_paths' in config:
205         template_paths = config['plugin_template_paths'] + template_paths
206     if extra_template_paths:
207         # must be first for them to override defaults
208         template_paths = extra_template_paths.split(',') + template_paths
209     config['computed_template_paths'] = template_paths
210 
211     # Enable pessimistic disconnect handling (added in SQLAlchemy 1.2)
212     # to eliminate database errors due to stale pooled connections
213     config.setdefault('sqlalchemy.pool_pre_ping', True)
214     # Initialize SQLAlchemy
215     engine = sqlalchemy.engine_from_config(config)
216     model.init_model(engine)
217 
218     for plugin in p.PluginImplementations(p.IConfigurable):
219         plugin.configure(config)
220 
221     # clear other caches
222     logic.clear_actions_cache()
223     logic.clear_validators_cache()
224     authz.clear_auth_functions_cache()
225 
226     # Here we create the site user if they are not already in the database
227     try:
228         logic.get_action('get_site_user')({'ignore_auth': True}, {})
229     except (sqlalchemy.exc.ProgrammingError, sqlalchemy.exc.OperationalError):
230         # The database is not yet initialised. It happens in `ckan db init`
231         pass
232     except sqlalchemy.exc.IntegrityError:
233         # Race condition, user already exists.
234         pass
235 
236     # Close current session and open database connections to ensure a clean
237     # clean environment even if an error occurs later on
238     model.Session.remove()
239     model.Session.bind.dispose()
240
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/ckan/config/environment.py b/ckan/config/environment.py
--- a/ckan/config/environment.py
+++ b/ckan/config/environment.py
@@ -116,6 +116,14 @@
 
     webassets_init()
 
+    # these are collections of all template/public paths registered by
+    # extensions. Each call to `tk.add_template_directory` or
+    # `tk.add_public_directory` updates these collections. We have to reset
+    # them in order to remove templates/public files that came from plugins
+    # that were once enabled but are disabled right now.
+    config["plugin_template_paths"] = []
+    config["plugin_public_paths"] = []
+
     for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))):
         # must do update in place as this does not work:
         # config = plugin.update_config(config)

{"golden_diff": "diff --git a/ckan/config/environment.py b/ckan/config/environment.py\n--- a/ckan/config/environment.py\n+++ b/ckan/config/environment.py\n@@ -116,6 +116,14 @@\n \n     webassets_init()\n \n+    # these are collections of all template/public paths registered by\n+    # extensions. Each call to `tk.add_template_directory` or\n+    # `tk.add_public_directory` updates these collections. We have to reset\n+    # them in order to remove templates/public files that came from plugins\n+    # that were once enabled but are disabled right now.\n+    config[\"plugin_template_paths\"] = []\n+    config[\"plugin_public_paths\"] = []\n+\n     for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))):\n         # must do update in place as this does not work:\n         # config = plugin.update_config(config)\n", "issue": "Pytest ckan_config does not override configurations from test.ini\n## CKAN version\r\n2.9, master\r\n\r\n## Describe the bug\r\nBy configuring some variable in test.ini like `ckan.plugins` reduces duplication in tests themselves. However if test requires some other variable like different plugins, using `ckan_config` decorator does not override the variable from test.ini\r\n\r\n### Steps to reproduce\r\nCreate tests with ckan.plugins set to something in test.ini\r\nImplement a test with decorator:\r\n@pytest.mark.ckan_config('ckan.plugins', 'some_plugin')\r\n\r\n### Expected behavior\r\nTest should use plugin given in decorator and not in test.ini\r\n\r\n\r\n\n", "before_files": [{"content": "# encoding: utf-8\n'''CKAN environment configuration'''\nfrom __future__ import annotations\n\nimport os\nimport logging\nimport warnings\nimport pytz\n\nfrom typing import Union, cast\n\nimport sqlalchemy\nimport sqlalchemy.exc\n\nimport ckan.model as model\nimport ckan.plugins as p\nimport ckan.lib.plugins as lib_plugins\nimport ckan.lib.helpers as helpers\nimport ckan.lib.app_globals as app_globals\nfrom ckan.lib.redis import is_redis_available\nimport ckan.lib.search as search\nimport ckan.logic as logic\nimport ckan.authz as authz\nfrom ckan.lib.webassets_tools import webassets_init\nfrom ckan.lib.i18n import build_js_translations\n\nfrom ckan.common import CKANConfig, config, config_declaration\nfrom ckan.exceptions import CkanConfigurationException\nfrom ckan.types import Config\n\nlog = logging.getLogger(__name__)\n\n# Suppress benign warning 'Unbuilt egg for setuptools'\nwarnings.simplefilter('ignore', UserWarning)\n\n\ndef load_environment(conf: Union[Config, CKANConfig]):\n    \"\"\"\n    Configure the Pylons environment via the ``pylons.config`` object. This\n    code should only need to be run once.\n    \"\"\"\n    os.environ['CKAN_CONFIG'] = cast(str, conf['__file__'])\n\n    valid_base_public_folder_names = ['public', 'public-bs3']\n    static_files = conf.get('ckan.base_public_folder', 'public')\n    conf['ckan.base_public_folder'] = static_files\n\n    if static_files not in valid_base_public_folder_names:\n        raise CkanConfigurationException(\n            'You provided an invalid value for ckan.base_public_folder. '\n            'Possible values are: \"public\" and \"public-bs3\".'\n        )\n\n    log.info('Loading static files from %s' % static_files)\n\n    # Initialize main CKAN config object\n    config.update(conf)\n\n    # Setup the SQLAlchemy database engine\n    # Suppress a couple of sqlalchemy warnings\n    msgs = ['^Unicode type received non-unicode bind param value',\n            \"^Did not recognize type 'BIGINT' of column 'size'\",\n            \"^Did not recognize type 'tsvector' of column 'search_vector'\"\n            ]\n    for msg in msgs:\n        warnings.filterwarnings('ignore', msg, sqlalchemy.exc.SAWarning)\n\n    # load all CKAN plugins\n    p.load_all()\n\n    # Check Redis availability\n    if not is_redis_available():\n        log.critical('Could not connect to Redis.')\n\n    app_globals.reset()\n\n    # Build JavaScript translations. Must be done after plugins have\n    # been loaded.\n    build_js_translations()\n\n\n# A mapping of config settings that can be overridden by env vars.\n# Note: Do not remove the following lines, they are used in the docs\n# Start CONFIG_FROM_ENV_VARS\nCONFIG_FROM_ENV_VARS: dict[str, str] = {\n    'sqlalchemy.url': 'CKAN_SQLALCHEMY_URL',\n    'ckan.datastore.write_url': 'CKAN_DATASTORE_WRITE_URL',\n    'ckan.datastore.read_url': 'CKAN_DATASTORE_READ_URL',\n    'ckan.redis.url': 'CKAN_REDIS_URL',\n    'solr_url': 'CKAN_SOLR_URL',\n    'solr_user': 'CKAN_SOLR_USER',\n    'solr_password': 'CKAN_SOLR_PASSWORD',\n    'ckan.site_id': 'CKAN_SITE_ID',\n    'ckan.site_url': 'CKAN_SITE_URL',\n    'ckan.storage_path': 'CKAN_STORAGE_PATH',\n    'ckan.datapusher.url': 'CKAN_DATAPUSHER_URL',\n    'smtp.server': 'CKAN_SMTP_SERVER',\n    'smtp.starttls': 'CKAN_SMTP_STARTTLS',\n    'smtp.user': 'CKAN_SMTP_USER',\n    'smtp.password': 'CKAN_SMTP_PASSWORD',\n    'smtp.mail_from': 'CKAN_SMTP_MAIL_FROM',\n    'ckan.max_resource_size': 'CKAN_MAX_UPLOAD_SIZE_MB'\n}\n# End CONFIG_FROM_ENV_VARS\n\n\ndef update_config() -> None:\n    ''' This code needs to be run when the config is changed to take those\n    changes into account. It is called whenever a plugin is loaded as the\n    plugin might have changed the config values (for instance it might\n    change ckan.site_url) '''\n\n    config_declaration.setup()\n    config_declaration.make_safe(config)\n    config_declaration.normalize(config)\n\n    webassets_init()\n\n    for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))):\n        # must do update in place as this does not work:\n        # config = plugin.update_config(config)\n        plugin.update_config(config)\n\n    for option in CONFIG_FROM_ENV_VARS:\n        from_env = os.environ.get(CONFIG_FROM_ENV_VARS[option], None)\n        if from_env:\n            config[option] = from_env\n\n    _, errors = config_declaration.validate(config)\n    if errors:\n        if config.get(\"config.mode\") == \"strict\":\n            msg = \"\\n\".join(\n                \"{}: {}\".format(key, \"; \".join(issues))\n                for key, issues in errors.items()\n            )\n            msg = \"Invalid configuration values provided:\\n\" + msg\n            raise CkanConfigurationException(msg)\n        else:\n            for key, issues in errors.items():\n                log.warning(\n                    \"Invalid value for %s (%s): %s\",\n                    key,\n                    config.get(key),\n                    \"; \".join(issues)\n                )\n\n    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n    site_url = config.get('ckan.site_url')\n    if not site_url:\n        raise RuntimeError(\n            'ckan.site_url is not configured and it must have a value.'\n            ' Please amend your .ini file.')\n    if not site_url.lower().startswith('http'):\n        raise RuntimeError(\n            'ckan.site_url should be a full URL, including the schema '\n            '(http or https)')\n    # Remove backslash from site_url if present\n    config['ckan.site_url'] = site_url.rstrip('/')\n\n    display_timezone = config.get('ckan.display_timezone')\n    if (display_timezone and\n            display_timezone != 'server' and\n            display_timezone not in pytz.all_timezones):\n        raise CkanConfigurationException(\n            \"ckan.display_timezone is not 'server' or a valid timezone\"\n        )\n\n    # Init SOLR settings and check if the schema is compatible\n    # from ckan.lib.search import SolrSettings, check_solr_schema_version\n\n    # lib.search is imported here as we need the config enabled and parsed\n    search.SolrSettings.init(config.get('solr_url'),\n                             config.get('solr_user'),\n                             config.get('solr_password'))\n    search.check_solr_schema_version()\n\n    lib_plugins.reset_package_plugins()\n    lib_plugins.register_package_plugins()\n    lib_plugins.reset_group_plugins()\n    lib_plugins.register_group_plugins()\n\n    # initialise the globals\n    app_globals.app_globals._init()\n\n    helpers.load_plugin_helpers()\n\n    # Templates and CSS loading from configuration\n    valid_base_templates_folder_names = ['templates', 'templates-bs3']\n    templates = config.get('ckan.base_templates_folder')\n    config['ckan.base_templates_folder'] = templates\n\n    if templates not in valid_base_templates_folder_names:\n        raise CkanConfigurationException(\n            'You provided an invalid value for ckan.base_templates_folder. '\n            'Possible values are: \"templates\" and \"templates-bs3\".'\n        )\n\n    jinja2_templates_path = os.path.join(root, templates)\n    log.info('Loading templates from %s' % jinja2_templates_path)\n    template_paths = [jinja2_templates_path]\n\n    extra_template_paths = config.get('extra_template_paths')\n    if 'plugin_template_paths' in config:\n        template_paths = config['plugin_template_paths'] + template_paths\n    if extra_template_paths:\n        # must be first for them to override defaults\n        template_paths = extra_template_paths.split(',') + template_paths\n    config['computed_template_paths'] = template_paths\n\n    # Enable pessimistic disconnect handling (added in SQLAlchemy 1.2)\n    # to eliminate database errors due to stale pooled connections\n    config.setdefault('sqlalchemy.pool_pre_ping', True)\n    # Initialize SQLAlchemy\n    engine = sqlalchemy.engine_from_config(config)\n    model.init_model(engine)\n\n    for plugin in p.PluginImplementations(p.IConfigurable):\n        plugin.configure(config)\n\n    # clear other caches\n    logic.clear_actions_cache()\n    logic.clear_validators_cache()\n    authz.clear_auth_functions_cache()\n\n    # Here we create the site user if they are not already in the database\n    try:\n        logic.get_action('get_site_user')({'ignore_auth': True}, {})\n    except (sqlalchemy.exc.ProgrammingError, sqlalchemy.exc.OperationalError):\n        # The database is not yet initialised. It happens in `ckan db init`\n        pass\n    except sqlalchemy.exc.IntegrityError:\n        # Race condition, user already exists.\n        pass\n\n    # Close current session and open database connections to ensure a clean\n    # clean environment even if an error occurs later on\n    model.Session.remove()\n    model.Session.bind.dispose()\n", "path": "ckan/config/environment.py"}], "after_files": [{"content": "# encoding: utf-8\n'''CKAN environment configuration'''\nfrom __future__ import annotations\n\nimport os\nimport logging\nimport warnings\nimport pytz\n\nfrom typing import Union, cast\n\nimport sqlalchemy\nimport sqlalchemy.exc\n\nimport ckan.model as model\nimport ckan.plugins as p\nimport ckan.lib.plugins as lib_plugins\nimport ckan.lib.helpers as helpers\nimport ckan.lib.app_globals as app_globals\nfrom ckan.lib.redis import is_redis_available\nimport ckan.lib.search as search\nimport ckan.logic as logic\nimport ckan.authz as authz\nfrom ckan.lib.webassets_tools import webassets_init\nfrom ckan.lib.i18n import build_js_translations\n\nfrom ckan.common import CKANConfig, config, config_declaration\nfrom ckan.exceptions import CkanConfigurationException\nfrom ckan.types import Config\n\nlog = logging.getLogger(__name__)\n\n# Suppress benign warning 'Unbuilt egg for setuptools'\nwarnings.simplefilter('ignore', UserWarning)\n\n\ndef load_environment(conf: Union[Config, CKANConfig]):\n    \"\"\"\n    Configure the Pylons environment via the ``pylons.config`` object. This\n    code should only need to be run once.\n    \"\"\"\n    os.environ['CKAN_CONFIG'] = cast(str, conf['__file__'])\n\n    valid_base_public_folder_names = ['public', 'public-bs3']\n    static_files = conf.get('ckan.base_public_folder', 'public')\n    conf['ckan.base_public_folder'] = static_files\n\n    if static_files not in valid_base_public_folder_names:\n        raise CkanConfigurationException(\n            'You provided an invalid value for ckan.base_public_folder. '\n            'Possible values are: \"public\" and \"public-bs3\".'\n        )\n\n    log.info('Loading static files from %s' % static_files)\n\n    # Initialize main CKAN config object\n    config.update(conf)\n\n    # Setup the SQLAlchemy database engine\n    # Suppress a couple of sqlalchemy warnings\n    msgs = ['^Unicode type received non-unicode bind param value',\n            \"^Did not recognize type 'BIGINT' of column 'size'\",\n            \"^Did not recognize type 'tsvector' of column 'search_vector'\"\n            ]\n    for msg in msgs:\n        warnings.filterwarnings('ignore', msg, sqlalchemy.exc.SAWarning)\n\n    # load all CKAN plugins\n    p.load_all()\n\n    # Check Redis availability\n    if not is_redis_available():\n        log.critical('Could not connect to Redis.')\n\n    app_globals.reset()\n\n    # Build JavaScript translations. Must be done after plugins have\n    # been loaded.\n    build_js_translations()\n\n\n# A mapping of config settings that can be overridden by env vars.\n# Note: Do not remove the following lines, they are used in the docs\n# Start CONFIG_FROM_ENV_VARS\nCONFIG_FROM_ENV_VARS: dict[str, str] = {\n    'sqlalchemy.url': 'CKAN_SQLALCHEMY_URL',\n    'ckan.datastore.write_url': 'CKAN_DATASTORE_WRITE_URL',\n    'ckan.datastore.read_url': 'CKAN_DATASTORE_READ_URL',\n    'ckan.redis.url': 'CKAN_REDIS_URL',\n    'solr_url': 'CKAN_SOLR_URL',\n    'solr_user': 'CKAN_SOLR_USER',\n    'solr_password': 'CKAN_SOLR_PASSWORD',\n    'ckan.site_id': 'CKAN_SITE_ID',\n    'ckan.site_url': 'CKAN_SITE_URL',\n    'ckan.storage_path': 'CKAN_STORAGE_PATH',\n    'ckan.datapusher.url': 'CKAN_DATAPUSHER_URL',\n    'smtp.server': 'CKAN_SMTP_SERVER',\n    'smtp.starttls': 'CKAN_SMTP_STARTTLS',\n    'smtp.user': 'CKAN_SMTP_USER',\n    'smtp.password': 'CKAN_SMTP_PASSWORD',\n    'smtp.mail_from': 'CKAN_SMTP_MAIL_FROM',\n    'ckan.max_resource_size': 'CKAN_MAX_UPLOAD_SIZE_MB'\n}\n# End CONFIG_FROM_ENV_VARS\n\n\ndef update_config() -> None:\n    ''' This code needs to be run when the config is changed to take those\n    changes into account. It is called whenever a plugin is loaded as the\n    plugin might have changed the config values (for instance it might\n    change ckan.site_url) '''\n\n    config_declaration.setup()\n    config_declaration.make_safe(config)\n    config_declaration.normalize(config)\n\n    webassets_init()\n\n    # these are collections of all template/public paths registered by\n    # extensions. Each call to `tk.add_template_directory` or\n    # `tk.add_public_directory` updates these collections. We have to reset\n    # them in order to remove templates/public files that came from plugins\n    # that were once enabled but are disabled right now.\n    config[\"plugin_template_paths\"] = []\n    config[\"plugin_public_paths\"] = []\n\n    for plugin in reversed(list(p.PluginImplementations(p.IConfigurer))):\n        # must do update in place as this does not work:\n        # config = plugin.update_config(config)\n        plugin.update_config(config)\n\n    for option in CONFIG_FROM_ENV_VARS:\n        from_env = os.environ.get(CONFIG_FROM_ENV_VARS[option], None)\n        if from_env:\n            config[option] = from_env\n\n    _, errors = config_declaration.validate(config)\n    if errors:\n        if config.get(\"config.mode\") == \"strict\":\n            msg = \"\\n\".join(\n                \"{}: {}\".format(key, \"; \".join(issues))\n                for key, issues in errors.items()\n            )\n            msg = \"Invalid configuration values provided:\\n\" + msg\n            raise CkanConfigurationException(msg)\n        else:\n            for key, issues in errors.items():\n                log.warning(\n                    \"Invalid value for %s (%s): %s\",\n                    key,\n                    config.get(key),\n                    \"; \".join(issues)\n                )\n\n    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n    site_url = config.get('ckan.site_url')\n    if not site_url:\n        raise RuntimeError(\n            'ckan.site_url is not configured and it must have a value.'\n            ' Please amend your .ini file.')\n    if not site_url.lower().startswith('http'):\n        raise RuntimeError(\n            'ckan.site_url should be a full URL, including the schema '\n            '(http or https)')\n    # Remove backslash from site_url if present\n    config['ckan.site_url'] = site_url.rstrip('/')\n\n    display_timezone = config.get('ckan.display_timezone')\n    if (display_timezone and\n            display_timezone != 'server' and\n            display_timezone not in pytz.all_timezones):\n        raise CkanConfigurationException(\n            \"ckan.display_timezone is not 'server' or a valid timezone\"\n        )\n\n    # Init SOLR settings and check if the schema is compatible\n    # from ckan.lib.search import SolrSettings, check_solr_schema_version\n\n    # lib.search is imported here as we need the config enabled and parsed\n    search.SolrSettings.init(config.get('solr_url'),\n                             config.get('solr_user'),\n                             config.get('solr_password'))\n    search.check_solr_schema_version()\n\n    lib_plugins.reset_package_plugins()\n    lib_plugins.register_package_plugins()\n    lib_plugins.reset_group_plugins()\n    lib_plugins.register_group_plugins()\n\n    # initialise the globals\n    app_globals.app_globals._init()\n\n    helpers.load_plugin_helpers()\n\n    # Templates and CSS loading from configuration\n    valid_base_templates_folder_names = ['templates', 'templates-bs3']\n    templates = config.get('ckan.base_templates_folder')\n    config['ckan.base_templates_folder'] = templates\n\n    if templates not in valid_base_templates_folder_names:\n        raise CkanConfigurationException(\n            'You provided an invalid value for ckan.base_templates_folder. '\n            'Possible values are: \"templates\" and \"templates-bs3\".'\n        )\n\n    jinja2_templates_path = os.path.join(root, templates)\n    log.info('Loading templates from %s' % jinja2_templates_path)\n    template_paths = [jinja2_templates_path]\n\n    extra_template_paths = config.get('extra_template_paths')\n    if 'plugin_template_paths' in config:\n        template_paths = config['plugin_template_paths'] + template_paths\n    if extra_template_paths:\n        # must be first for them to override defaults\n        template_paths = extra_template_paths.split(',') + template_paths\n    config['computed_template_paths'] = template_paths\n\n    # Enable pessimistic disconnect handling (added in SQLAlchemy 1.2)\n    # to eliminate database errors due to stale pooled connections\n    config.setdefault('sqlalchemy.pool_pre_ping', True)\n    # Initialize SQLAlchemy\n    engine = sqlalchemy.engine_from_config(config)\n    model.init_model(engine)\n\n    for plugin in p.PluginImplementations(p.IConfigurable):\n        plugin.configure(config)\n\n    # clear other caches\n    logic.clear_actions_cache()\n    logic.clear_validators_cache()\n    authz.clear_auth_functions_cache()\n\n    # Here we create the site user if they are not already in the database\n    try:\n        logic.get_action('get_site_user')({'ignore_auth': True}, {})\n    except (sqlalchemy.exc.ProgrammingError, sqlalchemy.exc.OperationalError):\n        # The database is not yet initialised. It happens in `ckan db init`\n        pass\n    except sqlalchemy.exc.IntegrityError:\n        # Race condition, user already exists.\n        pass\n\n    # Close current session and open database connections to ensure a clean\n    # clean environment even if an error occurs later on\n    model.Session.remove()\n    model.Session.bind.dispose()\n", "path": "ckan/config/environment.py"}]}