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')
86 cur.execute('CREATE EXTENSION ltree')
92 def temp_db_conn(temp_db):
93 """ Connection to the test database.
95 with connection.connect('', autocommit=True, dbname=temp_db) as conn:
96 connection.register_hstore(conn)
101 def temp_db_cursor(temp_db):
102 """ Connection and cursor towards the test database. The connection will
103 be in auto-commit mode.
105 with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
106 connection.register_hstore(conn)
107 with conn.cursor() as cur:
112 def table_factory(temp_db_conn):
113 """ A fixture that creates new SQL tables, potentially filled with
116 def mk_table(name, definition='id INT', content=None):
117 with psycopg.ClientCursor(temp_db_conn) as cur:
118 cur.execute(pysql.SQL("CREATE TABLE {} ({})")
119 .format(pysql.Identifier(name),
120 pysql.SQL(definition)))
122 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
123 .format(pysql.Identifier(name),
124 pysql.SQL(',').join([pysql.Placeholder()
125 for _ in range(len(content[0]))]))
126 cur.executemany(sql, content)
133 cfg = Configuration(None)
138 def project_env(tmp_path):
139 projdir = tmp_path / 'project'
141 cfg = Configuration(projdir)
146 def country_table(table_factory):
147 table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
151 def country_row(country_table, temp_db_cursor):
152 def _add(partition=None, country=None, names=None):
153 temp_db_cursor.insert_row('country_name', partition=partition,
154 country_code=country, name=names)
160 def load_sql(temp_db_conn, country_table):
161 conf = Configuration(None)
163 def _run(*filename, **kwargs):
165 SQLPreprocessor(temp_db_conn, conf).run_sql_file(temp_db_conn, fn, **kwargs)
171 def property_table(load_sql, temp_db_conn):
172 load_sql('tables/nominatim_properties.sql')
175 def set(self, name, value):
176 properties.set_property(temp_db_conn, name, value)
179 return properties.get_property(temp_db_conn, name)
185 def status_table(load_sql):
186 """ Create an empty version of the status table and
187 the status logging table.
189 load_sql('tables/status.sql')
193 def place_table(temp_db_with_extensions, table_factory):
194 """ Create an empty version of the place table.
196 table_factory('place',
197 """osm_id int8 NOT NULL,
198 osm_type char(1) NOT NULL,
202 admin_level smallint,
206 geometry GEOMETRY(Geometry,4326) NOT NULL""")
210 def place_row(place_table, temp_db_cursor):
211 """ A factory for rows in the place table. The table is created as a
212 prerequisite to the fixture.
214 idseq = itertools.count(1001)
216 def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
217 admin_level=None, address=None, extratags=None, categories=None,
219 args = {'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
220 'class': cls, 'type': typ, 'name': names,
221 'admin_level': admin_level, 'address': address,
222 'extratags': extratags, 'categories': categories,
223 'geometry': _with_srid(geom)}
224 temp_db_cursor.insert_row('place', **args)
230 def place_postcode_table(temp_db_with_extensions, table_factory):
231 """ Create an empty version of the place_postcode table.
233 table_factory('place_postcode',
234 """osm_type char(1) NOT NULL,
235 osm_id bigint NOT NULL,
236 postcode text NOT NULL,
238 centroid GEOMETRY(Point, 4326) NOT NULL,
239 geometry GEOMETRY(Geometry, 4326)""")
243 def place_postcode_row(place_postcode_table, temp_db_cursor):
244 """ A factory for rows in the place_postcode table. The table is created as a
245 prerequisite to the fixture.
247 idseq = itertools.count(5001)
249 def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
250 centroid='POINT(12.0 4.0)', geom=None):
251 temp_db_cursor.insert_row('place_postcode',
252 osm_type=osm_type, osm_id=osm_id or next(idseq),
253 postcode=postcode, country_code=country,
254 centroid=_with_srid(centroid),
255 geometry=_with_srid(geom))
261 def place_interpolation_table(temp_db_with_extensions, table_factory):
262 """ Create an empty version of the place_interpolation table.
264 table_factory('place_interpolation',
265 """osm_id bigint NOT NULL,
269 geometry GEOMETRY(Geometry, 4326)""")
273 def place_interpolation_row(place_interpolation_table, temp_db_cursor):
274 """ A factory for rows in the place_interpolation table. The table is created as a
275 prerequisite to the fixture.
277 idseq = itertools.count(30001)
279 def _insert(osm_id=None, typ='odd', address=None,
280 nodes=None, geom='LINESTRING(0.1 0.21, 0.1 0.2)'):
281 params = {'osm_id': osm_id or next(idseq),
282 'type': typ, 'address': address, 'nodes': nodes,
283 'geometry': _with_srid(geom)}
284 temp_db_cursor.insert_row('place_interpolation', **params)
290 def placex_table(temp_db_with_extensions, temp_db_conn, load_sql, place_table):
291 """ Create an empty version of the placex table.
293 load_sql('tables/placex.sql')
294 temp_db_conn.execute("CREATE SEQUENCE IF NOT EXISTS seq_place START 1")
298 def placex_row(placex_table, temp_db_cursor):
299 """ A factory for rows in the placex table. The table is created as a
300 prerequisite to the fixture.
302 idseq = itertools.count(1001)
304 def _add(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
305 admin_level=None, address=None, extratags=None, categories=None,
306 geom='POINT(10 4)', country=None, housenumber=None, rank_search=30,
307 rank_address=30, centroid='POINT(10 4)', indexed_status=0,
308 indexed_date=None, importance=0.00001):
309 args = {'place_id': pysql.SQL("nextval('seq_place')"),
310 'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
311 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
312 'address': address, 'housenumber': housenumber,
313 'rank_search': rank_search, 'rank_address': rank_address,
314 'extratags': extratags, 'categories': categories, 'importance': importance,
315 'centroid': _with_srid(centroid), 'geometry': _with_srid(geom),
316 'country_code': country,
317 'indexed_status': indexed_status, 'indexed_date': indexed_date,
318 'partition': pysql.Literal(0), 'geometry_sector': pysql.Literal(1)}
319 return temp_db_cursor.insert_row('placex', **args)
325 def osmline_table(temp_db_with_extensions, load_sql):
326 load_sql('tables/interpolation.sql')
330 def osmline_row(osmline_table, temp_db_cursor):
331 idseq = itertools.count(20001)
333 def _add(osm_id=None, geom='LINESTRING(12.0 11.0, 12.003 11.0)'):
334 return temp_db_cursor.insert_row(
335 'location_property_osmline',
336 place_id=pysql.SQL("nextval('seq_place')"),
337 osm_id=osm_id or next(idseq),
338 geometry_sector=pysql.Literal(20),
339 partition=pysql.Literal(0),
341 linegeo=_with_srid(geom))
347 def postcode_table(temp_db_with_extensions, load_sql):
348 load_sql('tables/postcodes.sql')
352 def postcode_row(postcode_table, temp_db_cursor):
353 def _add(country, postcode, x=34.5, y=-9.33, is_area=False):
354 geom = _with_srid(f"POINT({x} {y})")
355 return temp_db_cursor.insert_row(
356 'location_postcodes',
357 place_id=pysql.SQL("nextval('seq_place')"),
358 indexed_status=pysql.Literal(1),
359 country_code=country, postcode=postcode, is_area=is_area,
361 rank_search=pysql.Literal(16),
362 geometry=('ST_Expand(%s::geometry, 0.005)', geom))
368 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions, country_row):
369 for part in range(3):
370 country_row(partition=part)
372 cfg = Configuration(None)
373 cfg.set_libdirs(sql=tmp_path)
378 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
379 return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
383 def tokenizer_mock(monkeypatch, property_table):
384 """ Sets up the configuration so that the test dummy tokenizer will be
385 loaded when the tokenizer factory is used. Also returns a factory
386 with which a new dummy tokenizer may be created.
388 monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
390 def _import_dummy(*args, **kwargs):
391 return dummy_tokenizer
393 monkeypatch.setattr(nominatim_db.tokenizer.factory,
394 "_import_tokenizer", _import_dummy)
395 property_table.set('tokenizer', 'dummy')
397 def _create_tokenizer():
398 return dummy_tokenizer.DummyTokenizer(None)
400 return _create_tokenizer