2 Tests for Legacy ICU tokenizer.
9 from nominatim.tokenizer import legacy_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
14 from mock_icu_word_table import MockIcuWordTable
17 def word_table(temp_db_conn):
18 return MockIcuWordTable(temp_db_conn)
22 def test_config(def_config, tmp_path):
23 def_config.project_dir = tmp_path / 'project'
24 def_config.project_dir.mkdir()
26 sqldir = tmp_path / 'sql'
28 (sqldir / 'tokenizer').mkdir()
29 (sqldir / 'tokenizer' / 'legacy_icu_tokenizer.sql').write_text("SELECT 'a'")
30 shutil.copy(str(def_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer_tables.sql'),
31 str(sqldir / 'tokenizer' / 'icu_tokenizer_tables.sql'))
33 def_config.lib_dir.sql = sqldir
39 def tokenizer_factory(dsn, tmp_path, property_table,
40 sql_preprocessor, place_table, word_table):
41 (tmp_path / 'tokenizer').mkdir()
44 return legacy_icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
50 def db_prop(temp_db_conn):
51 def _get_db_property(name):
52 return properties.get_property(temp_db_conn, name)
54 return _get_db_property
58 def analyzer(tokenizer_factory, test_config, monkeypatch,
59 temp_db_with_extensions, tmp_path):
60 sql = tmp_path / 'sql' / 'tokenizer' / 'legacy_icu_tokenizer.sql'
61 sql.write_text("SELECT 'a';")
63 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
64 tok = tokenizer_factory()
65 tok.init_new_db(test_config)
68 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
69 variants=('~gasse -> gasse', 'street => st', )):
70 cfgfile = tmp_path / 'analyser_test_config.yaml'
71 with cfgfile.open('w') as stream:
72 cfgstr = {'normalization' : list(norm),
73 'transliteration' : list(trans),
74 'variants' : [ {'words': list(variants)}]}
75 yaml.dump(cfgstr, stream)
76 tok.naming_rules = ICUNameProcessorRules(loader=ICURuleLoader(cfgfile))
78 return tok.name_analyzer()
84 def getorcreate_full_word(temp_db_cursor):
85 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
86 norm_term TEXT, lookup_terms TEXT[],
88 OUT partial_tokens INT[])
91 partial_terms TEXT[] = '{}'::TEXT[];
96 SELECT min(word_id) INTO full_token
97 FROM word WHERE info->>'word' = norm_term and type = 'W';
99 IF full_token IS NULL THEN
100 full_token := nextval('seq_word');
101 INSERT INTO word (word_id, word_token, type, info)
102 SELECT full_token, lookup_term, 'W',
103 json_build_object('word', norm_term, 'count', 0)
104 FROM unnest(lookup_terms) as lookup_term;
107 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
109 IF NOT (ARRAY[term] <@ partial_terms) THEN
110 partial_terms := partial_terms || term;
114 partial_tokens := '{}'::INT[];
115 FOR term IN SELECT unnest(partial_terms) LOOP
116 SELECT min(word_id), max(info->>'count') INTO term_id, term_count
117 FROM word WHERE word_token = term and type = 'w';
119 IF term_id IS NULL THEN
120 term_id := nextval('seq_word');
122 INSERT INTO word (word_id, word_token, type, info)
123 VALUES (term_id, term, 'w', json_build_object('count', term_count));
126 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
127 partial_tokens := partial_tokens || term_id;
137 def getorcreate_hnr_id(temp_db_cursor):
138 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
139 RETURNS INTEGER AS $$
140 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
143 def test_init_new(tokenizer_factory, test_config, monkeypatch, db_prop):
144 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
146 tok = tokenizer_factory()
147 tok.init_new_db(test_config)
149 assert db_prop(legacy_icu_tokenizer.DBCFG_TERM_NORMALIZATION) == ':: lower();'
150 assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) is not None
153 def test_init_word_table(tokenizer_factory, test_config, place_row, word_table):
154 place_row(names={'name' : 'Test Area', 'ref' : '52'})
155 place_row(names={'name' : 'No Area'})
156 place_row(names={'name' : 'Holzstrasse'})
158 tok = tokenizer_factory()
159 tok.init_new_db(test_config)
161 assert word_table.get_partial_words() == {('test', 1),
162 ('no', 1), ('area', 2),
163 ('holz', 1), ('strasse', 1),
167 def test_init_from_project(monkeypatch, test_config, tokenizer_factory):
168 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
169 monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '90300')
170 tok = tokenizer_factory()
171 tok.init_new_db(test_config)
174 tok = tokenizer_factory()
175 tok.init_from_project()
177 assert tok.naming_rules is not None
178 assert tok.term_normalization == ':: lower();'
179 assert tok.max_word_frequency == '90300'
182 def test_update_sql_functions(db_prop, temp_db_cursor,
183 tokenizer_factory, test_config, table_factory,
185 monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '1133')
186 tok = tokenizer_factory()
187 tok.init_new_db(test_config)
190 assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) == '1133'
192 table_factory('test', 'txt TEXT')
194 func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_icu_tokenizer.sql'
195 func_file.write_text("""INSERT INTO test VALUES ('{{max_word_freq}}')""")
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, getorcreate_full_word):
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, getorcreate_full_word):
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_search']) == self.name_token_set('#HONU LULU',
444 assert eval(info['place_match']) == self.name_token_set('#HONU LULU')
447 def test_process_place_place_empty(self):
448 info = self.process_address(place='🜵')
450 assert 'place_search' not in info
451 assert 'place_match' not in info
454 def test_process_place_address_terms(self):
455 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
456 suburb='Zwickau', street='Hauptstr',
457 full='right behind the church')
459 city_full = self.name_token_set('#ZWICKAU')
460 city_all = self.name_token_set('#ZWICKAU', 'ZWICKAU')
461 state_full = self.name_token_set('#SACHSEN')
462 state_all = self.name_token_set('#SACHSEN', 'SACHSEN')
464 result = {k: [eval(v[0]), eval(v[1])] for k,v in info['addr'].items()}
466 assert result == {'city': [city_all, city_full],
467 'suburb': [city_all, city_full],
468 'state': [state_all, state_full]}
471 def test_process_place_address_terms_empty(self):
472 info = self.process_address(country='de', city=' ', street='Hauptstr',
473 full='right behind the church')
475 assert 'addr' not in info