]> git.openstreetmap.org Git - nominatim.git/blob - test/python/tokenizer/test_icu.py
remove automatic setup of tokenizer directory
[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'), ('es', 'SPAIN')}
347
348
349 def test_add_country_names_extend(analyzer, word_table):
350     word_table.add_country('ch', 'SCHWEIZ')
351
352     with analyzer() as anl:
353         anl.add_country_names('ch', {'name': 'Schweiz', 'name:fr': 'Suisse'})
354
355     assert word_table.get_country() == {('ch', 'SCHWEIZ'), ('ch', 'SUISSE')}
356
357
358 class TestPlaceNames:
359
360     @pytest.fixture(autouse=True)
361     def setup(self, analyzer, sql_functions):
362         sanitizers = [{'step': 'split-name-list'},
363                       {'step': 'strip-brace-terms'}]
364         with analyzer(sanitizers=sanitizers) as anl:
365             self.analyzer = anl
366             yield anl
367
368     def expect_name_terms(self, info, *expected_terms):
369         tokens = self.analyzer.get_word_token_info(expected_terms)
370         for token in tokens:
371             assert token[2] is not None, "No token for {0}".format(token)
372
373         assert eval(info['names']) == set((t[2] for t in tokens))
374
375     def process_named_place(self, names):
376         return self.analyzer.process_place(PlaceInfo({'name': names}))
377
378     def test_simple_names(self):
379         info = self.process_named_place({'name': 'Soft bAr', 'ref': '34'})
380
381         self.expect_name_terms(info, '#Soft bAr', '#34', 'Soft', 'bAr', '34')
382
383     @pytest.mark.parametrize('sep', [',', ';'])
384     def test_names_with_separator(self, sep):
385         info = self.process_named_place({'name': sep.join(('New York', 'Big Apple'))})
386
387         self.expect_name_terms(info, '#New York', '#Big Apple',
388                                      'new', 'york', 'big', 'apple')
389
390     def test_full_names_with_bracket(self):
391         info = self.process_named_place({'name': 'Houseboat (left)'})
392
393         self.expect_name_terms(info, '#Houseboat (left)', '#Houseboat',
394                                      'houseboat', 'left')
395
396     def test_country_name(self, word_table):
397         place = PlaceInfo({'name': {'name': 'Norge'},
398                            'country_code': 'no',
399                            'rank_address': 4,
400                            'class': 'boundary',
401                            'type': 'administrative'})
402
403         info = self.analyzer.process_place(place)
404
405         self.expect_name_terms(info, '#norge', 'norge')
406         assert word_table.get_country() == {('no', 'NORGE')}
407
408
409 class TestPlaceAddress:
410
411     @pytest.fixture(autouse=True)
412     def setup(self, analyzer, sql_functions):
413         hnr = {'step': 'clean-housenumbers',
414                'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
415         with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr]) as anl:
416             self.analyzer = anl
417             yield anl
418
419     @pytest.fixture
420     def getorcreate_hnr_id(self, temp_db_cursor):
421         temp_db_cursor.execute("""CREATE OR REPLACE FUNCTION getorcreate_hnr_id(lookup_term TEXT)
422                                   RETURNS INTEGER AS $$
423                                     SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
424
425     def process_address(self, **kwargs):
426         return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
427
428     def name_token_set(self, *expected_terms):
429         tokens = self.analyzer.get_word_token_info(expected_terms)
430         for token in tokens:
431             assert token[2] is not None, "No token for {0}".format(token)
432
433         return set((t[2] for t in tokens))
434
435     @pytest.mark.parametrize('pcode', ['12345', 'AB 123', '34-345'])
436     def test_process_place_postcode(self, word_table, pcode):
437         info = self.process_address(postcode=pcode)
438
439         assert info['postcode'] == pcode
440
441     @pytest.mark.parametrize('hnr', ['123a', '1', '101'])
442     def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
443         info = self.process_address(housenumber=hnr)
444
445         assert info['hnr'] == hnr.upper()
446         assert info['hnr_tokens'] == "{-1}"
447
448     def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
449         info = self.process_address(housenumber='134',
450                                     conscriptionnumber='134',
451                                     streetnumber='99a')
452
453         assert set(info['hnr'].split(';')) == set(('134', '99A'))
454         assert info['hnr_tokens'] == "{-1,-2}"
455
456     def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
457         info = self.process_address(housenumber="45")
458         assert info['hnr_tokens'] == "{-1}"
459
460         info = self.process_address(housenumber="46")
461         assert info['hnr_tokens'] == "{-2}"
462
463         info = self.process_address(housenumber="41;45")
464         assert eval(info['hnr_tokens']) == {-1, -3}
465
466         info = self.process_address(housenumber="41")
467         assert eval(info['hnr_tokens']) == {-3}
468
469     def test_process_place_street(self):
470         self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
471         info = self.process_address(street='Grand Road')
472
473         assert eval(info['street']) == self.name_token_set('#Grand Road')
474
475     def test_process_place_nonexisting_street(self):
476         info = self.process_address(street='Grand Road')
477
478         assert info['street'] == '{}'
479
480     def test_process_place_multiple_street_tags(self):
481         self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road',
482                                                         'ref': '05989'}}))
483         info = self.process_address(**{'street': 'Grand Road',
484                                        'street:sym_ul': '05989'})
485
486         assert eval(info['street']) == self.name_token_set('#Grand Road', '#05989')
487
488     def test_process_place_street_empty(self):
489         info = self.process_address(street='🜵')
490
491         assert info['street'] == '{}'
492
493     def test_process_place_street_from_cache(self):
494         self.analyzer.process_place(PlaceInfo({'name': {'name': 'Grand Road'}}))
495         self.process_address(street='Grand Road')
496
497         # request address again
498         info = self.process_address(street='Grand Road')
499
500         assert eval(info['street']) == self.name_token_set('#Grand Road')
501
502     def test_process_place_place(self):
503         info = self.process_address(place='Honu Lulu')
504
505         assert eval(info['place']) == self.name_token_set('HONU', 'LULU', '#HONU LULU')
506
507     def test_process_place_place_extra(self):
508         info = self.process_address(**{'place:en': 'Honu Lulu'})
509
510         assert 'place' not in info
511
512     def test_process_place_place_empty(self):
513         info = self.process_address(place='🜵')
514
515         assert 'place' not in info
516
517     def test_process_place_address_terms(self):
518         info = self.process_address(country='de', city='Zwickau', state='Sachsen',
519                                     suburb='Zwickau', street='Hauptstr',
520                                     full='right behind the church')
521
522         city = self.name_token_set('ZWICKAU', '#ZWICKAU')
523         state = self.name_token_set('SACHSEN', '#SACHSEN')
524
525         result = {k: eval(v) for k, v in info['addr'].items()}
526
527         assert result == {'city': city, 'suburb': city, 'state': state}
528
529     def test_process_place_multiple_address_terms(self):
530         info = self.process_address(**{'city': 'Bruxelles', 'city:de': 'Brüssel'})
531
532         result = {k: eval(v) for k, v in info['addr'].items()}
533
534         assert result == {'city': self.name_token_set('Bruxelles', '#Bruxelles')}
535
536     def test_process_place_address_terms_empty(self):
537         info = self.process_address(country='de', city=' ', street='Hauptstr',
538                                     full='right behind the church')
539
540         assert 'addr' not in info
541
542
543 class TestPlaceHousenumberWithAnalyser:
544
545     @pytest.fixture(autouse=True)
546     def setup(self, analyzer, sql_functions):
547         hnr = {'step': 'clean-housenumbers',
548                'filter-kind': ['housenumber', 'conscriptionnumber', 'streetnumber']}
549         with analyzer(trans=(":: upper()", "'🜵' > ' '"), sanitizers=[hnr],
550                       with_housenumber=True) as anl:
551             self.analyzer = anl
552             yield anl
553
554     @pytest.fixture
555     def getorcreate_hnr_id(self, temp_db_cursor):
556         temp_db_cursor.execute("""
557             CREATE OR REPLACE FUNCTION create_analyzed_hnr_id(norm_term TEXT, lookup_terms TEXT[])
558             RETURNS INTEGER AS $$
559                 SELECT -nextval('seq_word')::INTEGER; $$ LANGUAGE SQL""")
560
561     def process_address(self, **kwargs):
562         return self.analyzer.process_place(PlaceInfo({'address': kwargs}))
563
564     def name_token_set(self, *expected_terms):
565         tokens = self.analyzer.get_word_token_info(expected_terms)
566         for token in tokens:
567             assert token[2] is not None, "No token for {0}".format(token)
568
569         return set((t[2] for t in tokens))
570
571     @pytest.mark.parametrize('hnr', ['123 a', '1', '101'])
572     def test_process_place_housenumbers_simple(self, hnr, getorcreate_hnr_id):
573         info = self.process_address(housenumber=hnr)
574
575         assert info['hnr'] == hnr.upper()
576         assert info['hnr_tokens'] == "{-1}"
577
578     def test_process_place_housenumbers_duplicates(self, getorcreate_hnr_id):
579         info = self.process_address(housenumber='134',
580                                     conscriptionnumber='134',
581                                     streetnumber='99a')
582
583         assert set(info['hnr'].split(';')) == set(('134', '99 A'))
584         assert info['hnr_tokens'] == "{-1,-2}"
585
586     def test_process_place_housenumbers_cached(self, getorcreate_hnr_id):
587         info = self.process_address(housenumber="45")
588         assert info['hnr_tokens'] == "{-1}"
589
590         info = self.process_address(housenumber="46")
591         assert info['hnr_tokens'] == "{-2}"
592
593         info = self.process_address(housenumber="41;45")
594         assert eval(info['hnr_tokens']) == {-1, -3}
595
596         info = self.process_address(housenumber="41")
597         assert eval(info['hnr_tokens']) == {-3}
598
599
600 class TestUpdateWordTokens:
601
602     @pytest.fixture(autouse=True)
603     def setup(self, tokenizer_factory, table_factory, placex_table, word_table):
604         table_factory('search_name', 'place_id BIGINT, name_vector INT[]')
605         self.tok = tokenizer_factory()
606
607     @pytest.fixture
608     def search_entry(self, temp_db_cursor):
609         place_id = itertools.count(1000)
610
611         def _insert(*args):
612             temp_db_cursor.execute("INSERT INTO search_name VALUES (%s, %s)",
613                                    (next(place_id), list(args)))
614
615         return _insert
616
617     @pytest.fixture(params=['simple', 'analyzed'])
618     def add_housenumber(self, request, word_table):
619         if request.param == 'simple':
620             def _make(hid, hnr):
621                 word_table.add_housenumber(hid, hnr)
622         elif request.param == 'analyzed':
623             def _make(hid, hnr):
624                 word_table.add_housenumber(hid, [hnr])
625
626         return _make
627
628     @pytest.mark.parametrize('hnr', ('1a', '1234567', '34 5'))
629     def test_remove_unused_housenumbers(self, add_housenumber, word_table, hnr):
630         word_table.add_housenumber(1000, hnr)
631
632         assert word_table.count_housenumbers() == 1
633         self.tok.update_word_tokens()
634         assert word_table.count_housenumbers() == 0
635
636     def test_keep_unused_numeral_housenumbers(self, add_housenumber, word_table):
637         add_housenumber(1000, '5432')
638
639         assert word_table.count_housenumbers() == 1
640         self.tok.update_word_tokens()
641         assert word_table.count_housenumbers() == 1
642
643     def test_keep_housenumbers_from_search_name_table(self, add_housenumber,
644                                                       word_table, search_entry):
645         add_housenumber(9999, '5432a')
646         add_housenumber(9991, '9 a')
647         search_entry(123, 9999, 34)
648
649         assert word_table.count_housenumbers() == 2
650         self.tok.update_word_tokens()
651         assert word_table.count_housenumbers() == 1
652
653     def test_keep_housenumbers_from_placex_table(self, add_housenumber, word_table,
654                                                  placex_table):
655         add_housenumber(9999, '5432a')
656         add_housenumber(9990, '34z')
657         placex_table.add(housenumber='34z')
658         placex_table.add(housenumber='25432a')
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_hnr_list(self, add_housenumber,
665                                                           word_table, placex_table):
666         add_housenumber(9991, '9 b')
667         add_housenumber(9990, '34z')
668         placex_table.add(housenumber='9 a;9 b;9 c')
669
670         assert word_table.count_housenumbers() == 2
671         self.tok.update_word_tokens()
672         assert word_table.count_housenumbers() == 1