2 Tests for Legacy ICU tokenizer.
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
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(project_env, tmp_path):
24 sqldir = tmp_path / 'sql'
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'))
31 project_env.lib_dir.sql = sqldir
37 def tokenizer_factory(dsn, tmp_path, property_table,
38 sql_preprocessor, place_table, word_table):
39 (tmp_path / 'tokenizer').mkdir()
42 return icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
48 def db_prop(temp_db_conn):
49 def _get_db_property(name):
50 return properties.get_property(temp_db_conn, name)
52 return _get_db_property
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';")
61 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
62 tok = tokenizer_factory()
63 tok.init_new_db(test_config)
66 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
67 variants=('~gasse -> gasse', 'street => st', ),
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)
77 return tok.name_analyzer()
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
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[],
96 OUT partial_tokens INT[])
99 partial_terms TEXT[] = '{}'::TEXT[];
104 SELECT min(word_id) INTO full_token
105 FROM word WHERE info->>'word' = norm_term and type = 'W';
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;
115 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
117 IF NOT (ARRAY[term] <@ partial_terms) THEN
118 partial_terms := partial_terms || term;
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';
127 IF term_id IS NULL THEN
128 term_id := nextval('seq_word');
130 INSERT INTO word (word_id, word_token, type, info)
131 VALUES (term_id, term, 'w', json_build_object('count', term_count));
134 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
135 partial_tokens := partial_tokens || term_id;
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""")
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_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 Б'
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',)))
208 with analyzer() as anl:
209 anl.update_postcodes_from_db()
211 assert word_table.count() == 3
212 assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
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')
221 with analyzer() as anl:
222 anl.update_postcodes_from_db()
224 assert word_table.count() == 3
225 assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
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")
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')}
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)
246 assert word_table.count_special() == 2
248 with analyzer() as anl:
249 anl.update_special_phrases([], True)
251 assert word_table.count_special() == 0
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)
258 assert word_table.count_special() == 2
260 with analyzer() as anl:
261 anl.update_special_phrases([], False)
263 assert word_table.count_special() == 2
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)
270 assert word_table.count_special() == 2
272 with analyzer() as anl:
273 anl.update_special_phrases([
274 ('prison', 'amenity', 'prison', 'in'),
275 ('bar', 'highway', 'road', '-'),
276 ('garden', 'leisure', 'garden', 'near')
279 assert word_table.get_special() \
280 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
281 ('BAR', 'bar', 'highway', 'road', None),
282 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
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'})
289 assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
292 def test_add_country_names_extend(analyzer, word_table):
293 word_table.add_country('ch', 'SCHWEIZ')
295 with analyzer() as anl:
296 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
298 assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
301 class TestPlaceNames:
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:
312 def expect_name_terms(self, info, *expected_terms):
313 tokens = self.analyzer.get_word_token_info(expected_terms)
315 assert token[2] is not None, "No token for {0}".format(token)
317 assert eval(info['names']) == set((t[2] for t in tokens))
320 def process_named_place(self, names):
321 return self.analyzer.process_place(PlaceInfo({'name': names}))
324 def test_simple_names(self):
325 info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
327 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
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'))})
334 self.expect_name_terms(info, '#New York', '#Big Apple',
335 'new', 'york', 'big', 'apple')
338 def test_full_names_with_bracket(self):
339 info = self.process_named_place({'name': 'Houseboat (left)'})
341 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
345 def test_country_name(self, word_table):
346 place = PlaceInfo({'name' : {'name': 'Norge'},
347 'country_code': 'no',
350 'type': 'administrative'})
352 info = self.analyzer.process_place(place)
354 self.expect_name_terms(info, '#norge', 'norge')
355 assert word_table.get_country() == {('no', 'NORGE')}
358 class TestPlaceAddress:
360 @pytest.fixture(autouse=True)
361 def setup(self, analyzer, sql_functions):
362 with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
367 def process_address(self, **kwargs):
368 return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
371 def name_token_set(self, *expected_terms):
372 tokens = self.analyzer.get_word_token_info(expected_terms)
374 assert token[2] is not None, "No token for {0}".format(token)
376 return set((t[2] for t in tokens))
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)
383 assert word_table.get_postcodes() == {pcode, }
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)
390 assert not word_table.get_postcodes()
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)
397 assert info['hnr'] == hnr.upper()
398 assert info['hnr_tokens'] == "{-1}"
401 def test_process_place_housenumbers_lists(self, getorcreate_hnr_id):
402 info = self.process_address(conscriptionnumber='1; 2;3')
404 assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
405 assert info['hnr_tokens'] == "{-1,-2,-3}"
408 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
409 info = self.process_address(housenumber='134',
410 conscriptionnumber='134',
413 assert set(info['hnr'].split(';')) == set(('134', '99A'))
414 assert info['hnr_tokens'] == "{-1,-2}"
417 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
418 info = self.process_address(housenumber="45")
419 assert info['hnr_tokens'] == "{-1}"
421 info = self.process_address(housenumber="46")
422 assert info['hnr_tokens'] == "{-2}"
424 info = self.process_address(housenumber="41;45")
425 assert eval(info['hnr_tokens']) == {-1, -3}
427 info = self.process_address(housenumber="41")
428 assert eval(info['hnr_tokens']) == {-3}
431 def test_process_place_street(self):
432 info = self.process_address(street='Grand Road')
434 assert eval(info['street']) == self.name_token_set('GRAND', 'ROAD')
437 def test_process_place_street_empty(self):
438 info = self.process_address(street='🜵')
440 assert 'street' not in info
443 def test_process_place_place(self):
444 info = self.process_address(place='Honu Lulu')
446 assert eval(info['place']) == self.name_token_set('HONU', 'LULU')
449 def test_process_place_place_empty(self):
450 info = self.process_address(place='🜵')
452 assert 'place' not in info
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')
460 city = self.name_token_set('ZWICKAU')
461 state = self.name_token_set('SACHSEN')
463 result = {k: eval(v) for k,v in info['addr'].items()}
465 assert result == {'city': city, 'suburb': city, 'state': state}
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')
472 assert 'addr' not in info