1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Tests for ICU tokenizer.
15 from nominatim.tokenizer import icu_tokenizer
16 import nominatim.tokenizer.icu_rule_loader
17 from nominatim.db import properties
18 from nominatim.db.sql_preprocessor import SQLPreprocessor
19 from nominatim.indexer.place_info import PlaceInfo
21 from mock_icu_word_table import MockIcuWordTable
24 def word_table(temp_db_conn):
25 return MockIcuWordTable(temp_db_conn)
29 def test_config(project_env, tmp_path):
30 sqldir = tmp_path / 'sql'
32 (sqldir / 'tokenizer').mkdir()
33 (sqldir / 'tokenizer' / 'icu_tokenizer.sql').write_text("SELECT 'a'")
34 shutil.copy(str(project_env.lib_dir.sql / 'tokenizer' / 'icu_tokenizer_tables.sql'),
35 str(sqldir / 'tokenizer' / 'icu_tokenizer_tables.sql'))
37 project_env.lib_dir.sql = sqldir
43 def tokenizer_factory(dsn, tmp_path, property_table,
44 sql_preprocessor, place_table, word_table):
45 (tmp_path / 'tokenizer').mkdir()
48 return icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
54 def db_prop(temp_db_conn):
55 def _get_db_property(name):
56 return properties.get_property(temp_db_conn, name)
58 return _get_db_property
62 def analyzer(tokenizer_factory, test_config, monkeypatch,
63 temp_db_with_extensions, tmp_path):
64 sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
65 sql.write_text("SELECT 'a';")
67 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
68 tok = tokenizer_factory()
69 tok.init_new_db(test_config)
72 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
73 variants=('~gasse -> gasse', 'street => st', ),
75 cfgstr = {'normalization': list(norm),
76 'sanitizers': sanitizers,
77 'transliteration': list(trans),
78 'token-analysis': [{'analyzer': 'generic',
79 'variants': [{'words': list(variants)}]}]}
80 (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
81 tok.loader = nominatim.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
83 return tok.name_analyzer()
88 def sql_functions(temp_db_conn, def_config, src_dir):
89 orig_sql = def_config.lib_dir.sql
90 def_config.lib_dir.sql = src_dir / 'lib-sql'
91 sqlproc = SQLPreprocessor(temp_db_conn, def_config)
92 sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
93 sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
94 def_config.lib_dir.sql = orig_sql
98 def getorcreate_full_word(temp_db_cursor):
99 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
100 norm_term TEXT, lookup_terms TEXT[],
102 OUT partial_tokens INT[])
105 partial_terms TEXT[] = '{}'::TEXT[];
110 SELECT min(word_id) INTO full_token
111 FROM word WHERE info->>'word' = norm_term and type = 'W';
113 IF full_token IS NULL THEN
114 full_token := nextval('seq_word');
115 INSERT INTO word (word_id, word_token, type, info)
116 SELECT full_token, lookup_term, 'W',
117 json_build_object('word', norm_term, 'count', 0)
118 FROM unnest(lookup_terms) as lookup_term;
121 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
123 IF NOT (ARRAY[term] <@ partial_terms) THEN
124 partial_terms := partial_terms || term;
128 partial_tokens := '{}'::INT[];
129 FOR term IN SELECT unnest(partial_terms) LOOP
130 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
131 FROM word WHERE word_token = term and type = 'w';
133 IF term_id IS NULL THEN
134 term_id := nextval('seq_word');
136 INSERT INTO word (word_id, word_token, type, info)
137 VALUES (term_id, term, 'w', json_build_object('count', term_count));
140 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
141 partial_tokens := partial_tokens || term_id;
151 def test_init_new(tokenizer_factory, test_config, db_prop):
152 tok = tokenizer_factory()
153 tok.init_new_db(test_config)
155 assert db_prop(nominatim.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES) \
156 .startswith(':: lower ();')
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'})
164 tok = tokenizer_factory()
165 tok.init_new_db(test_config)
167 assert temp_db_cursor.table_exists('word')
170 def test_init_from_project(test_config, tokenizer_factory):
171 tok = tokenizer_factory()
172 tok.init_new_db(test_config)
174 tok = tokenizer_factory()
175 tok.init_from_project(test_config)
177 assert tok.loader is not None
180 def test_update_sql_functions(db_prop, temp_db_cursor,
181 tokenizer_factory, test_config, table_factory,
183 tok = tokenizer_factory()
184 tok.init_new_db(test_config)
186 table_factory('test', 'txt TEXT')
188 func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
189 func_file.write_text("""INSERT INTO test VALUES (1133)""")
191 tok.update_sql_functions(test_config)
193 test_content = temp_db_cursor.row_set('SELECT * FROM test')
194 assert test_content == set((('1133', ), ))
197 def test_finalize_import(tokenizer_factory, temp_db_conn,
198 temp_db_cursor, test_config, sql_preprocessor_cfg):
199 func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_indices.sql'
200 func_file.write_text("""CREATE FUNCTION test() RETURNS TEXT
201 AS $$ SELECT 'b'::text $$ LANGUAGE SQL""")
203 tok = tokenizer_factory()
204 tok.init_new_db(test_config)
206 tok.finalize_import(test_config)
208 temp_db_cursor.scalar('SELECT test()') == 'b'
211 def test_check_database(test_config, tokenizer_factory,
212 temp_db_cursor, sql_preprocessor_cfg):
213 tok = tokenizer_factory()
214 tok.init_new_db(test_config)
216 assert tok.check_database(test_config) is None
219 def test_update_statistics_reverse_only(word_table, tokenizer_factory):
220 tok = tokenizer_factory()
221 tok.update_statistics()
224 def test_update_statistics(word_table, table_factory, temp_db_cursor, tokenizer_factory):
225 word_table.add_full_word(1000, 'hello')
226 table_factory('search_name',
227 'place_id BIGINT, name_vector INT[]',
229 tok = tokenizer_factory()
231 tok.update_statistics()
233 assert temp_db_cursor.scalar("""SELECT count(*) FROM word
235 (info->>'count')::int > 0""") > 0
238 def test_normalize_postcode(analyzer):
239 with analyzer() as anl:
240 anl.normalize_postcode('123') == '123'
241 anl.normalize_postcode('ab-34 ') == 'AB-34'
242 anl.normalize_postcode('38 Б') == '38 Б'
245 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
246 table_factory('location_postcode', 'postcode TEXT',
247 content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
249 with analyzer() as anl:
250 anl.update_postcodes_from_db()
252 assert word_table.count() == 3
253 assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
256 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
257 table_factory('location_postcode', 'postcode TEXT',
258 content=(('1234',), ('45BC', ), ('XX45', )))
259 word_table.add_postcode(' 1234', '1234')
260 word_table.add_postcode(' 5678', '5678')
262 with analyzer() as anl:
263 anl.update_postcodes_from_db()
265 assert word_table.count() == 3
266 assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
269 def test_update_special_phrase_empty_table(analyzer, word_table):
270 with analyzer() as anl:
271 anl.update_special_phrases([
272 ("König bei", "amenity", "royal", "near"),
273 ("Könige ", "amenity", "royal", "-"),
274 ("street", "highway", "primary", "in")
277 assert word_table.get_special() \
278 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
279 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
280 ('STREET', 'street', 'highway', 'primary', 'in')}
283 def test_update_special_phrase_delete_all(analyzer, word_table):
284 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
285 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
287 assert word_table.count_special() == 2
289 with analyzer() as anl:
290 anl.update_special_phrases([], True)
292 assert word_table.count_special() == 0
295 def test_update_special_phrases_no_replace(analyzer, word_table):
296 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
297 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
299 assert word_table.count_special() == 2
301 with analyzer() as anl:
302 anl.update_special_phrases([], False)
304 assert word_table.count_special() == 2
307 def test_update_special_phrase_modify(analyzer, word_table):
308 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
309 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
311 assert word_table.count_special() == 2
313 with analyzer() as anl:
314 anl.update_special_phrases([
315 ('prison', 'amenity', 'prison', 'in'),
316 ('bar', 'highway', 'road', '-'),
317 ('garden', 'leisure', 'garden', 'near')
320 assert word_table.get_special() \
321 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
322 ('BAR', 'bar', 'highway', 'road', None),
323 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
326 def test_add_country_names_new(analyzer, word_table):
327 with analyzer() as anl:
328 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
330 assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
333 def test_add_country_names_extend(analyzer, word_table):
334 word_table.add_country('ch', 'SCHWEIZ')
336 with analyzer() as anl:
337 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
339 assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
342 class TestPlaceNames:
344 @pytest.fixture(autouse=True)
345 def setup(self, analyzer, sql_functions):
346 sanitizers = [{'step': 'split-name-list'},
347 {'step': 'strip-brace-terms'}]
348 with analyzer(sanitizers=sanitizers) as anl:
353 def expect_name_terms(self, info, *expected_terms):
354 tokens = self.analyzer.get_word_token_info(expected_terms)
356 assert token[2] is not None, "No token for {0}".format(token)
358 assert eval(info['names']) == set((t[2] for t in tokens))
361 def process_named_place(self, names):
362 return self.analyzer.process_place(PlaceInfo({'name': names}))
365 def test_simple_names(self):
366 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
368 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
371 @pytest.mark.parametrize('sep', [',' , ';'])
372 def test_names_with_separator(self, sep):
373 info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
375 self.expect_name_terms(info, '#New York', '#Big Apple',
376 'new', 'york', 'big', 'apple')
379 def test_full_names_with_bracket(self):
380 info = self.process_named_place({'name': 'Houseboat (left)'})
382 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
386 def test_country_name(self, word_table):
387 place = PlaceInfo({'name' : {'name': 'Norge'},
388 'country_code': 'no',
391 'type': 'administrative'})
393 info = self.analyzer.process_place(place)
395 self.expect_name_terms(info, '#norge', 'norge')
396 assert word_table.get_country() == {('no', 'NORGE')}
399 class TestPlaceAddress:
401 @pytest.fixture(autouse=True)
402 def setup(self, analyzer, sql_functions):
403 hnr = {'step': 'clean-housenumbers',
404 'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
405 with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
411 def getorcreate_hnr_id(self, temp_db_cursor):
412 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
413 RETURNS INTEGER AS $$
414 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
417 def process_address(self, **kwargs):
418 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
421 def name_token_set(self, *expected_terms):
422 tokens = self.analyzer.get_word_token_info(expected_terms)
424 assert token[2] is not None, "No token for {0}".format(token)
426 return set((t[2] for t in tokens))
429 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
430 def test_process_place_postcode(self, word_table, pcode):
431 self.process_address(postcode=pcode)
433 assert word_table.get_postcodes() == {pcode, }
436 @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
437 def test_process_place_bad_postcode(self, word_table, pcode):
438 self.process_address(postcode=pcode)
440 assert not word_table.get_postcodes()
443 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
444 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
445 info = self.process_address(housenumber=hnr)
447 assert info['hnr'] == hnr.upper()
448 assert info['hnr_tokens'] == "{-1}"
451 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
452 info = self.process_address(housenumber='134',
453 conscriptionnumber='134',
456 assert set(info['hnr'].split(';')) == set(('134', '99A'))
457 assert info['hnr_tokens'] == "{-1,-2}"
460 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
461 info = self.process_address(housenumber="45")
462 assert info['hnr_tokens'] == "{-1}"
464 info = self.process_address(housenumber="46")
465 assert info['hnr_tokens'] == "{-2}"
467 info = self.process_address(housenumber="41;45")
468 assert eval(info['hnr_tokens']) == {-1, -3}
470 info = self.process_address(housenumber="41")
471 assert eval(info['hnr_tokens']) == {-3}
474 def test_process_place_street(self):
475 self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road'}}))
476 info = self.process_address(street='Grand Road')
478 assert eval(info['street']) == self.name_token_set('#Grand Road')
481 def test_process_place_nonexisting_street(self):
482 info = self.process_address(street='Grand Road')
484 assert 'street' not in info
487 def test_process_place_multiple_street_tags(self):
488 self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road',
490 info = self.process_address(**{'street': 'Grand Road',
491 'street:sym_ul': '05989'})
493 assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
496 def test_process_place_street_empty(self):
497 info = self.process_address(street='🜵')
499 assert 'street' not in info
502 def test_process_place_street_from_cache(self):
503 self.analyzer.process_place(PlaceInfo({'name': {'name' : 'Grand Road'}}))
504 self.process_address(street='Grand Road')
506 # request address again
507 info = self.process_address(street='Grand Road')
509 assert eval(info['street']) == self.name_token_set('#Grand Road')
512 def test_process_place_place(self):
513 info = self.process_address(place='Honu Lulu')
515 assert eval(info['place']) == self.name_token_set('HONU', 'LULU')
518 def test_process_place_place_extra(self):
519 info = self.process_address(**{'place:en': 'Honu Lulu'})
521 assert 'place' not in info
524 def test_process_place_place_empty(self):
525 info = self.process_address(place='🜵')
527 assert 'place' not in info
530 def test_process_place_address_terms(self):
531 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
532 suburb='Zwickau', street='Hauptstr',
533 full='right behind the church')
535 city = self.name_token_set('ZWICKAU')
536 state = self.name_token_set('SACHSEN')
538 result = {k: eval(v) for k,v in info['addr'].items()}
540 assert result == {'city': city, 'suburb': city, 'state': state}
543 def test_process_place_multiple_address_terms(self):
544 info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
546 result = {k: eval(v) for k,v in info['addr'].items()}
548 assert result == {'city': self.name_token_set('Bruxelles')}
551 def test_process_place_address_terms_empty(self):
552 info = self.process_address(country='de', city=' ', street='Hauptstr',
553 full='right behind the church')
555 assert 'addr' not in info