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