2 Tests for Legacy ICU tokenizer.
9 from nominatim.tokenizer import icu_tokenizer
10 from nominatim.tokenizer.icu_rule_loader import ICURuleLoader
11 from nominatim.db import properties
12 from nominatim.db.sql_preprocessor import SQLPreprocessor
13 from nominatim.indexer.place_info import PlaceInfo
15 from mock_icu_word_table import MockIcuWordTable
18 def word_table(temp_db_conn):
19 return MockIcuWordTable(temp_db_conn)
23 def test_config(def_config, tmp_path):
24 def_config.project_dir = tmp_path / 'project'
25 def_config.project_dir.mkdir()
27 sqldir = tmp_path / 'sql'
29 (sqldir / 'tokenizer').mkdir()
30 (sqldir / 'tokenizer' / 'icu_tokenizer.sql').write_text("SELECT 'a'")
31 shutil.copy(str(def_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer_tables.sql'),
32 str(sqldir / 'tokenizer' / 'icu_tokenizer_tables.sql'))
34 def_config.lib_dir.sql = sqldir
40 def tokenizer_factory(dsn, tmp_path, property_table,
41 sql_preprocessor, place_table, word_table):
42 (tmp_path / 'tokenizer').mkdir()
45 return icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
51 def db_prop(temp_db_conn):
52 def _get_db_property(name):
53 return properties.get_property(temp_db_conn, name)
55 return _get_db_property
59 def analyzer(tokenizer_factory, test_config, monkeypatch,
60 temp_db_with_extensions, tmp_path):
61 sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
62 sql.write_text("SELECT 'a';")
64 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
65 tok = tokenizer_factory()
66 tok.init_new_db(test_config)
69 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
70 variants=('~gasse -> gasse', 'street => st', ),
72 cfgstr = {'normalization' : list(norm),
73 'sanitizers' : sanitizers,
74 'transliteration' : list(trans),
75 'variants' : [ {'words': list(variants)}]}
76 (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
77 tok.loader = ICURuleLoader(test_config)
79 return tok.name_analyzer()
84 def sql_functions(temp_db_conn, def_config, src_dir):
85 orig_sql = def_config.lib_dir.sql
86 def_config.lib_dir.sql = src_dir / 'lib-sql'
87 sqlproc = SQLPreprocessor(temp_db_conn, def_config)
88 sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
89 sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
90 def_config.lib_dir.sql = orig_sql
94 def getorcreate_full_word(temp_db_cursor):
95 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
96 norm_term TEXT, lookup_terms TEXT[],
98 OUT partial_tokens INT[])
101 partial_terms TEXT[] = '{}'::TEXT[];
106 SELECT min(word_id) INTO full_token
107 FROM word WHERE info->>'word' = norm_term and type = 'W';
109 IF full_token IS NULL THEN
110 full_token := nextval('seq_word');
111 INSERT INTO word (word_id, word_token, type, info)
112 SELECT full_token, lookup_term, 'W',
113 json_build_object('word', norm_term, 'count', 0)
114 FROM unnest(lookup_terms) as lookup_term;
117 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
119 IF NOT (ARRAY[term] <@ partial_terms) THEN
120 partial_terms := partial_terms || term;
124 partial_tokens := '{}'::INT[];
125 FOR term IN SELECT unnest(partial_terms) LOOP
126 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
127 FROM word WHERE word_token = term and type = 'w';
129 IF term_id IS NULL THEN
130 term_id := nextval('seq_word');
132 INSERT INTO word (word_id, word_token, type, info)
133 VALUES (term_id, term, 'w', json_build_object('count', term_count));
136 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
137 partial_tokens := partial_tokens || term_id;
147 def getorcreate_hnr_id(temp_db_cursor):
148 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
149 RETURNS INTEGER AS $$
150 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
153 def test_init_new(tokenizer_factory, test_config, monkeypatch, db_prop):
154 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
156 tok = tokenizer_factory()
157 tok.init_new_db(test_config)
159 assert db_prop(icu_tokenizer.DBCFG_TERM_NORMALIZATION) == ':: lower();'
162 def test_init_word_table(tokenizer_factory, test_config, place_row, word_table):
163 place_row(names={'name' : 'Test Area', 'ref' : '52'})
164 place_row(names={'name' : 'No Area'})
165 place_row(names={'name' : 'Holzstrasse'})
167 tok = tokenizer_factory()
168 tok.init_new_db(test_config)
170 assert word_table.get_partial_words() == {('test', 1),
171 ('no', 1), ('area', 2),
172 ('holz', 1), ('strasse', 1),
176 def test_init_from_project(monkeypatch, test_config, tokenizer_factory):
177 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
178 tok = tokenizer_factory()
179 tok.init_new_db(test_config)
182 tok = tokenizer_factory()
183 tok.init_from_project(test_config)
185 assert tok.loader is not None
186 assert tok.term_normalization == ':: lower();'
189 def test_update_sql_functions(db_prop, temp_db_cursor,
190 tokenizer_factory, test_config, table_factory,
192 tok = tokenizer_factory()
193 tok.init_new_db(test_config)
195 table_factory('test', 'txt TEXT')
197 func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
198 func_file.write_text("""INSERT INTO test VALUES (1133)""")
200 tok.update_sql_functions(test_config)
202 test_content = temp_db_cursor.row_set('SELECT * FROM test')
203 assert test_content == set((('1133', ), ))
206 def test_normalize_postcode(analyzer):
207 with analyzer() as anl:
208 anl.normalize_postcode('123') == '123'
209 anl.normalize_postcode('ab-34 ') == 'AB-34'
210 anl.normalize_postcode('38 Б') == '38 Б'
213 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
214 table_factory('location_postcode', 'postcode TEXT',
215 content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
217 with analyzer() as anl:
218 anl.update_postcodes_from_db()
220 assert word_table.count() == 3
221 assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
224 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
225 table_factory('location_postcode', 'postcode TEXT',
226 content=(('1234',), ('45BC', ), ('XX45', )))
227 word_table.add_postcode(' 1234', '1234')
228 word_table.add_postcode(' 5678', '5678')
230 with analyzer() as anl:
231 anl.update_postcodes_from_db()
233 assert word_table.count() == 3
234 assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
237 def test_update_special_phrase_empty_table(analyzer, word_table):
238 with analyzer() as anl:
239 anl.update_special_phrases([
240 ("König bei", "amenity", "royal", "near"),
241 ("Könige ", "amenity", "royal", "-"),
242 ("street", "highway", "primary", "in")
245 assert word_table.get_special() \
246 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
247 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
248 ('STREET', 'street', 'highway', 'primary', 'in')}
251 def test_update_special_phrase_delete_all(analyzer, word_table):
252 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
253 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
255 assert word_table.count_special() == 2
257 with analyzer() as anl:
258 anl.update_special_phrases([], True)
260 assert word_table.count_special() == 0
263 def test_update_special_phrases_no_replace(analyzer, word_table):
264 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
265 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
267 assert word_table.count_special() == 2
269 with analyzer() as anl:
270 anl.update_special_phrases([], False)
272 assert word_table.count_special() == 2
275 def test_update_special_phrase_modify(analyzer, word_table):
276 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
277 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
279 assert word_table.count_special() == 2
281 with analyzer() as anl:
282 anl.update_special_phrases([
283 ('prison', 'amenity', 'prison', 'in'),
284 ('bar', 'highway', 'road', '-'),
285 ('garden', 'leisure', 'garden', 'near')
288 assert word_table.get_special() \
289 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
290 ('BAR', 'bar', 'highway', 'road', None),
291 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
294 def test_add_country_names_new(analyzer, word_table):
295 with analyzer() as anl:
296 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
298 assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
301 def test_add_country_names_extend(analyzer, word_table):
302 word_table.add_country('ch', 'SCHWEIZ')
304 with analyzer() as anl:
305 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
307 assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
310 class TestPlaceNames:
312 @pytest.fixture(autouse=True)
313 def setup(self, analyzer, sql_functions):
314 sanitizers = [{'step': 'split-name-list'},
315 {'step': 'strip-brace-terms'}]
316 with analyzer(sanitizers=sanitizers) as anl:
321 def expect_name_terms(self, info, *expected_terms):
322 tokens = self.analyzer.get_word_token_info(expected_terms)
324 assert token[2] is not None, "No token for {0}".format(token)
326 assert eval(info['names']) == set((t[2] for t in tokens))
329 def process_named_place(self, names):
330 return self.analyzer.process_place(PlaceInfo({'name': names}))
333 def test_simple_names(self):
334 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
336 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
339 @pytest.mark.parametrize('sep', [',' , ';'])
340 def test_names_with_separator(self, sep):
341 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
343 self.expect_name_terms(info, '#New York', '#Big Apple',
344 'new', 'york', 'big', 'apple')
347 def test_full_names_with_bracket(self):
348 info = self.process_named_place({'name': 'Houseboat (left)'})
350 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
354 def test_country_name(self, word_table):
355 place = PlaceInfo({'name' : {'name': 'Norge'},
356 'country_code': 'no',
359 'type': 'administrative'})
361 info = self.analyzer.process_place(place)
363 self.expect_name_terms(info, '#norge', 'norge')
364 assert word_table.get_country() == {('no', 'NORGE')}
367 class TestPlaceAddress:
369 @pytest.fixture(autouse=True)
370 def setup(self, analyzer, sql_functions):
371 with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
376 def process_address(self, **kwargs):
377 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
380 def name_token_set(self, *expected_terms):
381 tokens = self.analyzer.get_word_token_info(expected_terms)
383 assert token[2] is not None, "No token for {0}".format(token)
385 return set((t[2] for t in tokens))
388 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
389 def test_process_place_postcode(self, word_table, pcode):
390 self.process_address(postcode=pcode)
392 assert word_table.get_postcodes() == {pcode, }
395 @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
396 def test_process_place_bad_postcode(self, word_table, pcode):
397 self.process_address(postcode=pcode)
399 assert not word_table.get_postcodes()
402 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
403 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
404 info = self.process_address(housenumber=hnr)
406 assert info['hnr'] == hnr.upper()
407 assert info['hnr_tokens'] == "{-1}"
410 def test_process_place_housenumbers_lists(self, getorcreate_hnr_id):
411 info = self.process_address(conscriptionnumber='1; 2;3')
413 assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
414 assert info['hnr_tokens'] == "{-1,-2,-3}"
417 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
418 info = self.process_address(housenumber='134',
419 conscriptionnumber='134',
422 assert set(info['hnr'].split(';')) == set(('134', '99A'))
423 assert info['hnr_tokens'] == "{-1,-2}"
426 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
427 info = self.process_address(housenumber="45")
428 assert info['hnr_tokens'] == "{-1}"
430 info = self.process_address(housenumber="46")
431 assert info['hnr_tokens'] == "{-2}"
433 info = self.process_address(housenumber="41;45")
434 assert eval(info['hnr_tokens']) == {-1, -3}
436 info = self.process_address(housenumber="41")
437 assert eval(info['hnr_tokens']) == {-3}
440 def test_process_place_street(self):
441 info = self.process_address(street='Grand Road')
443 assert eval(info['street']) == self.name_token_set('GRAND', 'ROAD')
446 def test_process_place_street_empty(self):
447 info = self.process_address(street='🜵')
449 assert 'street' not in info
452 def test_process_place_place(self):
453 info = self.process_address(place='Honu Lulu')
455 assert eval(info['place']) == self.name_token_set('HONU', 'LULU')
458 def test_process_place_place_empty(self):
459 info = self.process_address(place='🜵')
461 assert 'place' not in info
464 def test_process_place_address_terms(self):
465 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
466 suburb='Zwickau', street='Hauptstr',
467 full='right behind the church')
469 city = self.name_token_set('ZWICKAU')
470 state = self.name_token_set('SACHSEN')
472 result = {k: eval(v) for k,v in info['addr'].items()}
474 assert result == {'city': city, 'suburb': city, 'state': state}
477 def test_process_place_address_terms_empty(self):
478 info = self.process_address(country='de', city=' ', street='Hauptstr',
479 full='right behind the church')
481 assert 'addr' not in info