]> git.openstreetmap.org Git - nominatim.git/blob - test/python/api/conftest.py
Merge pull request #3926 from lonvia/rework-postcode-handling
[nominatim.git] / test / python / api / conftest.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 Helper fixtures for API call tests.
9 """
10 import pytest
11 import pytest_asyncio
12 import datetime as dt
13
14 import sqlalchemy as sa
15
16 import nominatim_api as napi
17 from nominatim_db.db.sql_preprocessor import SQLPreprocessor
18 from nominatim_api.search.query_analyzer_factory import make_query_analyzer
19 from nominatim_db.tools import convert_sqlite
20 import nominatim_api.logging as loglib
21
22
23 class APITester:
24
25     def __init__(self):
26         self.api = napi.NominatimAPI()
27         self.async_to_sync(self.api._async_api.setup_database())
28
29     def async_to_sync(self, func):
30         """ Run an asynchronous function until completion using the
31             internal loop of the API.
32         """
33         return self.api._loop.run_until_complete(func)
34
35     def add_data(self, table, data):
36         """ Insert data into the given table.
37         """
38         sql = getattr(self.api._async_api._tables, table).insert()
39         self.async_to_sync(self.exec_async(sql, data))
40
41     def add_placex(self, **kw):
42         name = kw.get('name')
43         if isinstance(name, str):
44             name = {'name': name}
45
46         centroid = kw.get('centroid', (23.0, 34.0))
47         geometry = kw.get('geometry', 'POINT(%f %f)' % centroid)
48
49         self.add_data('placex',
50                       {'place_id': kw.get('place_id', 1000),
51                        'osm_type': kw.get('osm_type', 'W'),
52                        'osm_id': kw.get('osm_id', 4),
53                        'class_': kw.get('class_', 'highway'),
54                        'type': kw.get('type', 'residential'),
55                        'name': name,
56                        'address': kw.get('address'),
57                        'extratags': kw.get('extratags'),
58                        'parent_place_id': kw.get('parent_place_id'),
59                        'linked_place_id': kw.get('linked_place_id'),
60                        'admin_level': kw.get('admin_level', 15),
61                        'country_code': kw.get('country_code'),
62                        'housenumber': kw.get('housenumber'),
63                        'postcode': kw.get('postcode'),
64                        'wikipedia': kw.get('wikipedia'),
65                        'rank_search': kw.get('rank_search', 30),
66                        'rank_address': kw.get('rank_address', 30),
67                        'importance': kw.get('importance'),
68                        'centroid': 'POINT(%f %f)' % centroid,
69                        'indexed_status': kw.get('indexed_status', 0),
70                        'indexed_date': kw.get('indexed_date',
71                                               dt.datetime(2022, 12, 7, 14, 14, 46, 0)),
72                        'geometry': geometry})
73
74     def add_address_placex(self, object_id, **kw):
75         self.add_placex(**kw)
76         self.add_data('addressline',
77                       {'place_id': object_id,
78                        'address_place_id': kw.get('place_id', 1000),
79                        'distance': kw.get('distance', 0.0),
80                        'cached_rank_address': kw.get('rank_address', 30),
81                        'fromarea': kw.get('fromarea', False),
82                        'isaddress': kw.get('isaddress', True)})
83
84     def add_osmline(self, **kw):
85         self.add_data('osmline',
86                       {'place_id': kw.get('place_id', 10000),
87                        'osm_id': kw.get('osm_id', 4004),
88                        'parent_place_id': kw.get('parent_place_id'),
89                        'indexed_date': kw.get('indexed_date',
90                                               dt.datetime(2022, 12, 7, 14, 14, 46, 0)),
91                        'startnumber': kw.get('startnumber', 2),
92                        'endnumber': kw.get('endnumber', 6),
93                        'step': kw.get('step', 2),
94                        'address': kw.get('address'),
95                        'postcode': kw.get('postcode'),
96                        'country_code': kw.get('country_code'),
97                        'linegeo': kw.get('geometry', 'LINESTRING(1.1 -0.2, 1.09 -0.22)')})
98
99     def add_tiger(self, **kw):
100         self.add_data('tiger',
101                       {'place_id': kw.get('place_id', 30000),
102                        'parent_place_id': kw.get('parent_place_id'),
103                        'startnumber': kw.get('startnumber', 2),
104                        'endnumber': kw.get('endnumber', 6),
105                        'step': kw.get('step', 2),
106                        'postcode': kw.get('postcode'),
107                        'linegeo': kw.get('geometry', 'LINESTRING(1.1 -0.2, 1.09 -0.22)')})
108
109     def add_postcode(self, **kw):
110         self.add_data('postcode',
111                       {'place_id': kw.get('place_id', 1000),
112                        'osm_id': kw.get('osm_id'),
113                        'parent_place_id': kw.get('parent_place_id'),
114                        'country_code': kw.get('country_code'),
115                        'postcode': kw.get('postcode'),
116                        'rank_search': kw.get('rank_search', 21),
117                        'indexed_date': kw.get('indexed_date',
118                                               dt.datetime(2022, 12, 7, 14, 14, 46, 0)),
119                        'centroid': kw.get('centroid', 'POINT(23 34)'),
120                        'geometry': kw.get('geometry', 'POLYGON((22.99 33.99, 22.99 34.01, '
121                                                       '23.01 34, 22.99 33.99))')})
122
123     def add_country(self, country_code, geometry):
124         self.add_data('country_grid',
125                       {'country_code': country_code,
126                        'area': 0.1,
127                        'geometry': geometry})
128
129     def add_country_name(self, country_code, names, partition=0):
130         self.add_data('country_name',
131                       {'country_code': country_code,
132                        'name': names,
133                        'partition': partition})
134
135     def add_search_name(self, place_id, **kw):
136         centroid = kw.get('centroid', (23.0, 34.0))
137         self.add_data('search_name',
138                       {'place_id': place_id,
139                        'importance': kw.get('importance', 0.00001),
140                        'search_rank': kw.get('search_rank', 30),
141                        'address_rank': kw.get('address_rank', 30),
142                        'name_vector': kw.get('names', []),
143                        'nameaddress_vector': kw.get('address', []),
144                        'country_code': kw.get('country_code', 'xx'),
145                        'centroid': 'POINT(%f %f)' % centroid})
146
147     def add_class_type_table(self, cls, typ):
148         self.async_to_sync(
149             self.exec_async(sa.text(f"""CREATE TABLE place_classtype_{cls}_{typ}
150                                          AS (SELECT place_id, centroid FROM placex
151                                              WHERE class = '{cls}' AND type = '{typ}')
152                                      """)))
153
154     def add_word_table(self, content):
155         data = [dict(zip(['word_id', 'word_token', 'type', 'word', 'info'], c))
156                 for c in content]
157
158         async def _do_sql():
159             async with self.api._async_api.begin() as conn:
160                 if 'word' not in conn.t.meta.tables:
161                     await make_query_analyzer(conn)
162                     word_table = conn.t.meta.tables['word']
163                     await conn.connection.run_sync(word_table.create)
164                 if data:
165                     await conn.execute(conn.t.meta.tables['word'].insert(), data)
166
167         self.async_to_sync(_do_sql())
168
169     async def exec_async(self, sql, *args, **kwargs):
170         async with self.api._async_api.begin() as conn:
171             return await conn.execute(sql, *args, **kwargs)
172
173     async def create_tables(self):
174         async with self.api._async_api._engine.begin() as conn:
175             await conn.run_sync(self.api._async_api._tables.meta.create_all)
176
177
178 @pytest.fixture
179 def apiobj(temp_db_with_extensions, temp_db_conn, monkeypatch):
180     """ Create an asynchronous SQLAlchemy engine for the test DB.
181     """
182     monkeypatch.setenv('NOMINATIM_USE_US_TIGER_DATA', 'yes')
183     testapi = APITester()
184     testapi.async_to_sync(testapi.create_tables())
185
186     proc = SQLPreprocessor(temp_db_conn, testapi.api.config)
187     proc.run_sql_file(temp_db_conn, 'functions/ranking.sql')
188
189     loglib.set_log_output('text')
190     yield testapi
191     print(loglib.get_and_disable())
192
193     testapi.api.close()
194
195
196 @pytest.fixture(params=['postgres_db', 'sqlite_db'])
197 def frontend(request, tmp_path):
198     testapis = []
199     if request.param == 'sqlite_db':
200         db = str(tmp_path / 'test_nominatim_python_unittest.sqlite')
201
202         def mkapi(apiobj, options={'reverse'}):
203             apiobj.add_data(
204                 'properties',
205                 [{'property': 'tokenizer', 'value': 'icu'},
206                  {'property': 'tokenizer_import_normalisation', 'value': ':: lower();'},
207                  {'property': 'tokenizer_import_transliteration',
208                   'value': "'1' > '/1/'; 'ä' > 'ä '"}])
209
210             async def _do_sql():
211                 async with apiobj.api._async_api.begin() as conn:
212                     if 'word' in conn.t.meta.tables:
213                         return
214                     await make_query_analyzer(conn)
215                     word_table = conn.t.meta.tables['word']
216                     await conn.connection.run_sync(word_table.create)
217
218             apiobj.async_to_sync(_do_sql())
219
220             apiobj.async_to_sync(convert_sqlite.convert(None, db, options))
221             outapi = napi.NominatimAPI(environ={'NOMINATIM_DATABASE_DSN': f"sqlite:dbname={db}",
222                                                 'NOMINATIM_USE_US_TIGER_DATA': 'yes'})
223             testapis.append(outapi)
224
225             return outapi
226     elif request.param == 'postgres_db':
227         def mkapi(apiobj, options=None):
228             return apiobj.api
229
230     yield mkapi
231
232     for api in testapis:
233         api.close()
234
235
236 @pytest_asyncio.fixture
237 async def api(temp_db):
238     async with napi.NominatimAPIAsync() as api:
239         yield api