]> git.openstreetmap.org Git - nominatim.git/blob - test/python/tokenizer/test_icu.py
release 5.2.0.post3
[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, property_table, sql_preprocessor, place_table, word_table):
43     def _maker():
44         return icu_tokenizer.create(dsn)
45
46     return _maker
47
48
49 @pytest.fixture
50 def db_prop(temp_db_conn):
51     def _get_db_property(name):
52         return properties.get_property(temp_db_conn, name)
53
54     return _get_db_property
55
56
57 @pytest.fixture
58 def analyzer(tokenizer_factory, test_config, monkeypatch,
59              temp_db_with_extensions, tmp_path):
60     sql = tmp_path / 'sql' / 'tokenizer' / 'icu_tokenizer.sql'
61     sql.write_text("SELECT 'a';")
62
63     monkeypatch.setenv('NOMINATIM_TERM_NORMALIZATION', ':: lower();')
64     tok = tokenizer_factory()
65     tok.init_new_db(test_config)
66     monkeypatch.undo()
67
68     def _mk_analyser(norm=("[[:Punctuation:][:Space:]]+ > ' '",), trans=(':: upper()',),
69                      variants=('~gasse -> gasse', 'street => st', ),
70                      sanitizers=[], with_housenumber=False,
71                      with_postcode=False):
72         cfgstr = {'normalization': list(norm),
73                   'sanitizers': sanitizers,
74                   'transliteration': list(trans),
75                   'token-analysis': [{'analyzer': 'generic',
76                                       'variants': [{'words': list(variants)}]}]}
77         if with_housenumber:
78             cfgstr['token-analysis'].append({'id': '@housenumber',
79                                              'analyzer': 'housenumbers'})
80         if with_postcode:
81             cfgstr['token-analysis'].append({'id': '@postcode',
82                                              'analyzer': 'postcodes'})
83         (test_config.project_dir / 'icu_tokenizer.yaml').write_text(yaml.dump(cfgstr))
84         tok.loader = nominatim_db.tokenizer.icu_rule_loader.ICURuleLoader(test_config)
85
86         return tok.name_analyzer()
87
88     return _mk_analyser
89
90
91 @pytest.fixture
92 def sql_functions(temp_db_conn, def_config, src_dir):
93     orig_sql = def_config.lib_dir.sql
94     def_config.lib_dir.sql = src_dir / 'lib-sql'
95     sqlproc = SQLPreprocessor(temp_db_conn, def_config)
96     sqlproc.run_sql_file(temp_db_conn, 'functions/utils.sql')
97     sqlproc.run_sql_file(temp_db_conn, 'tokenizer/icu_tokenizer.sql')
98     def_config.lib_dir.sql = orig_sql
99
100
101 @pytest.fixture
102 def getorcreate_full_word(temp_db_cursor):
103     temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_full_word(
104                                                  norm_term TEXT, lookup_terms TEXT[],
105                                                  OUT full_token INT,
106                                                  OUT partial_tokens INT[])
107   AS $$
108 DECLARE
109   partial_terms TEXT[] = '{}'::TEXT[];
110   term TEXT;
111   term_id INTEGER;
112   term_count INTEGER;
113 BEGIN
114   SELECT min(word_id) INTO full_token
115     FROM word WHERE info->>'word' = norm_term and type = 'W';
116
117   IF full_token IS NULL THEN
118     full_token := nextval('seq_word');
119     INSERT INTO word (word_id, word_token, type, info)
120       SELECT full_token, lookup_term, 'W',
121              json_build_object('word', norm_term, 'count', 0)
122         FROM unnest(lookup_terms) as lookup_term;
123   END IF;
124
125   FOR term IN SELECT unnest(string_to_array(unnest(lookup_terms), ' ')) LOOP
126     term := trim(term);
127     IF NOT (ARRAY[term] <@ partial_terms) THEN
128       partial_terms := partial_terms || term;
129     END IF;
130   END LOOP;
131
132   partial_tokens := '{}'::INT[];
133   FOR term IN SELECT unnest(partial_terms) LOOP
134     SELECT min(word_id), max(info->>'count') INTO term_id, term_count
135       FROM word WHERE word_token = term and type = 'w';
136
137     IF term_id IS NULL THEN
138       term_id := nextval('seq_word');
139       term_count := 0;
140       INSERT INTO word (word_id, word_token, type, info)
141         VALUES (term_id, term, 'w', json_build_object('count', term_count));
142     END IF;
143
144     IF NOT (ARRAY[term_id] <@ partial_tokens) THEN
145       partial_tokens := partial_tokens || term_id;
146     END IF;
147   END LOOP;
148 END;
149 $$
150 LANGUAGE plpgsql;
151                               """)
152
153
154 def test_init_new(tokenizer_factory, test_config, db_prop):
155     tok = tokenizer_factory()
156     tok.init_new_db(test_config)
157
158     prop = db_prop(nominatim_db.tokenizer.icu_rule_loader.DBCFG_IMPORT_NORM_RULES)
159
160     assert prop.startswith(':: lower ();')
161
162
163 def test_init_word_table(tokenizer_factory, test_config, place_row, temp_db_cursor):
164     place_row(names={'name': 'Test Area', 'ref': '52'})
165     place_row(names={'name': 'No Area'})
166     place_row(names={'name': 'Holzstrasse'})
167
168     tok = tokenizer_factory()
169     tok.init_new_db(test_config)
170
171     assert temp_db_cursor.table_exists('word')
172
173
174 def test_init_from_project(test_config, tokenizer_factory):
175     tok = tokenizer_factory()
176     tok.init_new_db(test_config)
177
178     tok = tokenizer_factory()
179     tok.init_from_project(test_config)
180
181     assert tok.loader is not None
182
183
184 def test_update_sql_functions(db_prop, temp_db_cursor,
185                               tokenizer_factory, test_config, table_factory,
186                               monkeypatch):
187     tok = tokenizer_factory()
188     tok.init_new_db(test_config)
189
190     table_factory('test', 'txt TEXT')
191
192     func_file = test_config.lib_dir.sql / 'tokenizer' / 'icu_tokenizer.sql'
193     func_file.write_text("""INSERT INTO test VALUES (1133)""")
194
195     tok.update_sql_functions(test_config)
196
197     test_content = temp_db_cursor.row_set('SELECT * FROM test')
198     assert test_content == set((('1133', ), ))
199
200
201 def test_finalize_import(tokenizer_factory, temp_db_cursor,
202                          test_config, sql_preprocessor_cfg):
203     tok = tokenizer_factory()
204     tok.init_new_db(test_config)
205
206     assert not temp_db_cursor.index_exists('word', 'idx_word_word_id')
207
208     tok.finalize_import(test_config)
209
210     assert temp_db_cursor.index_exists('word', 'idx_word_word_id')
211
212
213 def test_check_database(test_config, tokenizer_factory,
214                         temp_db_cursor, sql_preprocessor_cfg):
215     tok = tokenizer_factory()
216     tok.init_new_db(test_config)
217
218     assert tok.check_database(test_config) is None
219
220
221 def test_update_statistics_reverse_only(word_table, tokenizer_factory, test_config):
222     tok = tokenizer_factory()
223     tok.update_statistics(test_config)
224
225
226 def test_update_statistics(word_table, table_factory, temp_db_cursor,
227                            tokenizer_factory, test_config):
228     word_table.add_full_word(1000, 'hello')
229     word_table.add_full_word(1001, 'bye')
230     word_table.add_full_word(1002, 'town')
231     table_factory('search_name',
232                   'place_id BIGINT, name_vector INT[], nameaddress_vector INT[]',
233                   [(12, [1000], [1001]), (13, [1001], [1002]), (14, [1000, 1001], [1002])])
234     tok = tokenizer_factory()
235
236     tok.update_statistics(test_config)
237
238     assert temp_db_cursor.row_set("""SELECT word_id,
239                                             (info->>'count')::int,
240                                             (info->>'addr_count')::int
241                                      FROM word
242                                      WHERE type = 'W'""") == \
243         {(1000, 2, None), (1001, 2, None), (1002, None, 2)}
244
245
246 def test_normalize_postcode(analyzer):
247     with analyzer() as anl:
248         anl.normalize_postcode('123') == '123'
249         anl.normalize_postcode('ab-34 ') == 'AB-34'
250         anl.normalize_postcode('38 Б') == '38 Б'
251
252
253 class TestPostcodes:
254
255     @pytest.fixture(autouse=True)
256     def setup(self, analyzer, sql_functions):
257         sanitizers = [{'step': 'clean-postcodes'}]
258         with analyzer(sanitizers=sanitizers, with_postcode=True) as anl:
259             self.analyzer = anl
260             yield anl
261
262     def process_postcode(self, cc, postcode):
263         return self.analyzer.process_place(PlaceInfo({'country_code': cc,
264                                                       'address': {'postcode': postcode}}))
265
266     def test_update_postcodes_deleted(self, word_table):
267         word_table.add_postcode(' 1234', '1234')
268         word_table.add_postcode(' 5678', '5678')
269
270         self.analyzer.update_postcodes_from_db()
271
272         assert word_table.count() == 0
273
274     def test_process_place_postcode_simple(self, word_table):
275         info = self.process_postcode('de', '12345')
276
277         assert info['postcode'] == '12345'
278
279     def test_process_place_postcode_with_space(self, word_table):
280         info = self.process_postcode('in', '123 567')
281
282         assert info['postcode'] == '123567'
283
284
285 def test_update_special_phrase_empty_table(analyzer, word_table):
286     with analyzer() as anl:
287         anl.update_special_phrases([
288             ("König  bei", "amenity", "royal", "near"),
289             ("Könige ", "amenity", "royal", "-"),
290             ("street", "highway", "primary", "in")
291         ], True)
292
293     assert word_table.get_special() \
294         == {('KÖNIG BEI', 'König bei', 'amenity', 'royal', 'near'),
295             ('KÖNIGE', 'Könige', 'amenity', 'royal', None),
296             ('STREET', 'street', 'highway', 'primary', 'in')}
297
298
299 def test_update_special_phrase_delete_all(analyzer, word_table):
300     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
301     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
302
303     assert word_table.count_special() == 2
304
305     with analyzer() as anl:
306         anl.update_special_phrases([], True)
307
308     assert word_table.count_special() == 0
309
310
311 def test_update_special_phrases_no_replace(analyzer, word_table):
312     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
313     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
314
315     assert word_table.count_special() == 2
316
317     with analyzer() as anl:
318         anl.update_special_phrases([], False)
319
320     assert word_table.count_special() == 2
321
322
323 def test_update_special_phrase_modify(analyzer, word_table):
324     word_table.add_special('FOO', 'foo', 'amenity', 'prison', 'in')
325     word_table.add_special('BAR', 'bar', 'highway', 'road', None)
326
327     assert word_table.count_special() == 2
328
329     with analyzer() as anl:
330         anl.update_special_phrases([
331             ('prison', 'amenity', 'prison', 'in'),
332             ('bar', 'highway', 'road', '-'),
333             ('garden', 'leisure', 'garden', 'near')
334         ], True)
335
336     assert word_table.get_special() \
337         == {('PRISON', 'prison', 'amenity', 'prison', 'in'),
338             ('BAR', 'bar', 'highway', 'road', None),
339             ('GARDEN', 'garden', 'leisure', 'garden', 'near')}
340
341
342 def test_add_country_names_new(analyzer, word_table):
343     with analyzer() as anl:
344         anl.add_country_names('es', {'name': 'Espagña', 'name:en': 'Spain'})
345
346     assert word_table.get_country() == {('es', 'ESPAGÑA', 'Espagña'),
347                                         ('es', 'SPAIN', 'Spain')}
348
349
350 def test_add_country_names_extend(analyzer, word_table):
351     word_table.add_country('ch', 'SCHWEIZ', 'Schweiz')
352
353     with analyzer() as anl:
354         anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
355
356     assert word_table.get_country() == {('ch', 'SCHWEIZ', 'Schweiz'),
357                                         ('ch', 'SUISSE', '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', '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