]> git.openstreetmap.org Git - nominatim.git/blob - test/python/test_tokenizer_icu_rule_loader.py
adapt tests for ICU tokenizer
[nominatim.git] / test / python / test_tokenizer_icu_rule_loader.py
1 """
2 Tests for converting a config file to ICU rules.
3 """
4 import pytest
5 from textwrap import dedent
6
7 from nominatim.tokenizer.icu_rule_loader import ICURuleLoader
8 from nominatim.errors import UsageError
9
10 from icu import Transliterator
11
12 @pytest.fixture
13 def cfgfile(tmp_path, suffix='.yaml'):
14     def _create_config(suffixes, abbr):
15         content = dedent("""\
16         normalization:
17             - ":: NFD ()"
18             - "[[:Nonspacing Mark:] [:Cf:]] >"
19             - ":: lower ()"
20             - "[[:Punctuation:][:Space:]]+ > ' '"
21             - ":: NFC ()"
22         transliteration:
23             - "::  Latin ()"
24         """)
25         content += "compound_suffixes:\n"
26         content += '\n'.join(("    - " + s for s in suffixes)) + '\n'
27         content += "abbreviations:\n"
28         content += '\n'.join(("    - " + s for s in abbr)) + '\n'
29         fpath = tmp_path / ('test_config' + suffix)
30         fpath.write_text(dedent(content))
31         return fpath
32
33     return _create_config
34
35 def test_missing_normalization(tmp_path):
36     fpath = tmp_path / ('test_config.yaml')
37     fpath.write_text(dedent("""\
38         normalizatio:
39             - ":: NFD ()"
40         """))
41
42     with pytest.raises(UsageError):
43         ICURuleLoader(fpath)
44
45
46 def test_get_search_rules(cfgfile):
47     fpath = cfgfile(['strasse', 'straße', 'weg'],
48                     ['strasse,straße => str',
49                      'prospekt => pr'])
50
51     loader = ICURuleLoader(fpath)
52
53     rules = loader.get_search_rules()
54     trans = Transliterator.createFromRules("test", rules)
55
56     assert trans.transliterate(" Baumstraße ") == " baum straße "
57     assert trans.transliterate(" Baumstrasse ") == " baum strasse "
58     assert trans.transliterate(" Baumstr ") == " baum str "
59     assert trans.transliterate(" Baumwegstr ") == " baumweg str "
60     assert trans.transliterate(" Αθήνα ") == " athēna "
61     assert trans.transliterate(" проспект ") == " prospekt "
62
63
64 def test_get_synonym_pairs(cfgfile):
65     fpath = cfgfile(['Weg', 'Strasse'],
66                     ['Strasse => str,st'])
67
68     loader = ICURuleLoader(fpath)
69
70     repl = loader.get_replacement_pairs()
71
72     assert sorted(((a, sorted(b)) for a, b in repl)) == \
73              sorted([(' strasse ', [' st ', ' str ', ' strasse ']),
74                      ('strasse ', [' st ', ' str ', ' strasse ']),
75                      ('st ' , [' st ']),
76                      ('str ' , [' str ']),
77                      ('weg ', [' weg '])])
78