1 # SPDX-License-Identifier: GPL-3.0-or-later
 
   3 # This file is part of Nominatim. (https://nominatim.org)
 
   5 # Copyright (C) 2025 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_db.config import Configuration, flatten_config_list
 
  14 from nominatim_db.errors import UsageError
 
  19     """ Create a configuration object from the given project directory.
 
  21     def _mk_config(project_dir=None):
 
  22         return Configuration(project_dir)
 
  28 def make_config_path(tmp_path):
 
  29     """ Create a configuration object with project and config directories
 
  30         in a temporary directory.
 
  33         (tmp_path / 'project').mkdir()
 
  34         (tmp_path / 'config').mkdir()
 
  35         conf = Configuration(tmp_path / 'project')
 
  36         conf.config_dir = tmp_path / 'config'
 
  42 def test_no_project_dir(make_config):
 
  43     config = make_config()
 
  45     assert config.DATABASE_WEBUSER == 'www-data'
 
  48 @pytest.mark.parametrize("val", ('apache', '"apache"'))
 
  49 def test_prefer_project_setting_over_default(make_config, val, tmp_path):
 
  50     envfile = tmp_path / '.env'
 
  51     envfile.write_text('NOMINATIM_DATABASE_WEBUSER={}\n'.format(val))
 
  53     config = make_config(tmp_path)
 
  55     assert config.DATABASE_WEBUSER == 'apache'
 
  58 def test_prefer_os_environ_over_project_setting(make_config, monkeypatch, tmp_path):
 
  59     envfile = tmp_path / '.env'
 
  60     envfile.write_text('NOMINATIM_DATABASE_WEBUSER=apache\n')
 
  62     monkeypatch.setenv('NOMINATIM_DATABASE_WEBUSER', 'nobody')
 
  64     config = make_config(tmp_path)
 
  66     assert config.DATABASE_WEBUSER == 'nobody'
 
  69 def test_prefer_os_environ_can_unset_project_setting(make_config, monkeypatch, tmp_path):
 
  70     envfile = tmp_path / '.env'
 
  71     envfile.write_text('NOMINATIM_DATABASE_WEBUSER=apache\n')
 
  73     monkeypatch.setenv('NOMINATIM_DATABASE_WEBUSER', '')
 
  75     config = make_config(tmp_path)
 
  77     assert config.DATABASE_WEBUSER == ''
 
  80 def test_get_os_env_add_defaults(make_config, monkeypatch):
 
  81     config = make_config()
 
  83     monkeypatch.delenv('NOMINATIM_DATABASE_WEBUSER', raising=False)
 
  85     assert config.get_os_env()['NOMINATIM_DATABASE_WEBUSER'] == 'www-data'
 
  88 def test_get_os_env_prefer_os_environ(make_config, monkeypatch):
 
  89     config = make_config()
 
  91     monkeypatch.setenv('NOMINATIM_DATABASE_WEBUSER', 'nobody')
 
  93     assert config.get_os_env()['NOMINATIM_DATABASE_WEBUSER'] == 'nobody'
 
  96 def test_get_libpq_dsn_convert_default(make_config):
 
  97     config = make_config()
 
  99     assert config.get_libpq_dsn() == 'dbname=nominatim'
 
 102 def test_get_libpq_dsn_convert_php(make_config, monkeypatch):
 
 103     config = make_config()
 
 105     monkeypatch.setenv('NOMINATIM_DATABASE_DSN',
 
 106                        'pgsql:dbname=gis;password=foo;host=localhost')
 
 108     assert config.get_libpq_dsn() == 'dbname=gis password=foo host=localhost'
 
 111 @pytest.mark.parametrize("val,expect", [('foo bar', "'foo bar'"),
 
 114 def test_get_libpq_dsn_convert_php_special_chars(make_config, monkeypatch, val, expect):
 
 115     config = make_config()
 
 117     monkeypatch.setenv('NOMINATIM_DATABASE_DSN',
 
 118                        'pgsql:dbname=gis;password={}'.format(val))
 
 120     assert config.get_libpq_dsn() == "dbname=gis password={}".format(expect)
 
 123 def test_get_libpq_dsn_convert_libpq(make_config, monkeypatch):
 
 124     config = make_config()
 
 126     monkeypatch.setenv('NOMINATIM_DATABASE_DSN',
 
 127                        'host=localhost dbname=gis password=foo')
 
 129     assert config.get_libpq_dsn() == 'host=localhost dbname=gis password=foo'
 
 132 @pytest.mark.parametrize("value,result",
 
 133                          [(x, True) for x in ('1', 'true', 'True', 'yes', 'YES')] +
 
 134                          [(x, False) for x in ('0', 'false', 'no', 'NO', 'x')])
 
 135 def test_get_bool(make_config, monkeypatch, value, result):
 
 136     config = make_config()
 
 138     monkeypatch.setenv('NOMINATIM_FOOBAR', value)
 
 140     assert config.get_bool('FOOBAR') == result
 
 143 def test_get_bool_empty(make_config):
 
 144     config = make_config()
 
 146     assert config.TOKENIZER_CONFIG == ''
 
 147     assert not config.get_bool('TOKENIZER_CONFIG')
 
 150 @pytest.mark.parametrize("value,result", [('0', 0), ('1', 1),
 
 151                                           ('85762513444', 85762513444)])
 
 152 def test_get_int_success(make_config, monkeypatch, value, result):
 
 153     config = make_config()
 
 155     monkeypatch.setenv('NOMINATIM_FOOBAR', value)
 
 157     assert config.get_int('FOOBAR') == result
 
 160 @pytest.mark.parametrize("value", ['1b', 'fg', '0x23'])
 
 161 def test_get_int_bad_values(make_config, monkeypatch, value):
 
 162     config = make_config()
 
 164     monkeypatch.setenv('NOMINATIM_FOOBAR', value)
 
 166     with pytest.raises(UsageError):
 
 167         config.get_int('FOOBAR')
 
 170 def test_get_int_empty(make_config):
 
 171     config = make_config()
 
 173     assert config.TOKENIZER_CONFIG == ''
 
 175     with pytest.raises(UsageError):
 
 176         config.get_int('TOKENIZER_CONFIG')
 
 179 @pytest.mark.parametrize("value,outlist", [('sd', ['sd']),
 
 180                                            ('dd,rr', ['dd', 'rr']),
 
 181                                            (' a , b ', ['a', 'b'])])
 
 182 def test_get_str_list_success(make_config, monkeypatch, value, outlist):
 
 183     config = make_config()
 
 185     monkeypatch.setenv('NOMINATIM_MYLIST', value)
 
 187     assert config.get_str_list('MYLIST') == outlist
 
 190 def test_get_str_list_empty(make_config):
 
 191     config = make_config()
 
 193     assert config.get_str_list('LANGUAGES') is None
 
 196 def test_get_path_empty(make_config):
 
 197     config = make_config()
 
 199     assert config.TOKENIZER_CONFIG == ''
 
 200     assert not config.get_path('TOKENIZER_CONFIG')
 
 203 def test_get_path_absolute(make_config, monkeypatch):
 
 204     config = make_config()
 
 206     monkeypatch.setenv('NOMINATIM_FOOBAR', '/dont/care')
 
 207     result = config.get_path('FOOBAR')
 
 209     assert isinstance(result, Path)
 
 210     assert str(result) == '/dont/care'
 
 213 def test_get_path_relative(make_config, monkeypatch, tmp_path):
 
 214     config = make_config(tmp_path)
 
 216     monkeypatch.setenv('NOMINATIM_FOOBAR', 'an/oyster')
 
 217     result = config.get_path('FOOBAR')
 
 219     assert isinstance(result, Path)
 
 220     assert str(result) == str(tmp_path / 'an/oyster')
 
 223 def test_get_import_style_intern(make_config, src_dir, monkeypatch):
 
 224     config = make_config()
 
 226     monkeypatch.setenv('NOMINATIM_IMPORT_STYLE', 'street')
 
 228     expected = src_dir / 'lib-lua' / 'import-street.lua'
 
 230     assert config.get_import_style_file() == expected
 
 233 def test_get_import_style_extern_relative(make_config_path, monkeypatch):
 
 234     config = make_config_path()
 
 235     (config.project_dir / 'custom.style').write_text('x')
 
 237     monkeypatch.setenv('NOMINATIM_IMPORT_STYLE', 'custom.style')
 
 239     assert str(config.get_import_style_file()) == str(config.project_dir / 'custom.style')
 
 242 def test_get_import_style_extern_absolute(make_config, tmp_path, monkeypatch):
 
 243     config = make_config()
 
 244     cfgfile = tmp_path / 'test.style'
 
 246     cfgfile.write_text('x')
 
 248     monkeypatch.setenv('NOMINATIM_IMPORT_STYLE', str(cfgfile))
 
 250     assert str(config.get_import_style_file()) == str(cfgfile)
 
 253 def test_load_subconf_from_project_dir(make_config_path):
 
 254     config = make_config_path()
 
 256     testfile = config.project_dir / 'test.yaml'
 
 257     testfile.write_text('cow: muh\ncat: miau\n')
 
 259     testfile = config.config_dir / 'test.yaml'
 
 260     testfile.write_text('cow: miau\ncat: muh\n')
 
 262     rules = config.load_sub_configuration('test.yaml')
 
 264     assert rules == dict(cow='muh', cat='miau')
 
 267 def test_load_subconf_from_settings_dir(make_config_path):
 
 268     config = make_config_path()
 
 270     testfile = config.config_dir / 'test.yaml'
 
 271     testfile.write_text('cow: muh\ncat: miau\n')
 
 273     rules = config.load_sub_configuration('test.yaml')
 
 275     assert rules == dict(cow='muh', cat='miau')
 
 278 def test_load_subconf_empty_env_conf(make_config_path, monkeypatch):
 
 279     monkeypatch.setenv('NOMINATIM_MY_CONFIG', '')
 
 280     config = make_config_path()
 
 282     testfile = config.config_dir / 'test.yaml'
 
 283     testfile.write_text('cow: muh\ncat: miau\n')
 
 285     rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 287     assert rules == dict(cow='muh', cat='miau')
 
 290 def test_load_subconf_env_absolute_found(make_config_path, monkeypatch, tmp_path):
 
 291     monkeypatch.setenv('NOMINATIM_MY_CONFIG', str(tmp_path / 'other.yaml'))
 
 292     config = make_config_path()
 
 294     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
 
 295     (tmp_path / 'other.yaml').write_text('dog: muh\nfrog: miau\n')
 
 297     rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 299     assert rules == dict(dog='muh', frog='miau')
 
 302 def test_load_subconf_env_absolute_not_found(make_config_path, monkeypatch, tmp_path):
 
 303     monkeypatch.setenv('NOMINATIM_MY_CONFIG', str(tmp_path / 'other.yaml'))
 
 304     config = make_config_path()
 
 306     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
 
 308     with pytest.raises(UsageError, match='Config file not found.'):
 
 309         config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 312 @pytest.mark.parametrize("location", ['project_dir', 'config_dir'])
 
 313 def test_load_subconf_env_relative_found(make_config_path, monkeypatch, location):
 
 314     monkeypatch.setenv('NOMINATIM_MY_CONFIG', 'other.yaml')
 
 315     config = make_config_path()
 
 317     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
 
 318     (getattr(config, location) / 'other.yaml').write_text('dog: bark\n')
 
 320     rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 322     assert rules == dict(dog='bark')
 
 325 def test_load_subconf_env_relative_not_found(make_config_path, monkeypatch):
 
 326     monkeypatch.setenv('NOMINATIM_MY_CONFIG', 'other.yaml')
 
 327     config = make_config_path()
 
 329     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
 
 331     with pytest.raises(UsageError, match='Config file not found.'):
 
 332         config.load_sub_configuration('test.yaml', config='MY_CONFIG')
 
 335 def test_load_subconf_json(make_config_path):
 
 336     config = make_config_path()
 
 338     (config.project_dir / 'test.json').write_text('{"cow": "muh", "cat": "miau"}')
 
 340     rules = config.load_sub_configuration('test.json')
 
 342     assert rules == dict(cow='muh', cat='miau')
 
 345 def test_load_subconf_not_found(make_config_path):
 
 346     config = make_config_path()
 
 348     with pytest.raises(UsageError, match='Config file not found.'):
 
 349         config.load_sub_configuration('test.yaml')
 
 352 def test_load_subconf_env_unknown_format(make_config_path):
 
 353     config = make_config_path()
 
 355     (config.project_dir / 'test.xml').write_text('<html></html>')
 
 357     with pytest.raises(UsageError, match='unknown format'):
 
 358         config.load_sub_configuration('test.xml')
 
 361 def test_load_subconf_include_absolute(make_config_path, tmp_path):
 
 362     config = make_config_path()
 
 364     testfile = config.config_dir / 'test.yaml'
 
 365     testfile.write_text(f'base: !include {tmp_path}/inc.yaml\n')
 
 366     (tmp_path / 'inc.yaml').write_text('first: 1\nsecond: 2\n')
 
 368     rules = config.load_sub_configuration('test.yaml')
 
 370     assert rules == dict(base=dict(first=1, second=2))
 
 373 @pytest.mark.parametrize("location", ['project_dir', 'config_dir'])
 
 374 def test_load_subconf_include_relative(make_config_path, tmp_path, location):
 
 375     config = make_config_path()
 
 377     testfile = config.config_dir / 'test.yaml'
 
 378     testfile.write_text('base: !include inc.yaml\n')
 
 379     (getattr(config, location) / 'inc.yaml').write_text('first: 1\nsecond: 2\n')
 
 381     rules = config.load_sub_configuration('test.yaml')
 
 383     assert rules == dict(base=dict(first=1, second=2))
 
 386 def test_load_subconf_include_bad_format(make_config_path):
 
 387     config = make_config_path()
 
 389     testfile = config.config_dir / 'test.yaml'
 
 390     testfile.write_text('base: !include inc.txt\n')
 
 391     (config.config_dir / 'inc.txt').write_text('first: 1\nsecond: 2\n')
 
 393     with pytest.raises(UsageError, match='Cannot handle config file format.'):
 
 394         config.load_sub_configuration('test.yaml')
 
 397 def test_load_subconf_include_not_found(make_config_path):
 
 398     config = make_config_path()
 
 400     testfile = config.config_dir / 'test.yaml'
 
 401     testfile.write_text('base: !include inc.txt\n')
 
 403     with pytest.raises(UsageError, match='Config file not found.'):
 
 404         config.load_sub_configuration('test.yaml')
 
 407 def test_load_subconf_include_recursive(make_config_path):
 
 408     config = make_config_path()
 
 410     testfile = config.config_dir / 'test.yaml'
 
 411     testfile.write_text('base: !include inc.yaml\n')
 
 412     (config.config_dir / 'inc.yaml').write_text('- !include more.yaml\n- upper\n')
 
 413     (config.config_dir / 'more.yaml').write_text('- the end\n')
 
 415     rules = config.load_sub_configuration('test.yaml')
 
 417     assert rules == dict(base=[['the end'], 'upper'])
 
 420 @pytest.mark.parametrize("content", [[], None])
 
 421 def test_flatten_config_list_empty(content):
 
 422     assert flatten_config_list(content) == []
 
 425 @pytest.mark.parametrize("content", [{'foo': 'bar'}, 'hello world', 3])
 
 426 def test_flatten_config_list_no_list(content):
 
 427     with pytest.raises(UsageError):
 
 428         flatten_config_list(content)
 
 431 def test_flatten_config_list_allready_flat():
 
 432     assert flatten_config_list([1, 2, 456]) == [1, 2, 456]
 
 435 def test_flatten_config_list_nested():
 
 438         [{'first': '1st', 'second': '2nd'}, {}],
 
 439         [[2, 3], [45, [56, 78], 66]],
 
 443     assert flatten_config_list(content) == \
 
 444         [34, {'first': '1st', 'second': '2nd'}, {}, 2, 3, 45, 56, 78, 66, 'end']