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