2 Tests for Legacy ICU tokenizer.
9 from nominatim.tokenizer import icu_tokenizer
10 from nominatim.tokenizer.icu_name_processor import ICUNameProcessorRules
11 from nominatim.tokenizer.icu_rule_loader import ICURuleLoader
12 from nominatim.db import properties
13 from nominatim.db.sql_preprocessor import SQLPreprocessor
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', )):
71 cfgstr = {'normalization' : list(norm),
72 'transliteration' : list(trans),
73 'variants' : [ {'words': list(variants)}]}
74 tok.naming_rules = ICUNameProcessorRules(loader=ICURuleLoader(cfgstr))
76 return tok.name_analyzer()
81 def sql_functions(temp_db_conn, def_config, src_dir):
82 orig_sql = def_config.lib_dir.sql
83 def_config.lib_dir.sql = src_dir / 'lib-sql'
84 sqlproc = SQLPreprocessor(temp_db_conn, def_config)
85 sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
86 sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
87 def_config.lib_dir.sql = orig_sql
91 def getorcreate_full_word(temp_db_cursor):
92 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
93 norm_term TEXT, lookup_terms TEXT[],
95 OUT partial_tokens INT[])
98 partial_terms TEXT[] = '{}'::TEXT[];
103 SELECT min(word_id) INTO full_token
104 FROM word WHERE info->>'word' = norm_term and type = 'W';
106 IF full_token IS NULL THEN
107 full_token := nextval('seq_word');
108 INSERT INTO word (word_id, word_token, type, info)
109 SELECT full_token, lookup_term, 'W',
110 json_build_object('word', norm_term, 'count', 0)
111 FROM unnest(lookup_terms) as lookup_term;
114 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
116 IF NOT (ARRAY[term] <@ partial_terms) THEN
117 partial_terms := partial_terms || term;
121 partial_tokens := '{}'::INT[];
122 FOR term IN SELECT unnest(partial_terms) LOOP
123 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
124 FROM word WHERE word_token = term and type = 'w';
126 IF term_id IS NULL THEN
127 term_id := nextval('seq_word');
129 INSERT INTO word (word_id, word_token, type, info)
130 VALUES (term_id, term, 'w', json_build_object('count', term_count));
133 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
134 partial_tokens := partial_tokens || term_id;
144 def getorcreate_hnr_id(temp_db_cursor):
145 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
146 RETURNS INTEGER AS $$
147 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
150 def test_init_new(tokenizer_factory, test_config, monkeypatch, db_prop):
151 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
153 tok = tokenizer_factory()
154 tok.init_new_db(test_config)
156 assert db_prop(icu_tokenizer.DBCFG_TERM_NORMALIZATION) == ':: lower();'
159 def test_init_word_table(tokenizer_factory, test_config, place_row, word_table):
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 word_table.get_partial_words() == {('test', 1),
168 ('no', 1), ('area', 2),
169 ('holz', 1), ('strasse', 1),
173 def test_init_from_project(monkeypatch, test_config, tokenizer_factory):
174 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
175 tok = tokenizer_factory()
176 tok.init_new_db(test_config)
179 tok = tokenizer_factory()
180 tok.init_from_project()
182 assert tok.naming_rules is not None
183 assert tok.term_normalization == ':: lower();'
186 def test_update_sql_functions(db_prop, temp_db_cursor,
187 tokenizer_factory, test_config, table_factory,
189 tok = tokenizer_factory()
190 tok.init_new_db(test_config)
192 table_factory('test', 'txt TEXT')
194 func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
195 func_file.write_text("""INSERT INTO test VALUES (1133)""")
197 tok.update_sql_functions(test_config)
199 test_content = temp_db_cursor.row_set('SELECT * FROM test')
200 assert test_content == set((('1133', ), ))
203 def test_normalize_postcode(analyzer):
204 with analyzer() as anl:
205 anl.normalize_postcode('123') == '123'
206 anl.normalize_postcode('ab-34 ') == 'AB-34'
207 anl.normalize_postcode('38 Б') == '38 Б'
210 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
211 table_factory('location_postcode', 'postcode TEXT',
212 content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
214 with analyzer() as anl:
215 anl.update_postcodes_from_db()
217 assert word_table.count() == 3
218 assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
221 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
222 table_factory('location_postcode', 'postcode TEXT',
223 content=(('1234',), ('45BC', ), ('XX45', )))
224 word_table.add_postcode(' 1234', '1234')
225 word_table.add_postcode(' 5678', '5678')
227 with analyzer() as anl:
228 anl.update_postcodes_from_db()
230 assert word_table.count() == 3
231 assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
234 def test_update_special_phrase_empty_table(analyzer, word_table):
235 with analyzer() as anl:
236 anl.update_special_phrases([
237 ("König bei", "amenity", "royal", "near"),
238 ("Könige ", "amenity", "royal", "-"),
239 ("street", "highway", "primary", "in")
242 assert word_table.get_special() \
243 == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
244 ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
245 ('STREET', 'street', 'highway', 'primary', 'in')}
248 def test_update_special_phrase_delete_all(analyzer, word_table):
249 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
250 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
252 assert word_table.count_special() == 2
254 with analyzer() as anl:
255 anl.update_special_phrases([], True)
257 assert word_table.count_special() == 0
260 def test_update_special_phrases_no_replace(analyzer, word_table):
261 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
262 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
264 assert word_table.count_special() == 2
266 with analyzer() as anl:
267 anl.update_special_phrases([], False)
269 assert word_table.count_special() == 2
272 def test_update_special_phrase_modify(analyzer, word_table):
273 word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
274 word_table.add_special('BAR', 'bar', 'highway', 'road', None)
276 assert word_table.count_special() == 2
278 with analyzer() as anl:
279 anl.update_special_phrases([
280 ('prison', 'amenity', 'prison', 'in'),
281 ('bar', 'highway', 'road', '-'),
282 ('garden', 'leisure', 'garden', 'near')
285 assert word_table.get_special() \
286 == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
287 ('BAR', 'bar', 'highway', 'road', None),
288 ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
291 def test_add_country_names_new(analyzer, word_table):
292 with analyzer() as anl:
293 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
295 assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
298 def test_add_country_names_extend(analyzer, word_table):
299 word_table.add_country('ch', 'SCHWEIZ')
301 with analyzer() as anl:
302 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
304 assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
307 class TestPlaceNames:
309 @pytest.fixture(autouse=True)
310 def setup(self, analyzer, sql_functions):
311 with analyzer() as anl:
316 def expect_name_terms(self, info, *expected_terms):
317 tokens = self.analyzer.get_word_token_info(expected_terms)
320 assert token[2] is not None, "No token for {0}".format(token)
322 assert eval(info['names']) == set((t[2] for t in tokens))
325 def test_simple_names(self):
326 info = self.analyzer.process_place({'name': {'name': 'Soft bAr', 'ref': '34'}})
328 self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
331 @pytest.mark.parametrize('sep', [',' , ';'])
332 def test_names_with_separator(self, sep):
333 info = self.analyzer.process_place({'name': {'name': sep.join(('New York', 'Big Apple'))}})
335 self.expect_name_terms(info, '#New York', '#Big Apple',
336 'new', 'york', 'big', 'apple')
339 def test_full_names_with_bracket(self):
340 info = self.analyzer.process_place({'name': {'name': 'Houseboat (left)'}})
342 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
346 def test_country_name(self, word_table):
347 info = self.analyzer.process_place({'name': {'name': 'Norge'},
348 'country_feature': 'no'})
350 self.expect_name_terms(info, '#norge', 'norge')
351 assert word_table.get_country() == {('no', 'NORGE')}
354 class TestPlaceAddress:
356 @pytest.fixture(autouse=True)
357 def setup(self, analyzer, sql_functions):
358 with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
363 def process_address(self, **kwargs):
364 return self.analyzer.process_place({'address': kwargs})
367 def name_token_set(self, *expected_terms):
368 tokens = self.analyzer.get_word_token_info(expected_terms)
370 assert token[2] is not None, "No token for {0}".format(token)
372 return set((t[2] for t in tokens))
375 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
376 def test_process_place_postcode(self, word_table, pcode):
377 self.process_address(postcode=pcode)
379 assert word_table.get_postcodes() == {pcode, }
382 @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
383 def test_process_place_bad_postcode(self, word_table, pcode):
384 self.process_address(postcode=pcode)
386 assert not word_table.get_postcodes()
389 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
390 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
391 info = self.process_address(housenumber=hnr)
393 assert info['hnr'] == hnr.upper()
394 assert info['hnr_tokens'] == "{-1}"
397 def test_process_place_housenumbers_lists(self, getorcreate_hnr_id):
398 info = self.process_address(conscriptionnumber='1; 2;3')
400 assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
401 assert info['hnr_tokens'] == "{-1,-2,-3}"
404 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
405 info = self.process_address(housenumber='134',
406 conscriptionnumber='134',
409 assert set(info['hnr'].split(';')) == set(('134', '99A'))
410 assert info['hnr_tokens'] == "{-1,-2}"
413 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
414 info = self.process_address(housenumber="45")
415 assert info['hnr_tokens'] == "{-1}"
417 info = self.process_address(housenumber="46")
418 assert info['hnr_tokens'] == "{-2}"
420 info = self.process_address(housenumber="41;45")
421 assert eval(info['hnr_tokens']) == {-1, -3}
423 info = self.process_address(housenumber="41")
424 assert eval(info['hnr_tokens']) == {-3}
427 def test_process_place_street(self):
428 info = self.process_address(street='Grand Road')
430 assert eval(info['street']) == self.name_token_set('GRAND', 'ROAD')
433 def test_process_place_street_empty(self):
434 info = self.process_address(street='🜵')
436 assert 'street' not in info
439 def test_process_place_place(self):
440 info = self.process_address(place='Honu Lulu')
442 assert eval(info['place']) == self.name_token_set('HONU', 'LULU')
445 def test_process_place_place_empty(self):
446 info = self.process_address(place='🜵')
448 assert 'place' not in info
451 def test_process_place_address_terms(self):
452 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
453 suburb='Zwickau', street='Hauptstr',
454 full='right behind the church')
456 city = self.name_token_set('ZWICKAU')
457 state = self.name_token_set('SACHSEN')
459 result = {k: eval(v) for k,v in info['addr'].items()}
461 assert result == {'city': city, 'suburb': city, 'state': state}
464 def test_process_place_address_terms_empty(self):
465 info = self.process_address(country='de', city=' ', street='Hauptstr',
466 full='right behind the church')
468 assert 'addr' not in info