1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2025 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Helper fixtures for API call tests.
14 import sqlalchemy as sa
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
26 self.api = napi.NominatimAPI()
27 self.async_to_sync(self.api._async_api.setup_database())
29 def async_to_sync(self, func):
30 """ Run an asynchronous function until completion using the
31 internal loop of the API.
33 return self.api._loop.run_until_complete(func)
35 def add_data(self, table, data):
36 """ Insert data into the given table.
38 sql = getattr(self.api._async_api._tables, table).insert()
39 self.async_to_sync(self.exec_async(sql, data))
41 def add_placex(self, **kw):
43 if isinstance(name, str):
46 centroid = kw.get('centroid', (23.0, 34.0))
47 geometry = kw.get('geometry', 'POINT(%f %f)' % centroid)
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'),
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})
74 def add_address_placex(self, object_id, **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)})
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)')})
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)')})
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))')})
125 def add_country(self, country_code, geometry):
126 self.add_data('country_grid',
127 {'country_code': country_code,
129 'geometry': geometry})
131 def add_country_name(self, country_code, names, partition=0):
132 self.add_data('country_name',
133 {'country_code': country_code,
135 'partition': partition})
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})
149 def add_class_type_table(self, cls, typ):
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}')
156 def add_word_table(self, content):
157 data = [dict(zip(['word_id', 'word_token', 'type', 'word', 'info'], c))
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)
167 await conn.execute(conn.t.meta.tables['word'].insert(), data)
169 self.async_to_sync(_do_sql())
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)
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)
181 def apiobj(temp_db_with_extensions, temp_db_conn, monkeypatch):
182 """ Create an asynchronous SQLAlchemy engine for the test DB.
184 monkeypatch.setenv('NOMINATIM_USE_US_TIGER_DATA', 'yes')
185 testapi = APITester()
186 testapi.async_to_sync(testapi.create_tables())
188 proc = SQLPreprocessor(temp_db_conn, testapi.api.config)
189 proc.run_sql_file(temp_db_conn, 'functions/ranking.sql')
191 loglib.set_log_output('text')
193 print(loglib.get_and_disable())
198 @pytest.fixture(params=['postgres_db', 'sqlite_db'])
199 def frontend(request, tmp_path):
201 if request.param == 'sqlite_db':
202 db = str(tmp_path / 'test_nominatim_python_unittest.sqlite')
204 def mkapi(apiobj, options={'reverse'}):
207 [{'property': 'tokenizer', 'value': 'icu'},
208 {'property': 'tokenizer_import_normalisation', 'value': ':: lower();'},
209 {'property': 'tokenizer_import_transliteration',
210 'value': "'1' > '/1/'; 'ä' > 'ä '"}])
213 async with apiobj.api._async_api.begin() as conn:
214 if 'word' in conn.t.meta.tables:
216 await make_query_analyzer(conn)
217 word_table = conn.t.meta.tables['word']
218 await conn.connection.run_sync(word_table.create)
220 apiobj.async_to_sync(_do_sql())
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)
228 elif request.param == 'postgres_db':
229 def mkapi(apiobj, options=None):
238 @pytest_asyncio.fixture
239 async def api(temp_db):
240 async with napi.NominatimAPIAsync() as api: