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 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
25 self.api = napi.NominatimAPI()
26 self.async_to_sync(self.api._async_api.setup_database())
28 def async_to_sync(self, func):
29 """ Run an asynchronous function until completion using the
30 internal loop of the API.
32 return self.api._loop.run_until_complete(func)
34 def add_data(self, table, data):
35 """ Insert data into the given table.
37 sql = getattr(self.api._async_api._tables, table).insert()
38 self.async_to_sync(self.exec_async(sql, data))
40 def add_placex(self, **kw):
42 if isinstance(name, str):
45 centroid = kw.get('centroid', (23.0, 34.0))
46 geometry = kw.get('geometry', 'POINT(%f %f)' % centroid)
48 cat = category_ltree(kw.get('class_', 'highway'), kw.get('type', 'residential'))
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]),
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})
76 def add_address_placex(self, object_id, **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)})
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)')})
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)')})
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))')})
127 def add_country(self, country_code, geometry):
128 self.add_data('country_grid',
129 {'country_code': country_code,
131 'geometry': geometry})
133 def add_country_name(self, country_code, names, partition=0):
134 self.add_data('country_name',
135 {'country_code': country_code,
137 'partition': partition})
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})
151 def add_word_table(self, content):
152 data = [dict(zip(['word_id', 'word_token', 'type', 'word', 'info'], c))
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)
162 await conn.execute(conn.t.meta.tables['word'].insert(), data)
164 self.async_to_sync(_do_sql())
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)
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)
176 def apiobj(temp_db_with_extensions, temp_db_conn, monkeypatch):
177 """ Create an asynchronous SQLAlchemy engine for the test DB.
179 monkeypatch.setenv('NOMINATIM_USE_US_TIGER_DATA', 'yes')
180 testapi = APITester()
181 testapi.async_to_sync(testapi.create_tables())
183 proc = SQLPreprocessor(temp_db_conn, testapi.api.config)
184 proc.run_sql_file(temp_db_conn, 'functions/ranking.sql')
186 loglib.set_log_output('text')
188 print(loglib.get_and_disable())
193 @pytest.fixture(params=['postgres_db', 'sqlite_db'])
194 def frontend(request, tmp_path):
196 if request.param == 'sqlite_db':
197 db = str(tmp_path / 'test_nominatim_python_unittest.sqlite')
199 def mkapi(apiobj, options={'reverse'}):
202 [{'property': 'tokenizer', 'value': 'icu'},
203 {'property': 'tokenizer_import_normalisation', 'value': ':: lower();'},
204 {'property': 'tokenizer_import_transliteration',
205 'value': "'1' > '/1/'; 'ä' > 'ä '"}])
208 async with apiobj.api._async_api.begin() as conn:
209 if 'word' in conn.t.meta.tables:
211 await make_query_analyzer(conn)
212 word_table = conn.t.meta.tables['word']
213 await conn.connection.run_sync(word_table.create)
215 apiobj.async_to_sync(_do_sql())
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)
223 elif request.param == 'postgres_db':
224 def mkapi(apiobj, options=None):
233 @pytest_asyncio.fixture
234 async def api(temp_db):
235 async with napi.NominatimAPIAsync() as api: