]> git.openstreetmap.org Git - nominatim.git/blob - test/python/api/conftest.py
adapt tests to newly added table constraints
[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', 0.00001),
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_status': kw.get('indexed_status', 0),
90                        'indexed_date': kw.get('indexed_date',
91                                               dt.datetime(2022, 12, 7, 14, 14, 46, 0)),
92                        'startnumber': kw.get('startnumber', 2),
93                        'endnumber': kw.get('endnumber', 6),
94                        'step': kw.get('step', 2),
95                        'address': kw.get('address'),
96                        'postcode': kw.get('postcode'),
97                        'country_code': kw.get('country_code'),
98                        'linegeo': kw.get('geometry', 'LINESTRING(1.1 -0.2, 1.09 -0.22)')})
99
100     def add_tiger(self, **kw):
101         self.add_data('tiger',
102                       {'place_id': kw.get('place_id', 30000),
103                        'parent_place_id': kw.get('parent_place_id'),
104                        'startnumber': kw.get('startnumber', 2),
105                        'endnumber': kw.get('endnumber', 6),
106                        'step': kw.get('step', 2),
107                        'postcode': kw.get('postcode'),
108                        'linegeo': kw.get('geometry', 'LINESTRING(1.1 -0.2, 1.09 -0.22)')})
109
110     def add_postcode(self, **kw):
111         self.add_data('postcode',
112                       {'place_id': kw.get('place_id', 1000),
113                        'osm_id': kw.get('osm_id'),
114                        'parent_place_id': kw.get('parent_place_id'),
115                        'country_code': kw.get('country_code'),
116                        'postcode': kw.get('postcode'),
117                        'rank_search': kw.get('rank_search', 21),
118                        'indexed_status': kw.get('indexed_status', 0),
119                        'indexed_date': kw.get('indexed_date',
120                                               dt.datetime(2022, 12, 7, 14, 14, 46, 0)),
121                        'centroid': kw.get('centroid', 'POINT(23 34)'),
122                        'geometry': kw.get('geometry', 'POLYGON((22.99 33.99, 22.99 34.01, '
123                                                       '23.01 34, 22.99 33.99))')})
124
125     def add_country(self, country_code, geometry):
126         self.add_data('country_grid',
127                       {'country_code': country_code,
128                        'area': 0.1,
129                        'geometry': geometry})
130
131     def add_country_name(self, country_code, names, partition=0):
132         self.add_data('country_name',
133                       {'country_code': country_code,
134                        'name': names,
135                        'partition': partition})
136
137     def add_search_name(self, place_id, **kw):
138         centroid = kw.get('centroid', (23.0, 34.0))
139         self.add_data('search_name',
140                       {'place_id': place_id,
141                        'importance': kw.get('importance', 0.00001),
142                        'search_rank': kw.get('search_rank', 30),
143                        'address_rank': kw.get('address_rank', 30),
144                        'name_vector': kw.get('names', []),
145                        'nameaddress_vector': kw.get('address', []),
146                        'country_code': kw.get('country_code', 'xx'),
147                        'centroid': 'POINT(%f %f)' % centroid})
148
149     def add_class_type_table(self, cls, typ):
150         self.async_to_sync(
151             self.exec_async(sa.text(f"""CREATE TABLE place_classtype_{cls}_{typ}
152                                          AS (SELECT place_id, centroid FROM placex
153                                              WHERE class = '{cls}' AND type = '{typ}')
154                                      """)))
155
156     def add_word_table(self, content):
157         data = [dict(zip(['word_id', 'word_token', 'type', 'word', 'info'], c))
158                 for c in content]
159
160         async def _do_sql():
161             async with self.api._async_api.begin() as conn:
162                 if 'word' not in conn.t.meta.tables:
163                     await make_query_analyzer(conn)
164                     word_table = conn.t.meta.tables['word']
165                     await conn.connection.run_sync(word_table.create)
166                 if data:
167                     await conn.execute(conn.t.meta.tables['word'].insert(), data)
168
169         self.async_to_sync(_do_sql())
170
171     async def exec_async(self, sql, *args, **kwargs):
172         async with self.api._async_api.begin() as conn:
173             return await conn.execute(sql, *args, **kwargs)
174
175     async def create_tables(self):
176         async with self.api._async_api._engine.begin() as conn:
177             await conn.run_sync(self.api._async_api._tables.meta.create_all)
178
179
180 @pytest.fixture
181 def apiobj(temp_db_with_extensions, temp_db_conn, monkeypatch):
182     """ Create an asynchronous SQLAlchemy engine for the test DB.
183     """
184     monkeypatch.setenv('NOMINATIM_USE_US_TIGER_DATA', 'yes')
185     testapi = APITester()
186     testapi.async_to_sync(testapi.create_tables())
187
188     proc = SQLPreprocessor(temp_db_conn, testapi.api.config)
189     proc.run_sql_file(temp_db_conn, 'functions/ranking.sql')
190
191     loglib.set_log_output('text')
192     yield testapi
193     print(loglib.get_and_disable())
194
195     testapi.api.close()
196
197
198 @pytest.fixture(params=['postgres_db', 'sqlite_db'])
199 def frontend(request, tmp_path):
200     testapis = []
201     if request.param == 'sqlite_db':
202         db = str(tmp_path / 'test_nominatim_python_unittest.sqlite')
203
204         def mkapi(apiobj, options={'reverse'}):
205             apiobj.add_data(
206                 'properties',
207                 [{'property': 'tokenizer', 'value': 'icu'},
208                  {'property': 'tokenizer_import_normalisation', 'value': ':: lower();'},
209                  {'property': 'tokenizer_import_transliteration',
210                   'value': "'1' > '/1/'; 'ä' > 'ä '"}])
211
212             async def _do_sql():
213                 async with apiobj.api._async_api.begin() as conn:
214                     if 'word' in conn.t.meta.tables:
215                         return
216                     await make_query_analyzer(conn)
217                     word_table = conn.t.meta.tables['word']
218                     await conn.connection.run_sync(word_table.create)
219
220             apiobj.async_to_sync(_do_sql())
221
222             apiobj.async_to_sync(convert_sqlite.convert(None, db, options))
223             outapi = napi.NominatimAPI(environ={'NOMINATIM_DATABASE_DSN': f"sqlite:dbname={db}",
224                                                 'NOMINATIM_USE_US_TIGER_DATA': 'yes'})
225             testapis.append(outapi)
226
227             return outapi
228     elif request.param == 'postgres_db':
229         def mkapi(apiobj, options=None):
230             return apiobj.api
231
232     yield mkapi
233
234     for api in testapis:
235         api.close()
236
237
238 @pytest_asyncio.fixture
239 async def api(temp_db):
240     async with napi.NominatimAPIAsync() as api:
241         yield api