]> git.openstreetmap.org Git - nominatim.git/blob - test/python/config/test_config.py
enable flake for Python tests
[nominatim.git] / test / python / config / test_config.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2025 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Test for loading dotenv configuration.
9 """
10 from pathlib import Path
11 import pytest
12
13 from nominatim_db.config import Configuration, flatten_config_list
14 from nominatim_db.errors import UsageError
15
16
17 @pytest.fixture
18 def make_config():
19     """ Create a configuration object from the given project directory.
20     """
21     def _mk_config(project_dir=None):
22         return Configuration(project_dir)
23
24     return _mk_config
25
26
27 @pytest.fixture
28 def make_config_path(tmp_path):
29     """ Create a configuration object with project and config directories
30         in a temporary directory.
31     """
32     def _mk_config():
33         (tmp_path / 'project').mkdir()
34         (tmp_path / 'config').mkdir()
35         conf = Configuration(tmp_path / 'project')
36         conf.config_dir = tmp_path / 'config'
37         return conf
38
39     return _mk_config
40
41
42 def test_no_project_dir(make_config):
43     config = make_config()
44
45     assert config.DATABASE_WEBUSER == 'www-data'
46
47
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))
52
53     config = make_config(tmp_path)
54
55     assert config.DATABASE_WEBUSER == 'apache'
56
57
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')
61
62     monkeypatch.setenv('NOMINATIM_DATABASE_WEBUSER', 'nobody')
63
64     config = make_config(tmp_path)
65
66     assert config.DATABASE_WEBUSER == 'nobody'
67
68
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')
72
73     monkeypatch.setenv('NOMINATIM_DATABASE_WEBUSER', '')
74
75     config = make_config(tmp_path)
76
77     assert config.DATABASE_WEBUSER == ''
78
79
80 def test_get_os_env_add_defaults(make_config, monkeypatch):
81     config = make_config()
82
83     monkeypatch.delenv('NOMINATIM_DATABASE_WEBUSER', raising=False)
84
85     assert config.get_os_env()['NOMINATIM_DATABASE_WEBUSER'] == 'www-data'
86
87
88 def test_get_os_env_prefer_os_environ(make_config, monkeypatch):
89     config = make_config()
90
91     monkeypatch.setenv('NOMINATIM_DATABASE_WEBUSER', 'nobody')
92
93     assert config.get_os_env()['NOMINATIM_DATABASE_WEBUSER'] == 'nobody'
94
95
96 def test_get_libpq_dsn_convert_default(make_config):
97     config = make_config()
98
99     assert config.get_libpq_dsn() == 'dbname=nominatim'
100
101
102 def test_get_libpq_dsn_convert_php(make_config, monkeypatch):
103     config = make_config()
104
105     monkeypatch.setenv('NOMINATIM_DATABASE_DSN',
106                        'pgsql:dbname=gis;password=foo;host=localhost')
107
108     assert config.get_libpq_dsn() == 'dbname=gis password=foo host=localhost'
109
110
111 @pytest.mark.parametrize("val,expect", [('foo bar', "'foo bar'"),
112                                         ("xy'z", "xy\\'z"),
113                                         ])
114 def test_get_libpq_dsn_convert_php_special_chars(make_config, monkeypatch, val, expect):
115     config = make_config()
116
117     monkeypatch.setenv('NOMINATIM_DATABASE_DSN',
118                        'pgsql:dbname=gis;password={}'.format(val))
119
120     assert config.get_libpq_dsn() == "dbname=gis password={}".format(expect)
121
122
123 def test_get_libpq_dsn_convert_libpq(make_config, monkeypatch):
124     config = make_config()
125
126     monkeypatch.setenv('NOMINATIM_DATABASE_DSN',
127                        'host=localhost dbname=gis password=foo')
128
129     assert config.get_libpq_dsn() == 'host=localhost dbname=gis password=foo'
130
131
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()
137
138     monkeypatch.setenv('NOMINATIM_FOOBAR', value)
139
140     assert config.get_bool('FOOBAR') == result
141
142
143 def test_get_bool_empty(make_config):
144     config = make_config()
145
146     assert config.TOKENIZER_CONFIG == ''
147     assert not config.get_bool('TOKENIZER_CONFIG')
148
149
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()
154
155     monkeypatch.setenv('NOMINATIM_FOOBAR', value)
156
157     assert config.get_int('FOOBAR') == result
158
159
160 @pytest.mark.parametrize("value", ['1b', 'fg', '0x23'])
161 def test_get_int_bad_values(make_config, monkeypatch, value):
162     config = make_config()
163
164     monkeypatch.setenv('NOMINATIM_FOOBAR', value)
165
166     with pytest.raises(UsageError):
167         config.get_int('FOOBAR')
168
169
170 def test_get_int_empty(make_config):
171     config = make_config()
172
173     assert config.TOKENIZER_CONFIG == ''
174
175     with pytest.raises(UsageError):
176         config.get_int('TOKENIZER_CONFIG')
177
178
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()
184
185     monkeypatch.setenv('NOMINATIM_MYLIST', value)
186
187     assert config.get_str_list('MYLIST') == outlist
188
189
190 def test_get_str_list_empty(make_config):
191     config = make_config()
192
193     assert config.get_str_list('LANGUAGES') is None
194
195
196 def test_get_path_empty(make_config):
197     config = make_config()
198
199     assert config.TOKENIZER_CONFIG == ''
200     assert not config.get_path('TOKENIZER_CONFIG')
201
202
203 def test_get_path_absolute(make_config, monkeypatch):
204     config = make_config()
205
206     monkeypatch.setenv('NOMINATIM_FOOBAR', '/dont/care')
207     result = config.get_path('FOOBAR')
208
209     assert isinstance(result, Path)
210     assert str(result) == '/dont/care'
211
212
213 def test_get_path_relative(make_config, monkeypatch, tmp_path):
214     config = make_config(tmp_path)
215
216     monkeypatch.setenv('NOMINATIM_FOOBAR', 'an/oyster')
217     result = config.get_path('FOOBAR')
218
219     assert isinstance(result, Path)
220     assert str(result) == str(tmp_path / 'an/oyster')
221
222
223 def test_get_import_style_intern(make_config, src_dir, monkeypatch):
224     config = make_config()
225
226     monkeypatch.setenv('NOMINATIM_IMPORT_STYLE', 'street')
227
228     expected = src_dir / 'lib-lua' / 'import-street.lua'
229
230     assert config.get_import_style_file() == expected
231
232
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')
236
237     monkeypatch.setenv('NOMINATIM_IMPORT_STYLE', 'custom.style')
238
239     assert str(config.get_import_style_file()) == str(config.project_dir / 'custom.style')
240
241
242 def test_get_import_style_extern_absolute(make_config, tmp_path, monkeypatch):
243     config = make_config()
244     cfgfile = tmp_path / 'test.style'
245
246     cfgfile.write_text('x')
247
248     monkeypatch.setenv('NOMINATIM_IMPORT_STYLE', str(cfgfile))
249
250     assert str(config.get_import_style_file()) == str(cfgfile)
251
252
253 def test_load_subconf_from_project_dir(make_config_path):
254     config = make_config_path()
255
256     testfile = config.project_dir / 'test.yaml'
257     testfile.write_text('cow: muh\ncat: miau\n')
258
259     testfile = config.config_dir / 'test.yaml'
260     testfile.write_text('cow: miau\ncat: muh\n')
261
262     rules = config.load_sub_configuration('test.yaml')
263
264     assert rules == dict(cow='muh', cat='miau')
265
266
267 def test_load_subconf_from_settings_dir(make_config_path):
268     config = make_config_path()
269
270     testfile = config.config_dir / 'test.yaml'
271     testfile.write_text('cow: muh\ncat: miau\n')
272
273     rules = config.load_sub_configuration('test.yaml')
274
275     assert rules == dict(cow='muh', cat='miau')
276
277
278 def test_load_subconf_empty_env_conf(make_config_path, monkeypatch):
279     monkeypatch.setenv('NOMINATIM_MY_CONFIG', '')
280     config = make_config_path()
281
282     testfile = config.config_dir / 'test.yaml'
283     testfile.write_text('cow: muh\ncat: miau\n')
284
285     rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
286
287     assert rules == dict(cow='muh', cat='miau')
288
289
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()
293
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')
296
297     rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
298
299     assert rules == dict(dog='muh', frog='miau')
300
301
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()
305
306     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
307
308     with pytest.raises(UsageError, match='Config file not found.'):
309         config.load_sub_configuration('test.yaml', config='MY_CONFIG')
310
311
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()
316
317     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
318     (getattr(config, location) / 'other.yaml').write_text('dog: bark\n')
319
320     rules = config.load_sub_configuration('test.yaml', config='MY_CONFIG')
321
322     assert rules == dict(dog='bark')
323
324
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()
328
329     (config.config_dir / 'test.yaml').write_text('cow: muh\ncat: miau\n')
330
331     with pytest.raises(UsageError, match='Config file not found.'):
332         config.load_sub_configuration('test.yaml', config='MY_CONFIG')
333
334
335 def test_load_subconf_json(make_config_path):
336     config = make_config_path()
337
338     (config.project_dir / 'test.json').write_text('{"cow": "muh", "cat": "miau"}')
339
340     rules = config.load_sub_configuration('test.json')
341
342     assert rules == dict(cow='muh', cat='miau')
343
344
345 def test_load_subconf_not_found(make_config_path):
346     config = make_config_path()
347
348     with pytest.raises(UsageError, match='Config file not found.'):
349         config.load_sub_configuration('test.yaml')
350
351
352 def test_load_subconf_env_unknown_format(make_config_path):
353     config = make_config_path()
354
355     (config.project_dir / 'test.xml').write_text('<html></html>')
356
357     with pytest.raises(UsageError, match='unknown format'):
358         config.load_sub_configuration('test.xml')
359
360
361 def test_load_subconf_include_absolute(make_config_path, tmp_path):
362     config = make_config_path()
363
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')
367
368     rules = config.load_sub_configuration('test.yaml')
369
370     assert rules == dict(base=dict(first=1, second=2))
371
372
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()
376
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')
380
381     rules = config.load_sub_configuration('test.yaml')
382
383     assert rules == dict(base=dict(first=1, second=2))
384
385
386 def test_load_subconf_include_bad_format(make_config_path):
387     config = make_config_path()
388
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')
392
393     with pytest.raises(UsageError, match='Cannot handle config file format.'):
394         config.load_sub_configuration('test.yaml')
395
396
397 def test_load_subconf_include_not_found(make_config_path):
398     config = make_config_path()
399
400     testfile = config.config_dir / 'test.yaml'
401     testfile.write_text('base: !include inc.txt\n')
402
403     with pytest.raises(UsageError, match='Config file not found.'):
404         config.load_sub_configuration('test.yaml')
405
406
407 def test_load_subconf_include_recursive(make_config_path):
408     config = make_config_path()
409
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')
414
415     rules = config.load_sub_configuration('test.yaml')
416
417     assert rules == dict(base=[['the end'], 'upper'])
418
419
420 @pytest.mark.parametrize("content", [[], None])
421 def test_flatten_config_list_empty(content):
422     assert flatten_config_list(content) == []
423
424
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)
429
430
431 def test_flatten_config_list_allready_flat():
432     assert flatten_config_list([1, 2, 456]) == [1, 2, 456]
433
434
435 def test_flatten_config_list_nested():
436     content = [
437         34,
438         [{'first': '1st', 'second': '2nd'}, {}],
439         [[2, 3], [45, [56, 78], 66]],
440         'end'
441     ]
442
443     assert flatten_config_list(content) == \
444         [34, {'first': '1st', 'second': '2nd'}, {}, 2, 3, 45, 56, 78, 66, 'end']