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
16 def test_config(def_config, tmp_path):
17 def_config.project_dir = tmp_path / 'project'
18 def_config.project_dir.mkdir()
20 sqldir = tmp_path / 'sql'
22 (sqldir / 'tokenizer').mkdir()
23 (sqldir / 'tokenizer' / 'legacy_icu_tokenizer.sql').write_text("SELECT 'a'")
24 shutil.copy(str(def_config.lib_dir.sql / 'tokenizer' / 'legacy_tokenizer_tables.sql'),
25 str(sqldir / 'tokenizer' / 'legacy_tokenizer_tables.sql'))
27 def_config.lib_dir.sql = sqldir
33 def tokenizer_factory(dsn, tmp_path, property_table,
34 sql_preprocessor, place_table, word_table):
35 (tmp_path / 'tokenizer').mkdir()
38 return legacy_icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
44 def db_prop(temp_db_conn):
45 def _get_db_property(name):
46 return properties.get_property(temp_db_conn, name)
48 return _get_db_property
52 def analyzer(tokenizer_factory, test_config, monkeypatch,
53 temp_db_with_extensions, tmp_path):
54 sql = tmp_path / 'sql' / 'tokenizer' / 'legacy_icu_tokenizer.sql'
55 sql.write_text("SELECT 'a';")
57 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
58 tok = tokenizer_factory()
59 tok.init_new_db(test_config)
62 def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
63 variants=('~gasse -> gasse', 'street => st', )):
64 cfgfile = tmp_path / 'analyser_test_config.yaml'
65 with cfgfile.open('w') as stream:
66 cfgstr = {'normalization' : list(norm),
67 'transliteration' : list(trans),
68 'variants' : [ {'words': list(variants)}]}
69 yaml.dump(cfgstr, stream)
70 tok.naming_rules = ICUNameProcessorRules(loader=ICURuleLoader(cfgfile))
72 return tok.name_analyzer()
78 def getorcreate_full_word(temp_db_cursor):
79 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
80 norm_term TEXT, lookup_terms TEXT[],
82 OUT partial_tokens INT[])
85 partial_terms TEXT[] = '{}'::TEXT[];
90 SELECT min(word_id) INTO full_token
91 FROM word WHERE word = norm_term and class is null and country_code is null;
93 IF full_token IS NULL THEN
94 full_token := nextval('seq_word');
95 INSERT INTO word (word_id, word_token, word, search_name_count)
96 SELECT full_token, ' ' || lookup_term, norm_term, 0 FROM unnest(lookup_terms) as lookup_term;
99 FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
101 IF NOT (ARRAY[term] <@ partial_terms) THEN
102 partial_terms := partial_terms || term;
106 partial_tokens := '{}'::INT[];
107 FOR term IN SELECT unnest(partial_terms) LOOP
108 SELECT min(word_id), max(search_name_count) INTO term_id, term_count
109 FROM word WHERE word_token = term and class is null and country_code is null;
111 IF term_id IS NULL THEN
112 term_id := nextval('seq_word');
114 INSERT INTO word (word_id, word_token, search_name_count)
115 VALUES (term_id, term, 0);
118 IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
119 partial_tokens := partial_tokens || term_id;
129 def getorcreate_hnr_id(temp_db_cursor):
130 temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
131 RETURNS INTEGER AS $$
132 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
135 def test_init_new(tokenizer_factory, test_config, monkeypatch, db_prop):
136 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
138 tok = tokenizer_factory()
139 tok.init_new_db(test_config)
141 assert db_prop(legacy_icu_tokenizer.DBCFG_TERM_NORMALIZATION) == ':: lower();'
142 assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) is not None
145 def test_init_word_table(tokenizer_factory, test_config, place_row, word_table):
146 place_row(names={'name' : 'Test Area', 'ref' : '52'})
147 place_row(names={'name' : 'No Area'})
148 place_row(names={'name' : 'Holzstrasse'})
150 tok = tokenizer_factory()
151 tok.init_new_db(test_config)
153 assert word_table.get_partial_words() == {('test', 1),
154 ('no', 1), ('area', 2),
155 ('holz', 1), ('strasse', 1),
159 def test_init_from_project(monkeypatch, test_config, tokenizer_factory):
160 monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
161 monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '90300')
162 tok = tokenizer_factory()
163 tok.init_new_db(test_config)
166 tok = tokenizer_factory()
167 tok.init_from_project()
169 assert tok.naming_rules is not None
170 assert tok.term_normalization == ':: lower();'
171 assert tok.max_word_frequency == '90300'
174 def test_update_sql_functions(db_prop, temp_db_cursor,
175 tokenizer_factory, test_config, table_factory,
177 monkeypatch.setenv('NOMINATIM_MAX_WORD_FREQUENCY', '1133')
178 tok = tokenizer_factory()
179 tok.init_new_db(test_config)
182 assert db_prop(legacy_icu_tokenizer.DBCFG_MAXWORDFREQ) == '1133'
184 table_factory('test', 'txt TEXT')
186 func_file = test_config.lib_dir.sql / 'tokenizer' / 'legacy_icu_tokenizer.sql'
187 func_file.write_text("""INSERT INTO test VALUES ('{{max_word_freq}}')""")
189 tok.update_sql_functions(test_config)
191 test_content = temp_db_cursor.row_set('SELECT * FROM test')
192 assert test_content == set((('1133', ), ))
195 def test_normalize_postcode(analyzer):
196 with analyzer() as anl:
197 anl.normalize_postcode('123') == '123'
198 anl.normalize_postcode('ab-34 ') == 'AB-34'
199 anl.normalize_postcode('38 Б') == '38 Б'
202 def test_update_postcodes_from_db_empty(analyzer, table_factory, word_table):
203 table_factory('location_postcode', 'postcode TEXT',
204 content=(('1234',), ('12 34',), ('AB23',), ('1234',)))
206 with analyzer() as anl:
207 anl.update_postcodes_from_db()
209 assert word_table.count() == 3
210 assert word_table.get_postcodes() == {'1234', '12 34', 'AB23'}
213 def test_update_postcodes_from_db_add_and_remove(analyzer, table_factory, word_table):
214 table_factory('location_postcode', 'postcode TEXT',
215 content=(('1234',), ('45BC', ), ('XX45', )))
216 word_table.add_postcode(' 1234', '1234')
217 word_table.add_postcode(' 5678', '5678')
219 with analyzer() as anl:
220 anl.update_postcodes_from_db()
222 assert word_table.count() == 3
223 assert word_table.get_postcodes() == {'1234', '45BC', 'XX45'}
226 def test_update_special_phrase_empty_table(analyzer, word_table):
227 with analyzer() as anl:
228 anl.update_special_phrases([
229 ("König bei", "amenity", "royal", "near"),
230 ("Könige ", "amenity", "royal", "-"),
231 ("street", "highway", "primary", "in")
234 assert word_table.get_special() \
235 == {(' KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
236 (' KÖNIGE', 'Könige', 'amenity', 'royal', None),
237 (' STREET', 'street', 'highway', 'primary', 'in')}
240 def test_update_special_phrase_delete_all(analyzer, word_table):
241 word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
242 word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
244 assert word_table.count_special() == 2
246 with analyzer() as anl:
247 anl.update_special_phrases([], True)
249 assert word_table.count_special() == 0
252 def test_update_special_phrases_no_replace(analyzer, word_table):
253 word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
254 word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
256 assert word_table.count_special() == 2
258 with analyzer() as anl:
259 anl.update_special_phrases([], False)
261 assert word_table.count_special() == 2
264 def test_update_special_phrase_modify(analyzer, word_table):
265 word_table.add_special(' FOO', 'foo', 'amenity', 'prison', 'in')
266 word_table.add_special(' BAR', 'bar', 'highway', 'road', None)
268 assert word_table.count_special() == 2
270 with analyzer() as anl:
271 anl.update_special_phrases([
272 ('prison', 'amenity', 'prison', 'in'),
273 ('bar', 'highway', 'road', '-'),
274 ('garden', 'leisure', 'garden', 'near')
277 assert word_table.get_special() \
278 == {(' PRISON', 'prison', 'amenity', 'prison', 'in'),
279 (' BAR', 'bar', 'highway', 'road', None),
280 (' GARDEN', 'garden', 'leisure', 'garden', 'near')}
283 def test_add_country_names_new(analyzer, word_table):
284 with analyzer() as anl:
285 anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
287 assert word_table.get_country() == {('es', ' ESPAGÑA'), ('es', ' SPAIN')}
290 def test_add_country_names_extend(analyzer, word_table):
291 word_table.add_country('ch', ' SCHWEIZ')
293 with analyzer() as anl:
294 anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
296 assert word_table.get_country() == {('ch', ' SCHWEIZ'), ('ch', ' SUISSE')}
299 class TestPlaceNames:
301 @pytest.fixture(autouse=True)
302 def setup(self, analyzer, getorcreate_full_word):
303 with analyzer() as anl:
308 def expect_name_terms(self, info, *expected_terms):
309 tokens = self.analyzer.get_word_token_info(expected_terms)
311 assert token[2] is not None, "No token for {0}".format(token)
313 assert eval(info['names']) == set((t[2] for t in tokens))
316 def test_simple_names(self):
317 info = self.analyzer.process_place({'name': {'name': 'Soft bAr', 'ref': '34'}})
319 self.expect_name_terms(info, '#Soft bAr', '#34','Soft', 'bAr', '34')
322 @pytest.mark.parametrize('sep', [',' , ';'])
323 def test_names_with_separator(self, sep):
324 info = self.analyzer.process_place({'name': {'name': sep.join(('New York', 'Big Apple'))}})
326 self.expect_name_terms(info, '#New York', '#Big Apple',
327 'new', 'york', 'big', 'apple')
330 def test_full_names_with_bracket(self):
331 info = self.analyzer.process_place({'name': {'name': 'Houseboat (left)'}})
333 self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
337 def test_country_name(self, word_table):
338 info = self.analyzer.process_place({'name': {'name': 'Norge'},
339 'country_feature': 'no'})
341 self.expect_name_terms(info, '#norge', 'norge')
342 assert word_table.get_country() == {('no', ' NORGE')}
345 class TestPlaceAddress:
347 @pytest.fixture(autouse=True)
348 def setup(self, analyzer, getorcreate_full_word):
349 with analyzer(trans=(":: upper()", "'🜵' > ' '")) as anl:
354 def process_address(self, **kwargs):
355 return self.analyzer.process_place({'address': kwargs})
358 def name_token_set(self, *expected_terms):
359 tokens = self.analyzer.get_word_token_info(expected_terms)
361 assert token[2] is not None, "No token for {0}".format(token)
363 return set((t[2] for t in tokens))
366 @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
367 def test_process_place_postcode(self, word_table, pcode):
368 self.process_address(postcode=pcode)
370 assert word_table.get_postcodes() == {pcode, }
373 @pytest.mark.parametrize('pcode', ['12:23', 'ab;cd;f', '123;836'])
374 def test_process_place_bad_postcode(self, word_table, pcode):
375 self.process_address(postcode=pcode)
377 assert not word_table.get_postcodes()
380 @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
381 def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
382 info = self.process_address(housenumber=hnr)
384 assert info['hnr'] == hnr.upper()
385 assert info['hnr_tokens'] == "{-1}"
388 def test_process_place_housenumbers_lists(self, getorcreate_hnr_id):
389 info = self.process_address(conscriptionnumber='1; 2;3')
391 assert set(info['hnr'].split(';')) == set(('1', '2', '3'))
392 assert info['hnr_tokens'] == "{-1,-2,-3}"
395 def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
396 info = self.process_address(housenumber='134',
397 conscriptionnumber='134',
400 assert set(info['hnr'].split(';')) == set(('134', '99A'))
401 assert info['hnr_tokens'] == "{-1,-2}"
404 def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
405 info = self.process_address(housenumber="45")
406 assert info['hnr_tokens'] == "{-1}"
408 info = self.process_address(housenumber="46")
409 assert info['hnr_tokens'] == "{-2}"
411 info = self.process_address(housenumber="41;45")
412 assert eval(info['hnr_tokens']) == {-1, -3}
414 info = self.process_address(housenumber="41")
415 assert eval(info['hnr_tokens']) == {-3}
418 def test_process_place_street(self):
419 info = self.process_address(street='Grand Road')
421 assert eval(info['street']) == self.name_token_set('#GRAND ROAD')
424 def test_process_place_street_empty(self):
425 info = self.process_address(street='🜵')
427 assert 'street' not in info
430 def test_process_place_place(self):
431 info = self.process_address(place='Honu Lulu')
433 assert eval(info['place_search']) == self.name_token_set('#HONU LULU',
435 assert eval(info['place_match']) == self.name_token_set('#HONU LULU')
438 def test_process_place_place_empty(self):
439 info = self.process_address(place='🜵')
441 assert 'place_search' not in info
442 assert 'place_match' not in info
445 def test_process_place_address_terms(self):
446 info = self.process_address(country='de', city='Zwickau', state='Sachsen',
447 suburb='Zwickau', street='Hauptstr',
448 full='right behind the church')
450 city_full = self.name_token_set('#ZWICKAU')
451 city_all = self.name_token_set('#ZWICKAU', 'ZWICKAU')
452 state_full = self.name_token_set('#SACHSEN')
453 state_all = self.name_token_set('#SACHSEN', 'SACHSEN')
455 result = {k: [eval(v[0]), eval(v[1])] for k,v in info['addr'].items()}
457 assert result == {'city': [city_all, city_full],
458 'suburb': [city_all, city_full],
459 'state': [state_all, state_full]}
462 def test_process_place_address_terms_empty(self):
463 info = self.process_address(country='de', city=' ', street='Hauptstr',
464 full='right behind the church')
466 assert 'addr' not in info