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'),
 
  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_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)')})
 
  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)')})
 
 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)')})
 
 121     def add_country(self, country_code, geometry):
 
 122         self.add_data('country_grid',
 
 123                       {'country_code': country_code,
 
 125                        'geometry': geometry})
 
 127     def add_country_name(self, country_code, names, partition=0):
 
 128         self.add_data('country_name',
 
 129                       {'country_code': country_code,
 
 131                        'partition': partition})
 
 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})
 
 145     def add_class_type_table(self, cls, typ):
 
 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}')
 
 152     def add_word_table(self, content):
 
 153         data = [dict(zip(['word_id', 'word_token', 'type', 'word', 'info'], c))
 
 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)
 
 163                     await conn.execute(conn.t.meta.tables['word'].insert(), data)
 
 165         self.async_to_sync(_do_sql())
 
 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)
 
 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)
 
 177 def apiobj(temp_db_with_extensions, temp_db_conn, monkeypatch):
 
 178     """ Create an asynchronous SQLAlchemy engine for the test DB.
 
 180     monkeypatch.setenv('NOMINATIM_USE_US_TIGER_DATA', 'yes')
 
 181     testapi = APITester()
 
 182     testapi.async_to_sync(testapi.create_tables())
 
 184     proc = SQLPreprocessor(temp_db_conn, testapi.api.config)
 
 185     proc.run_sql_file(temp_db_conn, 'functions/ranking.sql')
 
 187     loglib.set_log_output('text')
 
 189     print(loglib.get_and_disable())
 
 194 @pytest.fixture(params=['postgres_db', 'sqlite_db'])
 
 195 def frontend(request, tmp_path):
 
 197     if request.param == 'sqlite_db':
 
 198         db = str(tmp_path / 'test_nominatim_python_unittest.sqlite')
 
 200         def mkapi(apiobj, options={'reverse'}):
 
 203                 [{'property': 'tokenizer', 'value': 'icu'},
 
 204                  {'property': 'tokenizer_import_normalisation', 'value': ':: lower();'},
 
 205                  {'property': 'tokenizer_import_transliteration',
 
 206                   'value': "'1' > '/1/'; 'ä' > 'ä '"}])
 
 209                 async with apiobj.api._async_api.begin() as conn:
 
 210                     if 'word' in conn.t.meta.tables:
 
 212                     await make_query_analyzer(conn)
 
 213                     word_table = conn.t.meta.tables['word']
 
 214                     await conn.connection.run_sync(word_table.create)
 
 216             apiobj.async_to_sync(_do_sql())
 
 218             apiobj.async_to_sync(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)
 
 224     elif request.param == 'postgres_db':
 
 225         def mkapi(apiobj, options=None):
 
 234 @pytest_asyncio.fixture
 
 235 async def api(temp_db):
 
 236     async with napi.NominatimAPIAsync() as api: