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
12 if sys.platform == 'win32':
13 asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
16 from psycopg import sql as pysql
19 # always test against the source
20 SRC_DIR = (Path(__file__) / '..' / '..' / '..').resolve()
21 sys.path.insert(0, str(SRC_DIR / 'src'))
23 from nominatim_db.config import Configuration
24 from nominatim_db.db import connection, properties
25 from nominatim_db.db.sql_preprocessor import SQLPreprocessor
26 import nominatim_db.tokenizer.factory
28 import dummy_tokenizer
29 from cursor import CursorForTesting
32 def _with_srid(geom, default=None):
34 return None if default is None else f"SRID=4326;{default}"
36 return f"SRID=4326;{geom}"
45 def temp_db(monkeypatch):
46 """ Create an empty database for the test. The database name is also
47 exported into NOMINATIM_DATABASE_DSN.
49 name = 'test_nominatim_python_unittest'
51 with psycopg.connect(dbname='postgres', autocommit=True) as conn:
52 with conn.cursor() as cur:
53 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
54 cur.execute(pysql.SQL('CREATE DATABASE') + pysql.Identifier(name))
56 monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
58 with psycopg.connect(dbname=name) as conn:
59 with conn.cursor() as cur:
60 cur.execute('CREATE EXTENSION hstore')
64 with psycopg.connect(dbname='postgres', autocommit=True) as conn:
65 with conn.cursor() as cur:
66 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
71 return 'dbname=' + temp_db
75 def temp_db_with_extensions(temp_db):
76 with psycopg.connect(dbname=temp_db) as conn:
77 with conn.cursor() as cur:
78 cur.execute('CREATE EXTENSION postgis')
84 def temp_db_conn(temp_db):
85 """ Connection to the test database.
87 with connection.connect('', autocommit=True, dbname=temp_db) as conn:
88 connection.register_hstore(conn)
93 def temp_db_cursor(temp_db):
94 """ Connection and cursor towards the test database. The connection will
95 be in auto-commit mode.
97 with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
98 connection.register_hstore(conn)
99 with conn.cursor() as cur:
104 def table_factory(temp_db_conn):
105 """ A fixture that creates new SQL tables, potentially filled with
108 def mk_table(name, definition='id INT', content=None):
109 with psycopg.ClientCursor(temp_db_conn) as cur:
110 cur.execute(pysql.SQL("CREATE TABLE {} ({})")
111 .format(pysql.Identifier(name),
112 pysql.SQL(definition)))
114 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
115 .format(pysql.Identifier(name),
116 pysql.SQL(',').join([pysql.Placeholder()
117 for _ in range(len(content[0]))]))
118 cur.executemany(sql, content)
125 cfg = Configuration(None)
130 def project_env(tmp_path):
131 projdir = tmp_path / 'project'
133 cfg = Configuration(projdir)
138 def country_table(table_factory):
139 table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
143 def country_row(country_table, temp_db_cursor):
144 def _add(partition=None, country=None, names=None):
145 temp_db_cursor.insert_row('country_name', partition=partition,
146 country_code=country, name=names)
152 def load_sql(temp_db_conn, country_table):
153 conf = Configuration(None)
155 def _run(*filename, **kwargs):
157 SQLPreprocessor(temp_db_conn, conf).run_sql_file(temp_db_conn, fn, **kwargs)
163 def property_table(load_sql, temp_db_conn):
164 load_sql('tables/nominatim_properties.sql')
167 def set(self, name, value):
168 properties.set_property(temp_db_conn, name, value)
171 return properties.get_property(temp_db_conn, name)
177 def status_table(load_sql):
178 """ Create an empty version of the status table and
179 the status logging table.
181 load_sql('tables/status.sql')
185 def place_table(temp_db_with_extensions, table_factory):
186 """ Create an empty version of the place table.
188 table_factory('place',
189 """osm_id int8 NOT NULL,
190 osm_type char(1) NOT NULL,
194 admin_level smallint,
197 geometry GEOMETRY(Geometry,4326) NOT NULL""")
201 def place_row(place_table, temp_db_cursor):
202 """ A factory for rows in the place table. The table is created as a
203 prerequisite to the fixture.
205 idseq = itertools.count(1001)
207 def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
208 admin_level=None, address=None, extratags=None, geom='POINT(0 0)'):
209 args = {'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
210 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
211 'address': address, 'extratags': extratags,
212 'geometry': _with_srid(geom)}
213 temp_db_cursor.insert_row('place', **args)
219 def place_postcode_table(temp_db_with_extensions, table_factory):
220 """ Create an empty version of the place_postcode table.
222 table_factory('place_postcode',
223 """osm_type char(1) NOT NULL,
224 osm_id bigint NOT NULL,
225 postcode text NOT NULL,
227 centroid GEOMETRY(Point, 4326) NOT NULL,
228 geometry GEOMETRY(Geometry, 4326)""")
232 def place_postcode_row(place_postcode_table, temp_db_cursor):
233 """ A factory for rows in the place_postcode table. The table is created as a
234 prerequisite to the fixture.
236 idseq = itertools.count(5001)
238 def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
239 centroid='POINT(12.0 4.0)', geom=None):
240 temp_db_cursor.insert_row('place_postcode',
241 osm_type=osm_type, osm_id=osm_id or next(idseq),
242 postcode=postcode, country_code=country,
243 centroid=_with_srid(centroid),
244 geometry=_with_srid(geom))
250 def place_interpolation_table(temp_db_with_extensions, table_factory):
251 """ Create an empty version of the place_interpolation table.
253 table_factory('place_interpolation',
254 """osm_id bigint NOT NULL,
258 geometry GEOMETRY(Geometry, 4326)""")
262 def place_interpolation_row(place_interpolation_table, temp_db_cursor):
263 """ A factory for rows in the place_interpolation table. The table is created as a
264 prerequisite to the fixture.
266 idseq = itertools.count(30001)
268 def _insert(osm_id=None, typ='odd', address=None,
269 nodes=None, geom='LINESTRING(0.1 0.21, 0.1 0.2)'):
270 params = {'osm_id': osm_id or next(idseq),
271 'type': typ, 'address': address, 'nodes': nodes,
272 'geometry': _with_srid(geom)}
273 temp_db_cursor.insert_row('place_interpolation', **params)
279 def placex_table(temp_db_with_extensions, temp_db_conn, load_sql, place_table):
280 """ Create an empty version of the placex table.
282 load_sql('tables/placex.sql')
283 temp_db_conn.execute("CREATE SEQUENCE IF NOT EXISTS seq_place START 1")
287 def placex_row(placex_table, temp_db_cursor):
288 """ A factory for rows in the placex table. The table is created as a
289 prerequisite to the fixture.
291 idseq = itertools.count(1001)
293 def _add(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
294 admin_level=None, address=None, extratags=None, geom='POINT(10 4)',
295 country=None, housenumber=None, rank_search=30, rank_address=30,
296 centroid='POINT(10 4)', indexed_status=0, indexed_date=None,
298 args = {'place_id': pysql.SQL("nextval('seq_place')"),
299 'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
300 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
301 'address': address, 'housenumber': housenumber,
302 'rank_search': rank_search, 'rank_address': rank_address,
303 'extratags': extratags, 'importance': importance,
304 'centroid': _with_srid(centroid), 'geometry': _with_srid(geom),
305 'country_code': country,
306 'indexed_status': indexed_status, 'indexed_date': indexed_date,
307 'partition': pysql.Literal(0), 'geometry_sector': pysql.Literal(1)}
308 return temp_db_cursor.insert_row('placex', **args)
314 def osmline_table(temp_db_with_extensions, load_sql):
315 load_sql('tables/interpolation.sql')
319 def osmline_row(osmline_table, temp_db_cursor):
320 idseq = itertools.count(20001)
322 def _add(osm_id=None, geom='LINESTRING(12.0 11.0, 12.003 11.0)'):
323 return temp_db_cursor.insert_row(
324 'location_property_osmline',
325 place_id=pysql.SQL("nextval('seq_place')"),
326 osm_id=osm_id or next(idseq),
327 geometry_sector=pysql.Literal(20),
328 partition=pysql.Literal(0),
330 linegeo=_with_srid(geom))
336 def postcode_table(temp_db_with_extensions, load_sql):
337 load_sql('tables/postcodes.sql')
341 def postcode_row(postcode_table, temp_db_cursor):
342 def _add(country, postcode, x=34.5, y=-9.33):
343 geom = _with_srid(f"POINT({x} {y})")
344 return temp_db_cursor.insert_row(
345 'location_postcodes',
346 place_id=pysql.SQL("nextval('seq_place')"),
347 indexed_status=pysql.Literal(1),
348 country_code=country, postcode=postcode,
350 rank_search=pysql.Literal(16),
351 geometry=('ST_Expand(%s::geometry, 0.005)', geom))
357 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions, country_row):
358 for part in range(3):
359 country_row(partition=part)
361 cfg = Configuration(None)
362 cfg.set_libdirs(sql=tmp_path)
367 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
368 return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
372 def tokenizer_mock(monkeypatch, property_table):
373 """ Sets up the configuration so that the test dummy tokenizer will be
374 loaded when the tokenizer factory is used. Also returns a factory
375 with which a new dummy tokenizer may be created.
377 monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
379 def _import_dummy(*args, **kwargs):
380 return dummy_tokenizer
382 monkeypatch.setattr(nominatim_db.tokenizer.factory,
383 "_import_tokenizer", _import_dummy)
384 property_table.set('tokenizer', 'dummy')
386 def _create_tokenizer():
387 return dummy_tokenizer.DummyTokenizer(None)
389 return _create_tokenizer