]> git.openstreetmap.org Git - nominatim.git/blob - test/python/tokenizer/test_icu.py
tests: add fixture for making test project directory
[nominatim.git] / test / python / tokenizer / test_icu.py
1 """
2 Tests for Legacy ICU tokenizer.
3 """
4 import shutil
5 import yaml
6
7 import pytest
8
9 from nominatim.tokenizer import icu_tokenizer
10 import nominatim.tokenizer.icu_rule_loader
11 from nominatim.db import properties
12 from nominatim.db.sql_preprocessor import SQLPreprocessor
13 from nominatim.indexer.place_info import PlaceInfo
14
15 from mock_icu_word_table import MockIcuWordTable
16
17 @pytest.fixture
18 def word_table(temp_db_conn):
19     return MockIcuWordTable(temp_db_conn)
20
21
22 @pytest.fixture
23 def test_config(project_env, tmp_path):
24     sqldir = tmp_path / 'sql'
25     sqldir.mkdir()
26     (sqldir / 'tokenizer').mkdir()
27     (sqldir / 'tokenizer' / 'icu_tokenizer.sql').write_text("SELECT 'a'")
28     shutil.copy(str(project_env.lib_dir.sql / 'tokenizer' / 'icu_tokenizer_tables.sql'),
29                 str(sqldir / 'tokenizer' / 'icu_tokenizer_tables.sql'))
30
31     project_env.lib_dir.sql = sqldir
32
33     return project_env
34
35
36 @pytest.fixture
37 def tokenizer_factory(dsn, tmp_path, property_table,
38                       sql_preprocessor, place_table, word_table):
39     (tmp_path / 'tokenizer').mkdir()
40
41     def _maker():
42         return icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
43
44     return _maker
45
46
47 @pytest.fixture
48 def db_prop(temp_db_conn):
49     def _get_db_property(name):
50         return properties.get_property(temp_db_conn, name)
51
52     return _get_db_property
53
54
55 @pytest.fixture
56 def analyzer(tokenizer_factory, test_config, monkeypatch,
57              temp_db_with_extensions, tmp_path):
58     sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
59     sql.write_text("SELECT 'a';")
60
61     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
62     tok = tokenizer_factory()
63     tok.init_new_db(test_config)
64     monkeypatch.undo()
65
66     def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
67                      variants=('~gasse -> gasse', 'street => st', ),
68                      sanitizers=[]):
69         cfgstr = {'normalization': list(norm),
70                   'sanitizers': sanitizers,
71                   'transliteration': list(trans),
72                   'token-analysis': [{'analyzer': 'generic',
73                                       'variants': [{'words': list(variants)}]}]}
74         (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
75         tok.loader = nominatim.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
76
77         return tok.name_analyzer()
78
79     return _mk_analyser
80
81 @pytest.fixture
82 def sql_functions(temp_db_conn, def_config, src_dir):
83     orig_sql = def_config.lib_dir.sql
84     def_config.lib_dir.sql = src_dir / 'lib-sql'
85     sqlproc = SQLPreprocessor(temp_db_conn, def_config)
86     sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
87     sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
88     def_config.lib_dir.sql = orig_sql
89
90
91 @pytest.fixture
92 def getorcreate_full_word(temp_db_cursor):
93     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
94                                                  norm_term TEXT, lookup_terms TEXT[],
95                                                  OUT full_token INT,
96                                                  OUT partial_tokens INT[])
97   AS $$
98 DECLARE
99   partial_terms TEXT[] = '{}'::TEXT[];
100   term TEXT;
101   term_id INTEGER;
102   term_count INTEGER;
103 BEGIN
104   SELECT min(word_id) INTO full_token
105     FROM word WHERE info->>'word' = norm_term and type = 'W';
106
107   IF full_token IS NULL THEN
108     full_token := nextval('seq_word');
109     INSERT INTO word (word_id, word_token, type, info)
110       SELECT full_token, lookup_term, 'W',
111              json_build_object('word', norm_term, 'count', 0)
112         FROM unnest(lookup_terms) as lookup_term;
113   END IF;
114
115   FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
116     term := trim(term);
117     IF NOT (ARRAY[term] <@ partial_terms) THEN
118       partial_terms := partial_terms || term;
119     END IF;
120   END LOOP;
121
122   partial_tokens := '{}'::INT[];
123   FOR term IN SELECT unnest(partial_terms) LOOP
124     SELECT min(word_id), max(info->>'count') INTO term_id, term_count
125       FROM word WHERE word_token = term and type = 'w';
126
127     IF term_id IS NULL THEN
128       term_id := nextval('seq_word');
129       term_count := 0;
130       INSERT INTO word (word_id, word_token, type, info)
131         VALUES (term_id, term, 'w', json_build_object('count', term_count));
132     END IF;
133
134     IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
135       partial_tokens := partial_tokens || term_id;
136     END IF;
137   END LOOP;
138 END;
139 $$
140 LANGUAGE plpgsql;
141                               """)
142
143
144 @pytest.fixture
145 def getorcreate_hnr_id(temp_db_cursor):
146     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
147                               RETURNS INTEGER AS $$
148                                 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
149
150
151 def test_init_new(tokenizer_factory, test_config, db_prop):
152     tok = tokenizer_factory()
153     tok.init_new_db(test_config)
154
155     assert db_prop(nominatim.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES) \
156             .startswith(':: lower ();')
157
158
159 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
160     place_row(names={'name' : 'Test Area', 'ref' : '52'})
161     place_row(names={'name' : 'No Area'})
162     place_row(names={'name' : 'Holzstrasse'})
163
164     tok = tokenizer_factory()
165     tok.init_new_db(test_config)
166
167     assert temp_db_cursor.table_exists('word')
168
169
170 def test_init_from_project(test_config, tokenizer_factory):
171     tok = tokenizer_factory()
172     tok.init_new_db(test_config)
173
174     tok = tokenizer_factory()
175     tok.init_from_project(test_config)
176
177     assert tok.loader is not None
178
179
180 def test_update_sql_functions(db_prop, temp_db_cursor,
181                               tokenizer_factory, test_config, table_factory,
182                               monkeypatch):
183     tok = tokenizer_factory()
184     tok.init_new_db(test_config)
185
186     table_factory('test', 'txt TEXT')
187
188     func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
189     func_file.write_text("""INSERT INTO test VALUES (1133)""")
190
191     tok.update_sql_functions(test_config)
192
193     test_content = temp_db_cursor.row_set('SELECT * FROM test')
194     assert test_content == set((('1133', ), ))
195
196
197 def test_normalize_postcode(analyzer):
198     with analyzer() as anl:
199         anl.normalize_postcode('123') == '123'
200         anl.normalize_postcode('ab-34 ') == 'AB-34'
201         anl.normalize_postcode('38 Б') == '38 Б'
202
203
204 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
205     table_factory('location_postcode', 'postcode TEXT',
206                   content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
207
208     with analyzer() as anl:
209         anl.update_postcodes_from_db()
210
211     assert word_table.count() == 3
212     assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
213
214
215 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
216     table_factory('location_postcode', 'postcode TEXT',
217                   content=(('1234',), ('45BC', ), ('XX45', )))
218     word_table.add_postcode(' 1234', '1234')
219     word_table.add_postcode(' 5678', '5678')
220
221     with analyzer() as anl:
222         anl.update_postcodes_from_db()
223
224     assert word_table.count() == 3
225     assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
226
227
228 def test_update_special_phrase_empty_table(analyzer, word_table):
229     with analyzer() as anl:
230         anl.update_special_phrases([
231             ("König  bei", "amenity", "royal", "near"),
232             ("Könige ", "amenity", "royal", "-"),
233             ("street", "highway", "primary", "in")
234         ], True)
235
236     assert word_table.get_special() \
237                == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
238                    ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
239                    ('STREET', 'street', 'highway', 'primary', 'in')}
240
241
242 def test_update_special_phrase_delete_all(analyzer, word_table):
243     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
244     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
245
246     assert word_table.count_special() == 2
247
248     with analyzer() as anl:
249         anl.update_special_phrases([], True)
250
251     assert word_table.count_special() == 0
252
253
254 def test_update_special_phrases_no_replace(analyzer, word_table):
255     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
256     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
257
258     assert word_table.count_special() == 2
259
260     with analyzer() as anl:
261         anl.update_special_phrases([], False)
262
263     assert word_table.count_special() == 2
264
265
266 def test_update_special_phrase_modify(analyzer, word_table):
267     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
268     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
269
270     assert word_table.count_special() == 2
271
272     with analyzer() as anl:
273         anl.update_special_phrases([
274             ('prison', 'amenity', 'prison', 'in'),
275             ('bar', 'highway', 'road', '-'),
276             ('garden', 'leisure', 'garden', 'near')
277         ], True)
278
279     assert word_table.get_special() \
280                == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
281                    ('BAR', 'bar', 'highway', 'road', None),
282                    ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
283
284
285 def test_add_country_names_new(analyzer, word_table):
286     with analyzer() as anl:
287         anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
288
289     assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
290
291
292 def test_add_country_names_extend(analyzer, word_table):
293     word_table.add_country('ch', 'SCHWEIZ')
294
295     with analyzer() as anl:
296         anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
297
298     assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
299
300
301 class TestPlaceNames:
302
303     @pytest.fixture(autouse=True)
304     def setup(self, analyzer, sql_functions):
305         sanitizers = [{'step': 'split-name-list'},
306                       {'step': 'strip-brace-terms'}]
307         with analyzer(sanitizers=sanitizers) as anl:
308             self.analyzer = anl
309             yield anl
310
311
312     def expect_name_terms(self, info, *expected_terms):
313         tokens = self.analyzer.get_word_token_info(expected_terms)
314         for token in tokens:
315             assert token[2] is not None, "No token for {0}".format(token)
316
317         assert eval(info['names']) == set((t[2] for t in tokens))
318
319
320     def process_named_place(self, names):
321         return self.analyzer.process_place(PlaceInfo({'name': names}))
322
323
324     def test_simple_names(self):
325         info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
326
327         self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
328
329
330     @pytest.mark.parametrize('sep', [',' , ';'])
331     def test_names_with_separator(self, sep):
332         info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
333
334         self.expect_name_terms(info, '#New York', '#Big Apple',
335                                      'new', 'york', 'big', 'apple')
336
337
338     def test_full_names_with_bracket(self):
339         info = self.process_named_place({'name': 'Houseboat (left)'})
340
341         self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
342                                      'houseboat', 'left')
343
344
345     def test_country_name(self, word_table):
346         place = PlaceInfo({'name' : {'name': 'Norge'},
347                            'country_code': 'no',
348                            'rank_address': 4,
349                            'class': 'boundary',
350                            'type': 'administrative'})
351
352         info = self.analyzer.process_place(place)
353
354         self.expect_name_terms(info, '#norge', 'norge')
355         assert word_table.get_country() == {('no', 'NORGE')}
356
357
358 class TestPlaceAddress:
359
360     @pytest.fixture(autouse=True)
361     def setup(self, analyzer, sql_functions):
362         with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
363             self.analyzer = anl
364             yield anl
365
366
367     def process_address(self, **kwargs):
368         return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
369
370
371     def name_token_set(self, *expected_terms):
372         tokens = self.analyzer.get_word_token_info(expected_terms)
373         for token in tokens:
374             assert token[2] is not None, "No token for {0}".format(token)
375
376         return set((t[2] for t in tokens))
377
378
379     @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
380     def test_process_place_postcode(self, word_table, pcode):
381         self.process_address(postcode=pcode)
382
383         assert word_table.get_postcodes() == {pcode, }
384
385
386     @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
387     def test_process_place_bad_postcode(self, word_table, pcode):
388         self.process_address(postcode=pcode)
389
390         assert not word_table.get_postcodes()
391
392
393     @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
394     def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
395         info = self.process_address(housenumber=hnr)
396
397         assert info['hnr'] == hnr.upper()
398         assert info['hnr_tokens'] == "{-1}"
399
400
401     def test_process_place_housenumbers_lists(self, getorcreate_hnr_id):
402         info = self.process_address(conscriptionnumber='1; 2;3')
403
404         assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
405         assert info['hnr_tokens'] == "{-1,-2,-3}"
406
407
408     def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
409         info = self.process_address(housenumber='134',
410                                     conscriptionnumber='134',
411                                     streetnumber='99a')
412
413         assert set(info['hnr'].split(';')) == set(('134', '99A'))
414         assert info['hnr_tokens'] == "{-1,-2}"
415
416
417     def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
418         info = self.process_address(housenumber="45")
419         assert info['hnr_tokens'] == "{-1}"
420
421         info = self.process_address(housenumber="46")
422         assert info['hnr_tokens'] == "{-2}"
423
424         info = self.process_address(housenumber="41;45")
425         assert eval(info['hnr_tokens']) == {-1, -3}
426
427         info = self.process_address(housenumber="41")
428         assert eval(info['hnr_tokens']) == {-3}
429
430
431     def test_process_place_street(self):
432         info = self.process_address(street='Grand Road')
433
434         assert eval(info['street']) == self.name_token_set('GRAND', 'ROAD')
435
436
437     def test_process_place_street_empty(self):
438         info = self.process_address(street='🜵')
439
440         assert 'street' not in info
441
442
443     def test_process_place_place(self):
444         info = self.process_address(place='Honu Lulu')
445
446         assert eval(info['place']) == self.name_token_set('HONU', 'LULU')
447
448
449     def test_process_place_place_empty(self):
450         info = self.process_address(place='🜵')
451
452         assert 'place' not in info
453
454
455     def test_process_place_address_terms(self):
456         info = self.process_address(country='de', city='Zwickau', state='Sachsen',
457                                     suburb='Zwickau', street='Hauptstr',
458                                     full='right behind the church')
459
460         city = self.name_token_set('ZWICKAU')
461         state = self.name_token_set('SACHSEN')
462
463         result = {k: eval(v) for k,v in info['addr'].items()}
464
465         assert result == {'city': city, 'suburb': city, 'state': state}
466
467
468     def test_process_place_address_terms_empty(self):
469         info = self.process_address(country='de', city=' ', street='Hauptstr',
470                                     full='right behind the church')
471
472         assert 'addr' not in info
473