1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2026 by the Nominatim developer community.
6 # For a full list of authors see the git log.
10 from pathlib import Path
11 from packaging.version import Version
14 if sys.platform == 'win32':
15 if Version(pytest_asyncio.__version__) >= Version("1.4.0"):
16 # pytest-asyncio hook for event loop factory.
17 def pytest_asyncio_loop_factories(config, item):
18 return {"selector": asyncio.SelectorEventLoop}
20 asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
23 from psycopg import sql as pysql
26 # always test against the source
27 SRC_DIR = (Path(__file__) / '..' / '..' / '..').resolve()
28 sys.path.insert(0, str(SRC_DIR / 'src'))
30 from nominatim_db.config import Configuration
31 from nominatim_db.db import connection, properties
32 from nominatim_db.db.sql_preprocessor import SQLPreprocessor
33 import nominatim_db.tokenizer.factory
35 import dummy_tokenizer
36 from cursor import CursorForTesting
39 def _with_srid(geom, default=None):
41 return None if default is None else f"SRID=4326;{default}"
43 return f"SRID=4326;{geom}"
52 def temp_db(monkeypatch):
53 """ Create an empty database for the test. The database name is also
54 exported into NOMINATIM_DATABASE_DSN.
56 name = 'test_nominatim_python_unittest'
58 with psycopg.connect(dbname='postgres', autocommit=True) as conn:
59 with conn.cursor() as cur:
60 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
61 cur.execute(pysql.SQL('CREATE DATABASE') + pysql.Identifier(name))
63 monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
65 with psycopg.connect(dbname=name) as conn:
66 with conn.cursor() as cur:
67 cur.execute('CREATE EXTENSION hstore')
71 with psycopg.connect(dbname='postgres', autocommit=True) as conn:
72 with conn.cursor() as cur:
73 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
78 return 'dbname=' + temp_db
82 def temp_db_with_extensions(temp_db):
83 with psycopg.connect(dbname=temp_db) as conn:
84 with conn.cursor() as cur:
85 cur.execute('CREATE EXTENSION postgis')
91 def temp_db_conn(temp_db):
92 """ Connection to the test database.
94 with connection.connect('', autocommit=True, dbname=temp_db) as conn:
95 connection.register_hstore(conn)
100 def temp_db_cursor(temp_db):
101 """ Connection and cursor towards the test database. The connection will
102 be in auto-commit mode.
104 with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
105 connection.register_hstore(conn)
106 with conn.cursor() as cur:
111 def table_factory(temp_db_conn):
112 """ A fixture that creates new SQL tables, potentially filled with
115 def mk_table(name, definition='id INT', content=None):
116 with psycopg.ClientCursor(temp_db_conn) as cur:
117 cur.execute(pysql.SQL("CREATE TABLE {} ({})")
118 .format(pysql.Identifier(name),
119 pysql.SQL(definition)))
121 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
122 .format(pysql.Identifier(name),
123 pysql.SQL(',').join([pysql.Placeholder()
124 for _ in range(len(content[0]))]))
125 cur.executemany(sql, content)
132 cfg = Configuration(None)
137 def project_env(tmp_path):
138 projdir = tmp_path / 'project'
140 cfg = Configuration(projdir)
145 def country_table(table_factory):
146 table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
150 def country_row(country_table, temp_db_cursor):
151 def _add(partition=None, country=None, names=None):
152 temp_db_cursor.insert_row('country_name', partition=partition,
153 country_code=country, name=names)
159 def load_sql(temp_db_conn, country_table):
160 conf = Configuration(None)
162 def _run(*filename, **kwargs):
164 SQLPreprocessor(temp_db_conn, conf).run_sql_file(temp_db_conn, fn, **kwargs)
170 def property_table(load_sql, temp_db_conn):
171 load_sql('tables/nominatim_properties.sql')
174 def set(self, name, value):
175 properties.set_property(temp_db_conn, name, value)
178 return properties.get_property(temp_db_conn, name)
184 def status_table(load_sql):
185 """ Create an empty version of the status table and
186 the status logging table.
188 load_sql('tables/status.sql')
192 def place_table(temp_db_with_extensions, table_factory):
193 """ Create an empty version of the place table.
195 table_factory('place',
196 """osm_id int8 NOT NULL,
197 osm_type char(1) NOT NULL,
201 admin_level smallint,
204 geometry GEOMETRY(Geometry,4326) NOT NULL""")
208 def place_row(place_table, temp_db_cursor):
209 """ A factory for rows in the place table. The table is created as a
210 prerequisite to the fixture.
212 idseq = itertools.count(1001)
214 def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
215 admin_level=None, address=None, extratags=None, geom='POINT(0 0)'):
216 args = {'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
217 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
218 'address': address, 'extratags': extratags,
219 'geometry': _with_srid(geom)}
220 temp_db_cursor.insert_row('place', **args)
226 def place_postcode_table(temp_db_with_extensions, table_factory):
227 """ Create an empty version of the place_postcode table.
229 table_factory('place_postcode',
230 """osm_type char(1) NOT NULL,
231 osm_id bigint NOT NULL,
232 postcode text NOT NULL,
234 centroid GEOMETRY(Point, 4326) NOT NULL,
235 geometry GEOMETRY(Geometry, 4326)""")
239 def place_postcode_row(place_postcode_table, temp_db_cursor):
240 """ A factory for rows in the place_postcode table. The table is created as a
241 prerequisite to the fixture.
243 idseq = itertools.count(5001)
245 def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
246 centroid='POINT(12.0 4.0)', geom=None):
247 temp_db_cursor.insert_row('place_postcode',
248 osm_type=osm_type, osm_id=osm_id or next(idseq),
249 postcode=postcode, country_code=country,
250 centroid=_with_srid(centroid),
251 geometry=_with_srid(geom))
257 def place_interpolation_table(temp_db_with_extensions, table_factory):
258 """ Create an empty version of the place_interpolation table.
260 table_factory('place_interpolation',
261 """osm_id bigint NOT NULL,
265 geometry GEOMETRY(Geometry, 4326)""")
269 def place_interpolation_row(place_interpolation_table, temp_db_cursor):
270 """ A factory for rows in the place_interpolation table. The table is created as a
271 prerequisite to the fixture.
273 idseq = itertools.count(30001)
275 def _insert(osm_id=None, typ='odd', address=None,
276 nodes=None, geom='LINESTRING(0.1 0.21, 0.1 0.2)'):
277 params = {'osm_id': osm_id or next(idseq),
278 'type': typ, 'address': address, 'nodes': nodes,
279 'geometry': _with_srid(geom)}
280 temp_db_cursor.insert_row('place_interpolation', **params)
286 def placex_table(temp_db_with_extensions, temp_db_conn, load_sql, place_table):
287 """ Create an empty version of the placex table.
289 load_sql('tables/placex.sql')
290 temp_db_conn.execute("CREATE SEQUENCE IF NOT EXISTS seq_place START 1")
294 def placex_row(placex_table, temp_db_cursor):
295 """ A factory for rows in the placex table. The table is created as a
296 prerequisite to the fixture.
298 idseq = itertools.count(1001)
300 def _add(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
301 admin_level=None, address=None, extratags=None, geom='POINT(10 4)',
302 country=None, housenumber=None, rank_search=30, rank_address=30,
303 centroid='POINT(10 4)', indexed_status=0, indexed_date=None,
305 args = {'place_id': pysql.SQL("nextval('seq_place')"),
306 'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
307 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
308 'address': address, 'housenumber': housenumber,
309 'rank_search': rank_search, 'rank_address': rank_address,
310 'extratags': extratags, 'importance': importance,
311 'centroid': _with_srid(centroid), 'geometry': _with_srid(geom),
312 'country_code': country,
313 'indexed_status': indexed_status, 'indexed_date': indexed_date,
314 'partition': pysql.Literal(0), 'geometry_sector': pysql.Literal(1)}
315 return temp_db_cursor.insert_row('placex', **args)
321 def osmline_table(temp_db_with_extensions, load_sql):
322 load_sql('tables/interpolation.sql')
326 def osmline_row(osmline_table, temp_db_cursor):
327 idseq = itertools.count(20001)
329 def _add(osm_id=None, geom='LINESTRING(12.0 11.0, 12.003 11.0)'):
330 return temp_db_cursor.insert_row(
331 'location_property_osmline',
332 place_id=pysql.SQL("nextval('seq_place')"),
333 osm_id=osm_id or next(idseq),
334 geometry_sector=pysql.Literal(20),
335 partition=pysql.Literal(0),
337 linegeo=_with_srid(geom))
343 def postcode_table(temp_db_with_extensions, load_sql):
344 load_sql('tables/postcodes.sql')
348 def postcode_row(postcode_table, temp_db_cursor):
349 def _add(country, postcode, x=34.5, y=-9.33, is_area=False):
350 geom = _with_srid(f"POINT({x} {y})")
351 return temp_db_cursor.insert_row(
352 'location_postcodes',
353 place_id=pysql.SQL("nextval('seq_place')"),
354 indexed_status=pysql.Literal(1),
355 country_code=country, postcode=postcode, is_area=is_area,
357 rank_search=pysql.Literal(16),
358 geometry=('ST_Expand(%s::geometry, 0.005)', geom))
364 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions, country_row):
365 for part in range(3):
366 country_row(partition=part)
368 cfg = Configuration(None)
369 cfg.set_libdirs(sql=tmp_path)
374 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
375 return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
379 def tokenizer_mock(monkeypatch, property_table):
380 """ Sets up the configuration so that the test dummy tokenizer will be
381 loaded when the tokenizer factory is used. Also returns a factory
382 with which a new dummy tokenizer may be created.
384 monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
386 def _import_dummy(*args, **kwargs):
387 return dummy_tokenizer
389 monkeypatch.setattr(nominatim_db.tokenizer.factory,
390 "_import_tokenizer", _import_dummy)
391 property_table.set('tokenizer', 'dummy')
393 def _create_tokenizer():
394 return dummy_tokenizer.DummyTokenizer(None)
396 return _create_tokenizer