]> git.openstreetmap.org Git - nominatim.git/blob - test/python/tokenizer/test_icu.py
Merge pull request #3692 from lonvia/word-lookup-variants
[nominatim.git] / test / python / tokenizer / test_icu.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2025 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Tests for ICU tokenizer.
9 """
10 import yaml
11 import itertools
12
13 import pytest
14
15 from nominatim_db.tokenizer import icu_tokenizer
16 import nominatim_db.tokenizer.icu_rule_loader
17 from nominatim_db.db import properties
18 from nominatim_db.db.sql_preprocessor import SQLPreprocessor
19 from nominatim_db.data.place_info import PlaceInfo
20
21 from mock_icu_word_table import MockIcuWordTable
22
23
24 @pytest.fixture
25 def word_table(temp_db_conn):
26     return MockIcuWordTable(temp_db_conn)
27
28
29 @pytest.fixture
30 def test_config(project_env, tmp_path):
31     sqldir = tmp_path / 'sql'
32     sqldir.mkdir()
33     (sqldir / 'tokenizer').mkdir()
34     (sqldir / 'tokenizer' / 'icu_tokenizer.sql').write_text("SELECT 'a'")
35
36     project_env.lib_dir.sql = sqldir
37
38     return project_env
39
40
41 @pytest.fixture
42 def tokenizer_factory(dsn, tmp_path, property_table,
43                       sql_preprocessor, place_table, word_table):
44     (tmp_path / 'tokenizer').mkdir()
45
46     def _maker():
47         return icu_tokenizer.create(dsn, tmp_path / 'tokenizer')
48
49     return _maker
50
51
52 @pytest.fixture
53 def db_prop(temp_db_conn):
54     def _get_db_property(name):
55         return properties.get_property(temp_db_conn, name)
56
57     return _get_db_property
58
59
60 @pytest.fixture
61 def analyzer(tokenizer_factory, test_config, monkeypatch,
62              temp_db_with_extensions, tmp_path):
63     sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
64     sql.write_text("SELECT 'a';")
65
66     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
67     tok = tokenizer_factory()
68     tok.init_new_db(test_config)
69     monkeypatch.undo()
70
71     def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
72                      variants=('~gasse -> gasse', 'street => st', ),
73                      sanitizers=[], with_housenumber=False,
74                      with_postcode=False):
75         cfgstr = {'normalization': list(norm),
76                   'sanitizers': sanitizers,
77                   'transliteration': list(trans),
78                   'token-analysis': [{'analyzer': 'generic',
79                                       'variants': [{'words': list(variants)}]}]}
80         if with_housenumber:
81             cfgstr['token-analysis'].append({'id': '@housenumber',
82                                              'analyzer': 'housenumbers'})
83         if with_postcode:
84             cfgstr['token-analysis'].append({'id': '@postcode',
85                                              'analyzer': 'postcodes'})
86         (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
87         tok.loader = nominatim_db.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
88
89         return tok.name_analyzer()
90
91     return _mk_analyser
92
93
94 @pytest.fixture
95 def sql_functions(temp_db_conn, def_config, src_dir):
96     orig_sql = def_config.lib_dir.sql
97     def_config.lib_dir.sql = src_dir / 'lib-sql'
98     sqlproc = SQLPreprocessor(temp_db_conn, def_config)
99     sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
100     sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
101     def_config.lib_dir.sql = orig_sql
102
103
104 @pytest.fixture
105 def getorcreate_full_word(temp_db_cursor):
106     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
107                                                  norm_term TEXT, lookup_terms TEXT[],
108                                                  OUT full_token INT,
109                                                  OUT partial_tokens INT[])
110   AS $$
111 DECLARE
112   partial_terms TEXT[] = '{}'::TEXT[];
113   term TEXT;
114   term_id INTEGER;
115   term_count INTEGER;
116 BEGIN
117   SELECT min(word_id) INTO full_token
118     FROM word WHERE info->>'word' = norm_term and type = 'W';
119
120   IF full_token IS NULL THEN
121     full_token := nextval('seq_word');
122     INSERT INTO word (word_id, word_token, type, info)
123       SELECT full_token, lookup_term, 'W',
124              json_build_object('word', norm_term, 'count', 0)
125         FROM unnest(lookup_terms) as lookup_term;
126   END IF;
127
128   FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
129     term := trim(term);
130     IF NOT (ARRAY[term] <@ partial_terms) THEN
131       partial_terms := partial_terms || term;
132     END IF;
133   END LOOP;
134
135   partial_tokens := '{}'::INT[];
136   FOR term IN SELECT unnest(partial_terms) LOOP
137     SELECT min(word_id), max(info->>'count') INTO term_id, term_count
138       FROM word WHERE word_token = term and type = 'w';
139
140     IF term_id IS NULL THEN
141       term_id := nextval('seq_word');
142       term_count := 0;
143       INSERT INTO word (word_id, word_token, type, info)
144         VALUES (term_id, term, 'w', json_build_object('count', term_count));
145     END IF;
146
147     IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
148       partial_tokens := partial_tokens || term_id;
149     END IF;
150   END LOOP;
151 END;
152 $$
153 LANGUAGE plpgsql;
154                               """)
155
156
157 def test_init_new(tokenizer_factory, test_config, db_prop):
158     tok = tokenizer_factory()
159     tok.init_new_db(test_config)
160
161     prop = db_prop(nominatim_db.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES)
162
163     assert prop.startswith(':: lower ();')
164
165
166 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
167     place_row(names={'name': 'Test Area', 'ref': '52'})
168     place_row(names={'name': 'No Area'})
169     place_row(names={'name': 'Holzstrasse'})
170
171     tok = tokenizer_factory()
172     tok.init_new_db(test_config)
173
174     assert temp_db_cursor.table_exists('word')
175
176
177 def test_init_from_project(test_config, tokenizer_factory):
178     tok = tokenizer_factory()
179     tok.init_new_db(test_config)
180
181     tok = tokenizer_factory()
182     tok.init_from_project(test_config)
183
184     assert tok.loader is not None
185
186
187 def test_update_sql_functions(db_prop, temp_db_cursor,
188                               tokenizer_factory, test_config, table_factory,
189                               monkeypatch):
190     tok = tokenizer_factory()
191     tok.init_new_db(test_config)
192
193     table_factory('test', 'txt TEXT')
194
195     func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
196     func_file.write_text("""INSERT INTO test VALUES (1133)""")
197
198     tok.update_sql_functions(test_config)
199
200     test_content = temp_db_cursor.row_set('SELECT * FROM test')
201     assert test_content == set((('1133', ), ))
202
203
204 def test_finalize_import(tokenizer_factory, temp_db_cursor,
205                          test_config, sql_preprocessor_cfg):
206     tok = tokenizer_factory()
207     tok.init_new_db(test_config)
208
209     assert not temp_db_cursor.index_exists('word', 'idx_word_word_id')
210
211     tok.finalize_import(test_config)
212
213     assert temp_db_cursor.index_exists('word', 'idx_word_word_id')
214
215
216 def test_check_database(test_config, tokenizer_factory,
217                         temp_db_cursor, sql_preprocessor_cfg):
218     tok = tokenizer_factory()
219     tok.init_new_db(test_config)
220
221     assert tok.check_database(test_config) is None
222
223
224 def test_update_statistics_reverse_only(word_table, tokenizer_factory, test_config):
225     tok = tokenizer_factory()
226     tok.update_statistics(test_config)
227
228
229 def test_update_statistics(word_table, table_factory, temp_db_cursor,
230                            tokenizer_factory, test_config):
231     word_table.add_full_word(1000, 'hello')
232     word_table.add_full_word(1001, 'bye')
233     word_table.add_full_word(1002, 'town')
234     table_factory('search_name',
235                   'place_id BIGINT, name_vector INT[], nameaddress_vector INT[]',
236                   [(12, [1000], [1001]), (13, [1001], [1002]), (14, [1000, 1001], [1002])])
237     tok = tokenizer_factory()
238
239     tok.update_statistics(test_config)
240
241     assert temp_db_cursor.row_set("""SELECT word_id,
242                                             (info->>'count')::int,
243                                             (info->>'addr_count')::int
244                                      FROM word
245                                      WHERE type = 'W'""") == \
246         {(1000, 2, None), (1001, 2, None), (1002, None, 2)}
247
248
249 def test_normalize_postcode(analyzer):
250     with analyzer() as anl:
251         anl.normalize_postcode('123') == '123'
252         anl.normalize_postcode('ab-34 ') == 'AB-34'
253         anl.normalize_postcode('38 Б') == '38 Б'
254
255
256 class TestPostcodes:
257
258     @pytest.fixture(autouse=True)
259     def setup(self, analyzer, sql_functions):
260         sanitizers = [{'step': 'clean-postcodes'}]
261         with analyzer(sanitizers=sanitizers, with_postcode=True) as anl:
262             self.analyzer = anl
263             yield anl
264
265     def process_postcode(self, cc, postcode):
266         return self.analyzer.process_place(PlaceInfo({'country_code': cc,
267                                                       'address': {'postcode': postcode}}))
268
269     def test_update_postcodes_deleted(self, word_table):
270         word_table.add_postcode(' 1234', '1234')
271         word_table.add_postcode(' 5678', '5678')
272
273         self.analyzer.update_postcodes_from_db()
274
275         assert word_table.count() == 0
276
277     def test_process_place_postcode_simple(self, word_table):
278         info = self.process_postcode('de', '12345')
279
280         assert info['postcode'] == '12345'
281
282     def test_process_place_postcode_with_space(self, word_table):
283         info = self.process_postcode('in', '123 567')
284
285         assert info['postcode'] == '123567'
286
287
288 def test_update_special_phrase_empty_table(analyzer, word_table):
289     with analyzer() as anl:
290         anl.update_special_phrases([
291             ("König  bei", "amenity", "royal", "near"),
292             ("Könige ", "amenity", "royal", "-"),
293             ("street", "highway", "primary", "in")
294         ], True)
295
296     assert word_table.get_special() \
297         == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
298             ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
299             ('STREET', 'street', 'highway', 'primary', 'in')}
300
301
302 def test_update_special_phrase_delete_all(analyzer, word_table):
303     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
304     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
305
306     assert word_table.count_special() == 2
307
308     with analyzer() as anl:
309         anl.update_special_phrases([], True)
310
311     assert word_table.count_special() == 0
312
313
314 def test_update_special_phrases_no_replace(analyzer, word_table):
315     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
316     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
317
318     assert word_table.count_special() == 2
319
320     with analyzer() as anl:
321         anl.update_special_phrases([], False)
322
323     assert word_table.count_special() == 2
324
325
326 def test_update_special_phrase_modify(analyzer, word_table):
327     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
328     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
329
330     assert word_table.count_special() == 2
331
332     with analyzer() as anl:
333         anl.update_special_phrases([
334             ('prison', 'amenity', 'prison', 'in'),
335             ('bar', 'highway', 'road', '-'),
336             ('garden', 'leisure', 'garden', 'near')
337         ], True)
338
339     assert word_table.get_special() \
340         == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
341             ('BAR', 'bar', 'highway', 'road', None),
342             ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
343
344
345 def test_add_country_names_new(analyzer, word_table):
346     with analyzer() as anl:
347         anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
348
349     assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
350
351
352 def test_add_country_names_extend(analyzer, word_table):
353     word_table.add_country('ch', 'SCHWEIZ')
354
355     with analyzer() as anl:
356         anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
357
358     assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
359
360
361 class TestPlaceNames:
362
363     @pytest.fixture(autouse=True)
364     def setup(self, analyzer, sql_functions):
365         sanitizers = [{'step': 'split-name-list'},
366                       {'step': 'strip-brace-terms'}]
367         with analyzer(sanitizers=sanitizers) as anl:
368             self.analyzer = anl
369             yield anl
370
371     def expect_name_terms(self, info, *expected_terms):
372         tokens = self.analyzer.get_word_token_info(expected_terms)
373         for token in tokens:
374             assert token[2] is not None, "No token for {0}".format(token)
375
376         assert eval(info['names']) == set((t[2] for t in tokens))
377
378     def process_named_place(self, names):
379         return self.analyzer.process_place(PlaceInfo({'name': names}))
380
381     def test_simple_names(self):
382         info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
383
384         self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
385
386     @pytest.mark.parametrize('sep', [',', ';'])
387     def test_names_with_separator(self, sep):
388         info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
389
390         self.expect_name_terms(info, '#New York', '#Big Apple',
391                                      'new', 'york', 'big', 'apple')
392
393     def test_full_names_with_bracket(self):
394         info = self.process_named_place({'name': 'Houseboat (left)'})
395
396         self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
397                                      'houseboat', 'left')
398
399     def test_country_name(self, word_table):
400         place = PlaceInfo({'name': {'name': 'Norge'},
401                            'country_code': 'no',
402                            'rank_address': 4,
403                            'class': 'boundary',
404                            'type': 'administrative'})
405
406         info = self.analyzer.process_place(place)
407
408         self.expect_name_terms(info, '#norge', 'norge')
409         assert word_table.get_country() == {('no', 'NORGE')}
410
411
412 class TestPlaceAddress:
413
414     @pytest.fixture(autouse=True)
415     def setup(self, analyzer, sql_functions):
416         hnr = {'step': 'clean-housenumbers',
417                'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
418         with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
419             self.analyzer = anl
420             yield anl
421
422     @pytest.fixture
423     def getorcreate_hnr_id(self, temp_db_cursor):
424         temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
425                                   RETURNS INTEGER AS $$
426                                     SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
427
428     def process_address(self, **kwargs):
429         return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
430
431     def name_token_set(self, *expected_terms):
432         tokens = self.analyzer.get_word_token_info(expected_terms)
433         for token in tokens:
434             assert token[2] is not None, "No token for {0}".format(token)
435
436         return set((t[2] for t in tokens))
437
438     @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
439     def test_process_place_postcode(self, word_table, pcode):
440         info = self.process_address(postcode=pcode)
441
442         assert info['postcode'] == pcode
443
444     @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
445     def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
446         info = self.process_address(housenumber=hnr)
447
448         assert info['hnr'] == hnr.upper()
449         assert info['hnr_tokens'] == "{-1}"
450
451     def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
452         info = self.process_address(housenumber='134',
453                                     conscriptionnumber='134',
454                                     streetnumber='99a')
455
456         assert set(info['hnr'].split(';')) == set(('134', '99A'))
457         assert info['hnr_tokens'] == "{-1,-2}"
458
459     def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
460         info = self.process_address(housenumber="45")
461         assert info['hnr_tokens'] == "{-1}"
462
463         info = self.process_address(housenumber="46")
464         assert info['hnr_tokens'] == "{-2}"
465
466         info = self.process_address(housenumber="41;45")
467         assert eval(info['hnr_tokens']) == {-1, -3}
468
469         info = self.process_address(housenumber="41")
470         assert eval(info['hnr_tokens']) == {-3}
471
472     def test_process_place_street(self):
473         self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
474         info = self.process_address(street='Grand Road')
475
476         assert eval(info['street']) == self.name_token_set('#Grand Road')
477
478     def test_process_place_nonexisting_street(self):
479         info = self.process_address(street='Grand Road')
480
481         assert info['street'] == '{}'
482
483     def test_process_place_multiple_street_tags(self):
484         self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road',
485                                                         'ref': '05989'}}))
486         info = self.process_address(**{'street': 'Grand Road',
487                                        'street:sym_ul': '05989'})
488
489         assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
490
491     def test_process_place_street_empty(self):
492         info = self.process_address(street='🜵')
493
494         assert info['street'] == '{}'
495
496     def test_process_place_street_from_cache(self):
497         self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
498         self.process_address(street='Grand Road')
499
500         # request address again
501         info = self.process_address(street='Grand Road')
502
503         assert eval(info['street']) == self.name_token_set('#Grand Road')
504
505     def test_process_place_place(self):
506         info = self.process_address(place='Honu Lulu')
507
508         assert eval(info['place']) == self.name_token_set('HONU', 'LULU', '#HONU LULU')
509
510     def test_process_place_place_extra(self):
511         info = self.process_address(**{'place:en': 'Honu Lulu'})
512
513         assert 'place' not in info
514
515     def test_process_place_place_empty(self):
516         info = self.process_address(place='🜵')
517
518         assert 'place' not in info
519
520     def test_process_place_address_terms(self):
521         info = self.process_address(country='de', city='Zwickau', state='Sachsen',
522                                     suburb='Zwickau', street='Hauptstr',
523                                     full='right behind the church')
524
525         city = self.name_token_set('ZWICKAU', '#ZWICKAU')
526         state = self.name_token_set('SACHSEN', '#SACHSEN')
527
528         result = {k: eval(v) for k, v in info['addr'].items()}
529
530         assert result == {'city': city, 'suburb': city, 'state': state}
531
532     def test_process_place_multiple_address_terms(self):
533         info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
534
535         result = {k: eval(v) for k, v in info['addr'].items()}
536
537         assert result == {'city': self.name_token_set('Bruxelles', '#Bruxelles')}
538
539     def test_process_place_address_terms_empty(self):
540         info = self.process_address(country='de', city=' ', street='Hauptstr',
541                                     full='right behind the church')
542
543         assert 'addr' not in info
544
545
546 class TestPlaceHousenumberWithAnalyser:
547
548     @pytest.fixture(autouse=True)
549     def setup(self, analyzer, sql_functions):
550         hnr = {'step': 'clean-housenumbers',
551                'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
552         with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr],
553                       with_housenumber=True) as anl:
554             self.analyzer = anl
555             yield anl
556
557     @pytest.fixture
558     def getorcreate_hnr_id(self, temp_db_cursor):
559         temp_db_cursor.execute("""
560             CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
561             RETURNS INTEGER AS $$
562                 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
563
564     def process_address(self, **kwargs):
565         return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
566
567     def name_token_set(self, *expected_terms):
568         tokens = self.analyzer.get_word_token_info(expected_terms)
569         for token in tokens:
570             assert token[2] is not None, "No token for {0}".format(token)
571
572         return set((t[2] for t in tokens))
573
574     @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
575     def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
576         info = self.process_address(housenumber=hnr)
577
578         assert info['hnr'] == hnr.upper()
579         assert info['hnr_tokens'] == "{-1}"
580
581     def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
582         info = self.process_address(housenumber='134',
583                                     conscriptionnumber='134',
584                                     streetnumber='99a')
585
586         assert set(info['hnr'].split(';')) == set(('134', '99 A'))
587         assert info['hnr_tokens'] == "{-1,-2}"
588
589     def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
590         info = self.process_address(housenumber="45")
591         assert info['hnr_tokens'] == "{-1}"
592
593         info = self.process_address(housenumber="46")
594         assert info['hnr_tokens'] == "{-2}"
595
596         info = self.process_address(housenumber="41;45")
597         assert eval(info['hnr_tokens']) == {-1, -3}
598
599         info = self.process_address(housenumber="41")
600         assert eval(info['hnr_tokens']) == {-3}
601
602
603 class TestUpdateWordTokens:
604
605     @pytest.fixture(autouse=True)
606     def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
607         table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
608         self.tok = tokenizer_factory()
609
610     @pytest.fixture
611     def search_entry(self, temp_db_cursor):
612         place_id = itertools.count(1000)
613
614         def _insert(*args):
615             temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
616                                    (next(place_id), list(args)))
617
618         return _insert
619
620     @pytest.fixture(params=['simple', 'analyzed'])
621     def add_housenumber(self, request, word_table):
622         if request.param == 'simple':
623             def _make(hid, hnr):
624                 word_table.add_housenumber(hid, hnr)
625         elif request.param == 'analyzed':
626             def _make(hid, hnr):
627                 word_table.add_housenumber(hid, [hnr])
628
629         return _make
630
631     @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
632     def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
633         word_table.add_housenumber(1000, hnr)
634
635         assert word_table.count_housenumbers() == 1
636         self.tok.update_word_tokens()
637         assert word_table.count_housenumbers() == 0
638
639     def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
640         add_housenumber(1000, '5432')
641
642         assert word_table.count_housenumbers() == 1
643         self.tok.update_word_tokens()
644         assert word_table.count_housenumbers() == 1
645
646     def test_keep_housenumbers_from_search_name_table(self, add_housenumber,
647                                                       word_table, search_entry):
648         add_housenumber(9999, '5432a')
649         add_housenumber(9991, '9 a')
650         search_entry(123, 9999, 34)
651
652         assert word_table.count_housenumbers() == 2
653         self.tok.update_word_tokens()
654         assert word_table.count_housenumbers() == 1
655
656     def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table,
657                                                  placex_table):
658         add_housenumber(9999, '5432a')
659         add_housenumber(9990, '34z')
660         placex_table.add(housenumber='34z')
661         placex_table.add(housenumber='25432a')
662
663         assert word_table.count_housenumbers() == 2
664         self.tok.update_word_tokens()
665         assert word_table.count_housenumbers() == 1
666
667     def test_keep_housenumbers_from_placex_table_hnr_list(self, add_housenumber,
668                                                           word_table, placex_table):
669         add_housenumber(9991, '9 b')
670         add_housenumber(9990, '34z')
671         placex_table.add(housenumber='9 a;9 b;9 c')
672
673         assert word_table.count_housenumbers() == 2
674         self.tok.update_word_tokens()
675         assert word_table.count_housenumbers() == 1