1 # SPDX-License-Identifier: GPL-2.0-only
 
   3 # This file is part of Nominatim. (https://nominatim.org)
 
   5 # Copyright (C) 2022 by the Nominatim developer community.
 
   6 # For a full list of authors see the git log.
 
   8 Test for loading dotenv configuration.
 
  10 from pathlib import Path
 
  13 from nominatim.config import Configuration, flatten_config_list
 
  14 from nominatim.errors import UsageError
 
  17 def make_config(src_dir):
 
  18     """ Create a configuration object from the given project directory.
 
  20     def _mk_config(project_dir=None):
 
  21         return Configuration(project_dir, src_dir / 'settings')
 
  26 def make_config_path(src_dir, tmp_path):
 
  27     """ Create a configuration object with project and config directories
 
  28         in a temporary directory.
 
  31         (tmp_path / 'project').mkdir()
 
  32         (tmp_path / 'config').mkdir()
 
  33         conf = Configuration(tmp_path / 'project', src_dir / 'settings')
 
  34         conf.config_dir = tmp_path / 'config'
 
  40 def test_no_project_dir(make_config):
 
  41     config = make_config()
 
  43     assert config.DATABASE_WEBUSER == 'www-data'
 
  46 @pytest.mark.parametrize("val", ('apache', '"apache"'))
 
  47 def test_prefer_project_setting_over_default(make_config, val, tmp_path):
 
  48     envfile = tmp_path / '.env'
 
  49     envfile.write_text('NOMINATIM_DATABASE_WEBUSER={}\n'.format(val))
 
  51     config = make_config(tmp_path)
 
  53     assert config.DATABASE_WEBUSER == 'apache'
 
  56 def test_prefer_os_environ_over_project_setting(make_config, monkeypatch, tmp_path):
 
  57     envfile = tmp_path / '.env'
 
  58     envfile.write_text('NOMINATIM_DATABASE_WEBUSER=apache\n')
 
  60     monkeypatch.setenv('NOMINATIM_DATABASE_WEBUSER', 'nobody')
 
  62     config = make_config(tmp_path)
 
  64     assert config.DATABASE_WEBUSER == 'nobody'
 
  67 def test_prefer_os_environ_can_unset_project_setting(make_config, monkeypatch, tmp_path):
 
  68     envfile = tmp_path / '.env'
 
  69     envfile.write_text('NOMINATIM_DATABASE_WEBUSER=apache\n')
 
  71     monkeypatch.setenv('NOMINATIM_DATABASE_WEBUSER', '')
 
  73     config = make_config(tmp_path)
 
  75     assert config.DATABASE_WEBUSER == ''
 
  78 def test_get_os_env_add_defaults(make_config, monkeypatch):
 
  79     config = make_config()
 
  81     monkeypatch.delenv('NOMINATIM_DATABASE_WEBUSER', raising=False)
 
  83     assert config.get_os_env()['NOMINATIM_DATABASE_WEBUSER'] == 'www-data'
 
  86 def test_get_os_env_prefer_os_environ(make_config, monkeypatch):
 
  87     config = make_config()
 
  89     monkeypatch.setenv('NOMINATIM_DATABASE_WEBUSER', 'nobody')
 
  91     assert config.get_os_env()['NOMINATIM_DATABASE_WEBUSER'] == 'nobody'
 
  94 def test_get_libpq_dsn_convert_default(make_config):
 
  95     config = make_config()
 
  97     assert config.get_libpq_dsn() == 'dbname=nominatim'
 
 100 def test_get_libpq_dsn_convert_php(make_config, monkeypatch):
 
 101     config = make_config()
 
 103     monkeypatch.setenv('NOMINATIM_DATABASE_DSN',
 
 104                        'pgsql:dbname=gis;password=foo;host=localhost')
 
 106     assert config.get_libpq_dsn() == 'dbname=gis password=foo host=localhost'
 
 109 @pytest.mark.parametrize("val,expect", [('foo bar', "'foo bar'"),
 
 112 def test_get_libpq_dsn_convert_php_special_chars(make_config, monkeypatch, val, expect):
 
 113     config = make_config()
 
 115     monkeypatch.setenv('NOMINATIM_DATABASE_DSN',
 
 116                        'pgsql:dbname=gis;password={}'.format(val))
 
 118     assert config.get_libpq_dsn() == "dbname=gis password={}".format(expect)
 
 121 def test_get_libpq_dsn_convert_libpq(make_config, monkeypatch):
 
 122     config = make_config()
 
 124     monkeypatch.setenv('NOMINATIM_DATABASE_DSN',
 
 125                        'host=localhost dbname=gis password=foo')
 
 127     assert config.get_libpq_dsn() == 'host=localhost dbname=gis password=foo'
 
 130 @pytest.mark.parametrize("value,result",
 
 131                          [(x, True) for x in ('1', 'true', 'True', 'yes', 'YES')] +
 
 132                          [(x, False) for x in ('0', 'false', 'no', 'NO', 'x')])
 
 133 def test_get_bool(make_config, monkeypatch, value, result):
 
 134     config = make_config()
 
 136     monkeypatch.setenv('NOMINATIM_FOOBAR', value)
 
 138     assert config.get_bool('FOOBAR') == result
 
 140 def test_get_bool_empty(make_config):
 
 141     config = make_config()
 
 143     assert config.DATABASE_MODULE_PATH == ''
 
 144     assert not config.get_bool('DATABASE_MODULE_PATH')
 
 147 @pytest.mark.parametrize("value,result", [('0', 0), ('1', 1),
 
 148                                           ('85762513444', 85762513444)])
 
 149 def test_get_int_success(make_config, monkeypatch, value, result):
 
 150     config = make_config()
 
 152     monkeypatch.setenv('NOMINATIM_FOOBAR', value)
 
 154     assert config.get_int('FOOBAR') == result
 
 157 @pytest.mark.parametrize("value", ['1b', 'fg', '0x23'])
 
 158 def test_get_int_bad_values(make_config, monkeypatch, value):
 
 159     config = make_config()
 
 161     monkeypatch.setenv('NOMINATIM_FOOBAR', value)
 
 163     with pytest.raises(UsageError):
 
 164         config.get_int('FOOBAR')
 
 167 def test_get_int_empty(make_config):
 
 168     config = make_config()
 
 170     assert config.DATABASE_MODULE_PATH == ''
 
 172     with pytest.raises(UsageError):
 
 173         config.get_int('DATABASE_MODULE_PATH')
 
 176 def test_get_path_empty(make_config):
 
 177     config = make_config()
 
 179     assert config.DATABASE_MODULE_PATH == ''
 
 180     assert not config.get_path('DATABASE_MODULE_PATH')
 
 183 def test_get_path_absolute(make_config, monkeypatch):
 
 184     config = make_config()
 
 186     monkeypatch.setenv('NOMINATIM_FOOBAR', '/dont/care')
 
 187     result = config.get_path('FOOBAR')
 
 189     assert isinstance(result, Path)
 
 190     assert str(result) == '/dont/care'
 
 193 def test_get_path_relative(make_config, monkeypatch, tmp_path):
 
 194     config = make_config(tmp_path)
 
 196     monkeypatch.setenv('NOMINATIM_FOOBAR', 'an/oyster')
 
 197     result = config.get_path('FOOBAR')
 
 199     assert isinstance(result, Path)
 
 200     assert str(result) == str(tmp_path / 'an/oyster')
 
 203 def test_get_import_style_intern(make_config, src_dir, monkeypatch):
 
 204     config = make_config()
 
 206     monkeypatch.setenv('NOMINATIM_IMPORT_STYLE', 'street')
 
 208     expected = src_dir / 'settings' / 'import-street.style'
 
 210     assert config.get_import_style_file() == expected
 
 213 def test_get_import_style_extern_relative(make_config_path, monkeypatch):
 
 214     config = make_config_path()
 
 215     (config.project_dir / 'custom.style').write_text('x')
 
 217     monkeypatch.setenv('NOMINATIM_IMPORT_STYLE', 'custom.style')
 
 219     assert str(config.get_import_style_file()) == str(config.project_dir / 'custom.style')
 
 222 def test_get_import_style_extern_absolute(make_config, tmp_path, monkeypatch):
 
 223     config = make_config()
 
 224     cfgfile = tmp_path / 'test.style'
 
 226     cfgfile.write_text('x')
 
 228     monkeypatch.setenv('NOMINATIM_IMPORT_STYLE', str(cfgfile))
 
 230     assert str(config.get_import_style_file()) == str(cfgfile)
 
 233 def test_load_subconf_from_project_dir(make_config_path):
 
 234     config = make_config_path()
 
 236     testfile = config.project_dir / 'test.yaml'
 
 237     testfile.write_text('cow: muh\ncat: miau\n')
 
 239     testfile = config.config_dir / 'test.yaml'
 
 240     testfile.write_text('cow: miau\ncat: muh\n')
 
 242     rules = config.load_sub_configuration('test.yaml')
 
 244     assert rules == dict(cow='muh', cat='miau')
 
 247 def test_load_subconf_from_settings_dir(make_config_path):
 
 248     config = make_config_path()
 
 250     testfile = config.config_dir / 'test.yaml'
 
 251     testfile.write_text('cow: muh\ncat: miau\n')
 
 253     rules = config.load_sub_configuration('test.yaml')
 
 255     assert rules == dict(cow='muh', cat='miau')
 
 258 def test_load_subconf_empty_env_conf(make_config_path, monkeypatch):
 
 259     monkeypatch.setenv('NOMINATIM_MY_CONFIG', '')
 
 260     config = make_config_path()
 
 262     testfile = config.config_dir / 'test.yaml'
 
 263     testfile.write_text('cow: muh\ncat: miau\n')
 
 265     rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 267     assert rules == dict(cow='muh', cat='miau')
 
 270 def test_load_subconf_env_absolute_found(make_config_path, monkeypatch, tmp_path):
 
 271     monkeypatch.setenv('NOMINATIM_MY_CONFIG', str(tmp_path / 'other.yaml'))
 
 272     config = make_config_path()
 
 274     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
 
 275     (tmp_path / 'other.yaml').write_text('dog: muh\nfrog: miau\n')
 
 277     rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 279     assert rules == dict(dog='muh', frog='miau')
 
 282 def test_load_subconf_env_absolute_not_found(make_config_path, monkeypatch, tmp_path):
 
 283     monkeypatch.setenv('NOMINATIM_MY_CONFIG', str(tmp_path / 'other.yaml'))
 
 284     config = make_config_path()
 
 286     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
 
 288     with pytest.raises(UsageError, match='Config file not found.'):
 
 289         rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 292 @pytest.mark.parametrize("location", ['project_dir', 'config_dir'])
 
 293 def test_load_subconf_env_relative_found(make_config_path, monkeypatch, location):
 
 294     monkeypatch.setenv('NOMINATIM_MY_CONFIG', 'other.yaml')
 
 295     config = make_config_path()
 
 297     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
 
 298     (getattr(config, location) / 'other.yaml').write_text('dog: bark\n')
 
 300     rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 302     assert rules == dict(dog='bark')
 
 305 def test_load_subconf_env_relative_not_found(make_config_path, monkeypatch):
 
 306     monkeypatch.setenv('NOMINATIM_MY_CONFIG', 'other.yaml')
 
 307     config = make_config_path()
 
 309     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
 
 311     with pytest.raises(UsageError, match='Config file not found.'):
 
 312         rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 315 def test_load_subconf_json(make_config_path):
 
 316     config = make_config_path()
 
 318     (config.project_dir / 'test.json').write_text('{"cow": "muh", "cat": "miau"}')
 
 320     rules = config.load_sub_configuration('test.json')
 
 322     assert rules == dict(cow='muh', cat='miau')
 
 324 def test_load_subconf_not_found(make_config_path):
 
 325     config = make_config_path()
 
 327     with pytest.raises(UsageError, match='Config file not found.'):
 
 328         config.load_sub_configuration('test.yaml')
 
 331 def test_load_subconf_env_unknown_format(make_config_path):
 
 332     config = make_config_path()
 
 334     (config.project_dir / 'test.xml').write_text('<html></html>')
 
 336     with pytest.raises(UsageError, match='unknown format'):
 
 337         config.load_sub_configuration('test.xml')
 
 340 def test_load_subconf_include_absolute(make_config_path, tmp_path):
 
 341     config = make_config_path()
 
 343     testfile = config.config_dir / 'test.yaml'
 
 344     testfile.write_text(f'base: !include {tmp_path}/inc.yaml\n')
 
 345     (tmp_path / 'inc.yaml').write_text('first: 1\nsecond: 2\n')
 
 347     rules = config.load_sub_configuration('test.yaml')
 
 349     assert rules == dict(base=dict(first=1, second=2))
 
 352 @pytest.mark.parametrize("location", ['project_dir', 'config_dir'])
 
 353 def test_load_subconf_include_relative(make_config_path, tmp_path, location):
 
 354     config = make_config_path()
 
 356     testfile = config.config_dir / 'test.yaml'
 
 357     testfile.write_text(f'base: !include inc.yaml\n')
 
 358     (getattr(config, location) / 'inc.yaml').write_text('first: 1\nsecond: 2\n')
 
 360     rules = config.load_sub_configuration('test.yaml')
 
 362     assert rules == dict(base=dict(first=1, second=2))
 
 365 def test_load_subconf_include_bad_format(make_config_path):
 
 366     config = make_config_path()
 
 368     testfile = config.config_dir / 'test.yaml'
 
 369     testfile.write_text(f'base: !include inc.txt\n')
 
 370     (config.config_dir / 'inc.txt').write_text('first: 1\nsecond: 2\n')
 
 372     with pytest.raises(UsageError, match='Cannot handle config file format.'):
 
 373         rules = config.load_sub_configuration('test.yaml')
 
 376 def test_load_subconf_include_not_found(make_config_path):
 
 377     config = make_config_path()
 
 379     testfile = config.config_dir / 'test.yaml'
 
 380     testfile.write_text(f'base: !include inc.txt\n')
 
 382     with pytest.raises(UsageError, match='Config file not found.'):
 
 383         rules = config.load_sub_configuration('test.yaml')
 
 386 def test_load_subconf_include_recursive(make_config_path):
 
 387     config = make_config_path()
 
 389     testfile = config.config_dir / 'test.yaml'
 
 390     testfile.write_text(f'base: !include inc.yaml\n')
 
 391     (config.config_dir / 'inc.yaml').write_text('- !include more.yaml\n- upper\n')
 
 392     (config.config_dir / 'more.yaml').write_text('- the end\n')
 
 394     rules = config.load_sub_configuration('test.yaml')
 
 396     assert rules == dict(base=[['the end'], 'upper'])
 
 399 @pytest.mark.parametrize("content", [[], None])
 
 400 def test_flatten_config_list_empty(content):
 
 401     assert flatten_config_list(content) == []
 
 404 @pytest.mark.parametrize("content", [{'foo': 'bar'}, 'hello world', 3])
 
 405 def test_flatten_config_list_no_list(content):
 
 406     with pytest.raises(UsageError):
 
 407         flatten_config_list(content)
 
 410 def test_flatten_config_list_allready_flat():
 
 411     assert flatten_config_list([1, 2, 456]) == [1, 2, 456]
 
 414 def test_flatten_config_list_nested():
 
 417         [{'first': '1st', 'second': '2nd'}, {}],
 
 418         [[2, 3], [45, [56, 78], 66]],
 
 421     assert flatten_config_list(content) == \
 
 422                [34, {'first': '1st', 'second': '2nd'}, {},
 
 423                 2, 3, 45, 56, 78, 66, 'end']