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