]> git.openstreetmap.org Git - nominatim.git/blob - test/python/test_tokenizer_legacy.py
update unit tests for adapted abbreviation code
[nominatim.git] / test / python / test_tokenizer_legacy.py
1 """
2 Test for legacy tokenizer.
3 """
4 import shutil
5
6 import pytest
7
8 from nominatim.tokenizer import legacy_tokenizer
9 from nominatim.db import properties
10 from nominatim.errors import UsageError
11
12 @pytest.fixture
13 def test_config(def_config, tmp_path):
14     def_config.project_dir = tmp_path / 'project'
15     def_config.project_dir.mkdir()
16
17     module_dir = tmp_path / 'module_src'
18     module_dir.mkdir()
19     (module_dir / 'nominatim.so').write_text('TEST nomiantim.so')
20
21     def_config.lib_dir.module = module_dir
22
23     sqldir = tmp_path / 'sql'
24     sqldir.mkdir()
25     (sqldir / 'tokenizer').mkdir()
26     (sqldir / 'tokenizer' / 'legacy_tokenizer.sql').write_text("SELECT 'a'")
27     (sqldir / 'words.sql').write_text("SELECT 'a'")
28     shutil.copy(str(def_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_tables.sql'),
29                 str(sqldir / 'tokenizer' / 'legacy_tokenizer_tables.sql'))
30
31     def_config.lib_dir.sql = sqldir
32     def_config.lib_dir.data = sqldir
33
34     return def_config
35
36
37 @pytest.fixture
38 def tokenizer_factory(dsn, tmp_path, property_table):
39     (tmp_path / 'tokenizer').mkdir()
40
41     def _maker():
42         return legacy_tokenizer.create(dsn, tmp_path / 'tokenizer')
43
44     return _maker
45
46
47 @pytest.fixture
48 def tokenizer_setup(tokenizer_factory, test_config, monkeypatch, sql_preprocessor):
49     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
50     tok = tokenizer_factory()
51     tok.init_new_db(test_config)
52
53
54 @pytest.fixture
55 def analyzer(tokenizer_factory, test_config, monkeypatch, sql_preprocessor,
56              word_table, temp_db_with_extensions, tmp_path):
57     sql = tmp_path / 'sql' / 'tokenizer' / 'legacy_tokenizer.sql'
58     sql.write_text("""
59         CREATE OR REPLACE FUNCTION getorcreate_housenumber_id(lookup_word TEXT)
60           RETURNS INTEGER AS $$ SELECT 342; $$ LANGUAGE SQL;
61         """)
62
63     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
64     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
65     tok = tokenizer_factory()
66     tok.init_new_db(test_config)
67     monkeypatch.undo()
68
69     with tok.name_analyzer() as analyzer:
70         yield analyzer
71
72
73 @pytest.fixture
74 def make_standard_name(temp_db_cursor):
75     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION make_standard_name(name TEXT)
76                               RETURNS TEXT AS $$ SELECT '#' || lower(name) || '#'; $$ LANGUAGE SQL""")
77
78
79 @pytest.fixture
80 def create_postcode_id(temp_db_cursor):
81     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION create_postcode_id(postcode TEXT)
82                               RETURNS BOOLEAN AS $$
83                               INSERT INTO word (word_token, word, class, type)
84                                 VALUES (' ' || postcode, postcode, 'place', 'postcode')
85                               RETURNING True;
86                               $$ LANGUAGE SQL""")
87
88
89 @pytest.fixture
90 def make_keywords(temp_db_cursor, temp_db_with_extensions):
91     temp_db_cursor.execute(
92         """CREATE OR REPLACE FUNCTION make_keywords(names HSTORE)
93            RETURNS INTEGER[] AS $$ SELECT ARRAY[1, 2, 3] $$ LANGUAGE SQL""")
94
95 def test_init_new(tokenizer_factory, test_config, monkeypatch,
96                   temp_db_conn, sql_preprocessor):
97     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', 'xxvv')
98     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
99
100     tok = tokenizer_factory()
101     tok.init_new_db(test_config)
102
103     assert properties.get_property(temp_db_conn, legacy_tokenizer.DBCFG_NORMALIZATION) == 'xxvv'
104
105     outfile = test_config.project_dir / 'module' / 'nominatim.so'
106
107     assert outfile.exists()
108     assert outfile.read_text() == 'TEST nomiantim.so'
109     assert outfile.stat().st_mode == 33261
110
111
112 def test_init_module_load_failed(tokenizer_factory, test_config):
113     tok = tokenizer_factory()
114
115     with pytest.raises(UsageError):
116         tok.init_new_db(test_config)
117
118
119 def test_init_module_custom(tokenizer_factory, test_config,
120                             monkeypatch, tmp_path, sql_preprocessor):
121     module_dir = (tmp_path / 'custom').resolve()
122     module_dir.mkdir()
123     (module_dir/ 'nominatim.so').write_text('CUSTOM nomiantim.so')
124
125     monkeypatch.setenv('NOMINATIM_DATABASE_MODULE_PATH', str(module_dir))
126     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
127
128     tok = tokenizer_factory()
129     tok.init_new_db(test_config)
130
131     assert not (test_config.project_dir / 'module').exists()
132
133
134 def test_init_from_project(tokenizer_setup, tokenizer_factory):
135     tok = tokenizer_factory()
136
137     tok.init_from_project()
138
139     assert tok.normalization is not None
140
141
142 def test_update_sql_functions(sql_preprocessor, temp_db_conn,
143                               tokenizer_factory, test_config, table_factory,
144                               monkeypatch, temp_db_cursor):
145     monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '1133')
146     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
147     tok = tokenizer_factory()
148     tok.init_new_db(test_config)
149     monkeypatch.undo()
150
151     assert properties.get_property(temp_db_conn, legacy_tokenizer.DBCFG_MAXWORDFREQ) == '1133'
152
153     table_factory('test', 'txt TEXT')
154
155     func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer.sql'
156     func_file.write_text("""INSERT INTO test VALUES ('{{max_word_freq}}'),
157                                                    ('{{modulepath}}')""")
158
159     tok.update_sql_functions(test_config)
160
161     test_content = temp_db_cursor.row_set('SELECT * FROM test')
162     assert test_content == set((('1133', ), (str(test_config.project_dir / 'module'), )))
163
164
165 def test_migrate_database(tokenizer_factory, test_config, temp_db_conn, monkeypatch):
166     monkeypatch.setattr(legacy_tokenizer, '_check_module', lambda m, c: None)
167     tok = tokenizer_factory()
168     tok.migrate_database(test_config)
169
170     assert properties.get_property(temp_db_conn, legacy_tokenizer.DBCFG_MAXWORDFREQ) is not None
171     assert properties.get_property(temp_db_conn, legacy_tokenizer.DBCFG_NORMALIZATION) is not None
172
173     outfile = test_config.project_dir / 'module' / 'nominatim.so'
174
175     assert outfile.exists()
176     assert outfile.read_text() == 'TEST nomiantim.so'
177     assert outfile.stat().st_mode == 33261
178
179
180 def test_normalize(analyzer):
181     assert analyzer.normalize('TEsT') == 'test'
182
183
184 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table,
185                                         create_postcode_id):
186     table_factory('location_postcode', 'postcode TEXT',
187                   content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
188
189     analyzer.update_postcodes_from_db()
190
191     assert word_table.count() == 3
192     assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
193
194
195 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table,
196                                                  create_postcode_id):
197     table_factory('location_postcode', 'postcode TEXT',
198                   content=(('1234',), ('45BC', ), ('XX45', )))
199     word_table.add_postcode(' 1234', '1234')
200     word_table.add_postcode(' 5678', '5678')
201
202     analyzer.update_postcodes_from_db()
203
204     assert word_table.count() == 3
205     assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
206
207
208 def test_update_special_phrase_empty_table(analyzer, word_table, make_standard_name):
209     analyzer.update_special_phrases([
210         ("König bei", "amenity", "royal", "near"),
211         ("Könige", "amenity", "royal", "-"),
212         ("könige", "amenity", "royal", "-"),
213         ("strasse", "highway", "primary", "in")
214     ], True)
215
216     assert word_table.get_special() \
217                == set(((' #könig bei#', 'könig bei', 'amenity', 'royal', 'near'),
218                        (' #könige#', 'könige', 'amenity', 'royal', None),
219                        (' #strasse#', 'strasse', 'highway', 'primary', 'in')))
220
221
222 def test_update_special_phrase_delete_all(analyzer, word_table, make_standard_name):
223     word_table.add_special(' #foo#', 'foo', 'amenity', 'prison', 'in')
224     word_table.add_special(' #bar#', 'bar', 'highway', 'road', None)
225
226     assert word_table.count_special() == 2
227
228     analyzer.update_special_phrases([], True)
229
230     assert word_table.count_special() == 0
231
232
233 def test_update_special_phrases_no_replace(analyzer, word_table, make_standard_name):
234     word_table.add_special(' #foo#', 'foo', 'amenity', 'prison', 'in')
235     word_table.add_special(' #bar#', 'bar', 'highway', 'road', None)
236
237     assert word_table.count_special() == 2
238
239     analyzer.update_special_phrases([], False)
240
241     assert word_table.count_special() == 2
242
243
244 def test_update_special_phrase_modify(analyzer, word_table, make_standard_name):
245     word_table.add_special(' #foo#', 'foo', 'amenity', 'prison', 'in')
246     word_table.add_special(' #bar#', 'bar', 'highway', 'road', None)
247
248     assert word_table.count_special() == 2
249
250     analyzer.update_special_phrases([
251         ('prison', 'amenity', 'prison', 'in'),
252         ('bar', 'highway', 'road', '-'),
253         ('garden', 'leisure', 'garden', 'near')
254     ], True)
255
256     assert word_table.get_special() \
257                == set(((' #prison#', 'prison', 'amenity', 'prison', 'in'),
258                        (' #bar#', 'bar', 'highway', 'road', None),
259                        (' #garden#', 'garden', 'leisure', 'garden', 'near')))
260
261
262 def test_add_country_names(analyzer, word_table, make_standard_name):
263     analyzer.add_country_names('de', {'name': 'Germany',
264                                       'name:de': 'Deutschland',
265                                       'short_name': 'germany'})
266
267     assert word_table.get_country() \
268                == {('de', ' #germany#'),
269                    ('de', ' #deutschland#')}
270
271
272 def test_add_more_country_names(analyzer, word_table, make_standard_name):
273     word_table.add_country('fr', ' #france#')
274     word_table.add_country('it', ' #italy#')
275     word_table.add_country('it', ' #itala#')
276
277     analyzer.add_country_names('it', {'name': 'Italy', 'ref': 'IT'})
278
279     assert word_table.get_country() \
280                == {('fr', ' #france#'),
281                    ('it', ' #italy#'),
282                    ('it', ' #itala#'),
283                    ('it', ' #it#')}
284
285
286 def test_process_place_names(analyzer, make_keywords):
287     info = analyzer.process_place({'name' : {'name' : 'Soft bAr', 'ref': '34'}})
288
289     assert info['names'] == '{1,2,3}'
290
291
292 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
293 def test_process_place_postcode(analyzer, create_postcode_id, word_table, pcode):
294     analyzer.process_place({'address': {'postcode' : pcode}})
295
296     assert word_table.get_postcodes() == {pcode, }
297
298
299 @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
300 def test_process_place_bad_postcode(analyzer, create_postcode_id, word_table, pcode):
301     analyzer.process_place({'address': {'postcode' : pcode}})
302
303     assert not word_table.get_postcodes()
304
305
306 class TestHousenumberName:
307
308     @staticmethod
309     @pytest.fixture(autouse=True)
310     def setup_create_housenumbers(temp_db_cursor):
311         temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION create_housenumbers(
312                                       housenumbers TEXT[],
313                                       OUT tokens TEXT, OUT normtext TEXT)
314                                   AS $$
315                                   SELECT housenumbers::TEXT, array_to_string(housenumbers, ';')
316                                   $$ LANGUAGE SQL""")
317
318
319     @staticmethod
320     @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
321     def test_process_place_housenumbers_simple(analyzer, hnr):
322         info = analyzer.process_place({'address': {'housenumber' : hnr}})
323
324         assert info['hnr'] == hnr
325         assert info['hnr_tokens'].startswith("{")
326
327
328     @staticmethod
329     def test_process_place_housenumbers_lists(analyzer):
330         info = analyzer.process_place({'address': {'conscriptionnumber' : '1; 2;3'}})
331
332         assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
333
334
335     @staticmethod
336     def test_process_place_housenumbers_duplicates(analyzer):
337         info = analyzer.process_place({'address': {'housenumber' : '134',
338                                                    'conscriptionnumber' : '134',
339                                                    'streetnumber' : '99a'}})
340
341         assert set(info['hnr'].split(';')) == set(('134', '99a'))