]> git.openstreetmap.org Git - nominatim.git/blob - test/python/tokenizer/test_icu.py
enable flake for Python tests
[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     table_factory('search_name',
234                   'place_id BIGINT, name_vector INT[], nameaddress_vector INT[]',
235                   [(12, [1000], [1001])])
236     tok = tokenizer_factory()
237
238     tok.update_statistics(test_config)
239
240     assert temp_db_cursor.scalar("""SELECT count(*) FROM word
241                                     WHERE type = 'W' and word_id = 1000 and
242                                           (info->>'count')::int > 0""") == 1
243     assert temp_db_cursor.scalar("""SELECT count(*) FROM word
244                                     WHERE type = 'W' and word_id = 1001 and
245                                           (info->>'addr_count')::int > 0""") == 1
246
247
248 def test_normalize_postcode(analyzer):
249     with analyzer() as anl:
250         anl.normalize_postcode('123') == '123'
251         anl.normalize_postcode('ab-34 ') == 'AB-34'
252         anl.normalize_postcode('38 Б') == '38 Б'
253
254
255 class TestPostcodes:
256
257     @pytest.fixture(autouse=True)
258     def setup(self, analyzer, sql_functions):
259         sanitizers = [{'step': 'clean-postcodes'}]
260         with analyzer(sanitizers=sanitizers, with_postcode=True) as anl:
261             self.analyzer = anl
262             yield anl
263
264     def process_postcode(self, cc, postcode):
265         return self.analyzer.process_place(PlaceInfo({'country_code': cc,
266                                                       'address': {'postcode': postcode}}))
267
268     def test_update_postcodes_deleted(self, word_table):
269         word_table.add_postcode(' 1234', '1234')
270         word_table.add_postcode(' 5678', '5678')
271
272         self.analyzer.update_postcodes_from_db()
273
274         assert word_table.count() == 0
275
276     def test_process_place_postcode_simple(self, word_table):
277         info = self.process_postcode('de', '12345')
278
279         assert info['postcode'] == '12345'
280
281     def test_process_place_postcode_with_space(self, word_table):
282         info = self.process_postcode('in', '123 567')
283
284         assert info['postcode'] == '123567'
285
286
287 def test_update_special_phrase_empty_table(analyzer, word_table):
288     with analyzer() as anl:
289         anl.update_special_phrases([
290             ("König  bei", "amenity", "royal", "near"),
291             ("Könige ", "amenity", "royal", "-"),
292             ("street", "highway", "primary", "in")
293         ], True)
294
295     assert word_table.get_special() \
296         == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
297             ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
298             ('STREET', 'street', 'highway', 'primary', 'in')}
299
300
301 def test_update_special_phrase_delete_all(analyzer, word_table):
302     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
303     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
304
305     assert word_table.count_special() == 2
306
307     with analyzer() as anl:
308         anl.update_special_phrases([], True)
309
310     assert word_table.count_special() == 0
311
312
313 def test_update_special_phrases_no_replace(analyzer, word_table):
314     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
315     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
316
317     assert word_table.count_special() == 2
318
319     with analyzer() as anl:
320         anl.update_special_phrases([], False)
321
322     assert word_table.count_special() == 2
323
324
325 def test_update_special_phrase_modify(analyzer, word_table):
326     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
327     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
328
329     assert word_table.count_special() == 2
330
331     with analyzer() as anl:
332         anl.update_special_phrases([
333             ('prison', 'amenity', 'prison', 'in'),
334             ('bar', 'highway', 'road', '-'),
335             ('garden', 'leisure', 'garden', 'near')
336         ], True)
337
338     assert word_table.get_special() \
339         == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
340             ('BAR', 'bar', 'highway', 'road', None),
341             ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
342
343
344 def test_add_country_names_new(analyzer, word_table):
345     with analyzer() as anl:
346         anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
347
348     assert word_table.get_country() == {('es', 'ESPAGÑA'), ('es', 'SPAIN')}
349
350
351 def test_add_country_names_extend(analyzer, word_table):
352     word_table.add_country('ch', 'SCHWEIZ')
353
354     with analyzer() as anl:
355         anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
356
357     assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
358
359
360 class TestPlaceNames:
361
362     @pytest.fixture(autouse=True)
363     def setup(self, analyzer, sql_functions):
364         sanitizers = [{'step': 'split-name-list'},
365                       {'step': 'strip-brace-terms'}]
366         with analyzer(sanitizers=sanitizers) as anl:
367             self.analyzer = anl
368             yield anl
369
370     def expect_name_terms(self, info, *expected_terms):
371         tokens = self.analyzer.get_word_token_info(expected_terms)
372         for token in tokens:
373             assert token[2] is not None, "No token for {0}".format(token)
374
375         assert eval(info['names']) == set((t[2] for t in tokens))
376
377     def process_named_place(self, names):
378         return self.analyzer.process_place(PlaceInfo({'name': names}))
379
380     def test_simple_names(self):
381         info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
382
383         self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
384
385     @pytest.mark.parametrize('sep', [',', ';'])
386     def test_names_with_separator(self, sep):
387         info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
388
389         self.expect_name_terms(info, '#New York', '#Big Apple',
390                                      'new', 'york', 'big', 'apple')
391
392     def test_full_names_with_bracket(self):
393         info = self.process_named_place({'name': 'Houseboat (left)'})
394
395         self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
396                                      'houseboat', 'left')
397
398     def test_country_name(self, word_table):
399         place = PlaceInfo({'name': {'name': 'Norge'},
400                            'country_code': 'no',
401                            'rank_address': 4,
402                            'class': 'boundary',
403                            'type': 'administrative'})
404
405         info = self.analyzer.process_place(place)
406
407         self.expect_name_terms(info, '#norge', 'norge')
408         assert word_table.get_country() == {('no', 'NORGE')}
409
410
411 class TestPlaceAddress:
412
413     @pytest.fixture(autouse=True)
414     def setup(self, analyzer, sql_functions):
415         hnr = {'step': 'clean-housenumbers',
416                'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
417         with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
418             self.analyzer = anl
419             yield anl
420
421     @pytest.fixture
422     def getorcreate_hnr_id(self, temp_db_cursor):
423         temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
424                                   RETURNS INTEGER AS $$
425                                     SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
426
427     def process_address(self, **kwargs):
428         return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
429
430     def name_token_set(self, *expected_terms):
431         tokens = self.analyzer.get_word_token_info(expected_terms)
432         for token in tokens:
433             assert token[2] is not None, "No token for {0}".format(token)
434
435         return set((t[2] for t in tokens))
436
437     @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
438     def test_process_place_postcode(self, word_table, pcode):
439         info = self.process_address(postcode=pcode)
440
441         assert info['postcode'] == pcode
442
443     @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
444     def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
445         info = self.process_address(housenumber=hnr)
446
447         assert info['hnr'] == hnr.upper()
448         assert info['hnr_tokens'] == "{-1}"
449
450     def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
451         info = self.process_address(housenumber='134',
452                                     conscriptionnumber='134',
453                                     streetnumber='99a')
454
455         assert set(info['hnr'].split(';')) == set(('134', '99A'))
456         assert info['hnr_tokens'] == "{-1,-2}"
457
458     def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
459         info = self.process_address(housenumber="45")
460         assert info['hnr_tokens'] == "{-1}"
461
462         info = self.process_address(housenumber="46")
463         assert info['hnr_tokens'] == "{-2}"
464
465         info = self.process_address(housenumber="41;45")
466         assert eval(info['hnr_tokens']) == {-1, -3}
467
468         info = self.process_address(housenumber="41")
469         assert eval(info['hnr_tokens']) == {-3}
470
471     def test_process_place_street(self):
472         self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
473         info = self.process_address(street='Grand Road')
474
475         assert eval(info['street']) == self.name_token_set('#Grand Road')
476
477     def test_process_place_nonexisting_street(self):
478         info = self.process_address(street='Grand Road')
479
480         assert info['street'] == '{}'
481
482     def test_process_place_multiple_street_tags(self):
483         self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road',
484                                                         'ref': '05989'}}))
485         info = self.process_address(**{'street': 'Grand Road',
486                                        'street:sym_ul': '05989'})
487
488         assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
489
490     def test_process_place_street_empty(self):
491         info = self.process_address(street='🜵')
492
493         assert info['street'] == '{}'
494
495     def test_process_place_street_from_cache(self):
496         self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
497         self.process_address(street='Grand Road')
498
499         # request address again
500         info = self.process_address(street='Grand Road')
501
502         assert eval(info['street']) == self.name_token_set('#Grand Road')
503
504     def test_process_place_place(self):
505         info = self.process_address(place='Honu Lulu')
506
507         assert eval(info['place']) == self.name_token_set('HONU', 'LULU', '#HONU LULU')
508
509     def test_process_place_place_extra(self):
510         info = self.process_address(**{'place:en': 'Honu Lulu'})
511
512         assert 'place' not in info
513
514     def test_process_place_place_empty(self):
515         info = self.process_address(place='🜵')
516
517         assert 'place' not in info
518
519     def test_process_place_address_terms(self):
520         info = self.process_address(country='de', city='Zwickau', state='Sachsen',
521                                     suburb='Zwickau', street='Hauptstr',
522                                     full='right behind the church')
523
524         city = self.name_token_set('ZWICKAU', '#ZWICKAU')
525         state = self.name_token_set('SACHSEN', '#SACHSEN')
526
527         result = {k: eval(v) for k, v in info['addr'].items()}
528
529         assert result == {'city': city, 'suburb': city, 'state': state}
530
531     def test_process_place_multiple_address_terms(self):
532         info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
533
534         result = {k: eval(v) for k, v in info['addr'].items()}
535
536         assert result == {'city': self.name_token_set('Bruxelles', '#Bruxelles')}
537
538     def test_process_place_address_terms_empty(self):
539         info = self.process_address(country='de', city=' ', street='Hauptstr',
540                                     full='right behind the church')
541
542         assert 'addr' not in info
543
544
545 class TestPlaceHousenumberWithAnalyser:
546
547     @pytest.fixture(autouse=True)
548     def setup(self, analyzer, sql_functions):
549         hnr = {'step': 'clean-housenumbers',
550                'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
551         with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr],
552                       with_housenumber=True) as anl:
553             self.analyzer = anl
554             yield anl
555
556     @pytest.fixture
557     def getorcreate_hnr_id(self, temp_db_cursor):
558         temp_db_cursor.execute("""
559             CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
560             RETURNS INTEGER AS $$
561                 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
562
563     def process_address(self, **kwargs):
564         return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
565
566     def name_token_set(self, *expected_terms):
567         tokens = self.analyzer.get_word_token_info(expected_terms)
568         for token in tokens:
569             assert token[2] is not None, "No token for {0}".format(token)
570
571         return set((t[2] for t in tokens))
572
573     @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
574     def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
575         info = self.process_address(housenumber=hnr)
576
577         assert info['hnr'] == hnr.upper()
578         assert info['hnr_tokens'] == "{-1}"
579
580     def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
581         info = self.process_address(housenumber='134',
582                                     conscriptionnumber='134',
583                                     streetnumber='99a')
584
585         assert set(info['hnr'].split(';')) == set(('134', '99 A'))
586         assert info['hnr_tokens'] == "{-1,-2}"
587
588     def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
589         info = self.process_address(housenumber="45")
590         assert info['hnr_tokens'] == "{-1}"
591
592         info = self.process_address(housenumber="46")
593         assert info['hnr_tokens'] == "{-2}"
594
595         info = self.process_address(housenumber="41;45")
596         assert eval(info['hnr_tokens']) == {-1, -3}
597
598         info = self.process_address(housenumber="41")
599         assert eval(info['hnr_tokens']) == {-3}
600
601
602 class TestUpdateWordTokens:
603
604     @pytest.fixture(autouse=True)
605     def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
606         table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
607         self.tok = tokenizer_factory()
608
609     @pytest.fixture
610     def search_entry(self, temp_db_cursor):
611         place_id = itertools.count(1000)
612
613         def _insert(*args):
614             temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
615                                    (next(place_id), list(args)))
616
617         return _insert
618
619     @pytest.fixture(params=['simple', 'analyzed'])
620     def add_housenumber(self, request, word_table):
621         if request.param == 'simple':
622             def _make(hid, hnr):
623                 word_table.add_housenumber(hid, hnr)
624         elif request.param == 'analyzed':
625             def _make(hid, hnr):
626                 word_table.add_housenumber(hid, [hnr])
627
628         return _make
629
630     @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
631     def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
632         word_table.add_housenumber(1000, hnr)
633
634         assert word_table.count_housenumbers() == 1
635         self.tok.update_word_tokens()
636         assert word_table.count_housenumbers() == 0
637
638     def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
639         add_housenumber(1000, '5432')
640
641         assert word_table.count_housenumbers() == 1
642         self.tok.update_word_tokens()
643         assert word_table.count_housenumbers() == 1
644
645     def test_keep_housenumbers_from_search_name_table(self, add_housenumber,
646                                                       word_table, search_entry):
647         add_housenumber(9999, '5432a')
648         add_housenumber(9991, '9 a')
649         search_entry(123, 9999, 34)
650
651         assert word_table.count_housenumbers() == 2
652         self.tok.update_word_tokens()
653         assert word_table.count_housenumbers() == 1
654
655     def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table,
656                                                  placex_table):
657         add_housenumber(9999, '5432a')
658         add_housenumber(9990, '34z')
659         placex_table.add(housenumber='34z')
660         placex_table.add(housenumber='25432a')
661
662         assert word_table.count_housenumbers() == 2
663         self.tok.update_word_tokens()
664         assert word_table.count_housenumbers() == 1
665
666     def test_keep_housenumbers_from_placex_table_hnr_list(self, add_housenumber,
667                                                           word_table, placex_table):
668         add_housenumber(9991, '9 b')
669         add_housenumber(9990, '34z')
670         placex_table.add(housenumber='9 a;9 b;9 c')
671
672         assert word_table.count_housenumbers() == 2
673         self.tok.update_word_tokens()
674         assert word_table.count_housenumbers() == 1