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')
79 cur.execute('CREATE EXTENSION ltree')
85 def temp_db_conn(temp_db):
86 """ Connection to the test database.
88 with connection.connect('', autocommit=True, dbname=temp_db) as conn:
89 connection.register_hstore(conn)
94 def temp_db_cursor(temp_db):
95 """ Connection and cursor towards the test database. The connection will
96 be in auto-commit mode.
98 with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
99 connection.register_hstore(conn)
100 with conn.cursor() as cur:
105 def table_factory(temp_db_conn):
106 """ A fixture that creates new SQL tables, potentially filled with
109 def mk_table(name, definition='id INT', content=None):
110 with psycopg.ClientCursor(temp_db_conn) as cur:
111 cur.execute(pysql.SQL("CREATE TABLE {} ({})")
112 .format(pysql.Identifier(name),
113 pysql.SQL(definition)))
115 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
116 .format(pysql.Identifier(name),
117 pysql.SQL(',').join([pysql.Placeholder()
118 for _ in range(len(content[0]))]))
119 cur.executemany(sql, content)
126 cfg = Configuration(None)
131 def project_env(tmp_path):
132 projdir = tmp_path / 'project'
134 cfg = Configuration(projdir)
139 def country_table(table_factory):
140 table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
144 def country_row(country_table, temp_db_cursor):
145 def _add(partition=None, country=None, names=None):
146 temp_db_cursor.insert_row('country_name', partition=partition,
147 country_code=country, name=names)
153 def load_sql(temp_db_conn, country_table):
154 conf = Configuration(None)
156 def _run(*filename, **kwargs):
158 SQLPreprocessor(temp_db_conn, conf).run_sql_file(temp_db_conn, fn, **kwargs)
164 def property_table(load_sql, temp_db_conn):
165 load_sql('tables/nominatim_properties.sql')
168 def set(self, name, value):
169 properties.set_property(temp_db_conn, name, value)
172 return properties.get_property(temp_db_conn, name)
178 def status_table(load_sql):
179 """ Create an empty version of the status table and
180 the status logging table.
182 load_sql('tables/status.sql')
186 def place_table(temp_db_with_extensions, table_factory):
187 """ Create an empty version of the place table.
189 table_factory('place',
190 """osm_id int8 NOT NULL,
191 osm_type char(1) NOT NULL,
195 admin_level smallint,
199 geometry GEOMETRY(Geometry,4326) NOT NULL""")
203 def place_row(place_table, temp_db_cursor):
204 """ A factory for rows in the place table. The table is created as a
205 prerequisite to the fixture.
207 idseq = itertools.count(1001)
209 def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
210 admin_level=None, address=None, extratags=None, categories=None,
212 args = {'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
213 'class': cls, 'type': typ, 'name': names,
214 'admin_level': admin_level, 'address': address,
215 'extratags': extratags, 'categories': categories,
216 'geometry': _with_srid(geom)}
217 temp_db_cursor.insert_row('place', **args)
223 def place_postcode_table(temp_db_with_extensions, table_factory):
224 """ Create an empty version of the place_postcode table.
226 table_factory('place_postcode',
227 """osm_type char(1) NOT NULL,
228 osm_id bigint NOT NULL,
229 postcode text NOT NULL,
231 centroid GEOMETRY(Point, 4326) NOT NULL,
232 geometry GEOMETRY(Geometry, 4326)""")
236 def place_postcode_row(place_postcode_table, temp_db_cursor):
237 """ A factory for rows in the place_postcode table. The table is created as a
238 prerequisite to the fixture.
240 idseq = itertools.count(5001)
242 def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
243 centroid='POINT(12.0 4.0)', geom=None):
244 temp_db_cursor.insert_row('place_postcode',
245 osm_type=osm_type, osm_id=osm_id or next(idseq),
246 postcode=postcode, country_code=country,
247 centroid=_with_srid(centroid),
248 geometry=_with_srid(geom))
254 def place_interpolation_table(temp_db_with_extensions, table_factory):
255 """ Create an empty version of the place_interpolation table.
257 table_factory('place_interpolation',
258 """osm_id bigint NOT NULL,
262 geometry GEOMETRY(Geometry, 4326)""")
266 def place_interpolation_row(place_interpolation_table, temp_db_cursor):
267 """ A factory for rows in the place_interpolation table. The table is created as a
268 prerequisite to the fixture.
270 idseq = itertools.count(30001)
272 def _insert(osm_id=None, typ='odd', address=None,
273 nodes=None, geom='LINESTRING(0.1 0.21, 0.1 0.2)'):
274 params = {'osm_id': osm_id or next(idseq),
275 'type': typ, 'address': address, 'nodes': nodes,
276 'geometry': _with_srid(geom)}
277 temp_db_cursor.insert_row('place_interpolation', **params)
283 def placex_table(temp_db_with_extensions, temp_db_conn, load_sql, place_table):
284 """ Create an empty version of the placex table.
286 load_sql('tables/placex.sql')
287 temp_db_conn.execute("CREATE SEQUENCE IF NOT EXISTS seq_place START 1")
291 def placex_row(placex_table, temp_db_cursor):
292 """ A factory for rows in the placex table. The table is created as a
293 prerequisite to the fixture.
295 idseq = itertools.count(1001)
297 def _add(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
298 admin_level=None, address=None, extratags=None, categories=None,
299 geom='POINT(10 4)', country=None, housenumber=None, rank_search=30,
300 rank_address=30, centroid='POINT(10 4)', indexed_status=0,
301 indexed_date=None, importance=0.00001):
302 args = {'place_id': pysql.SQL("nextval('seq_place')"),
303 'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
304 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
305 'address': address, 'housenumber': housenumber,
306 'rank_search': rank_search, 'rank_address': rank_address,
307 'extratags': extratags, 'categories': categories, 'importance': importance,
308 'centroid': _with_srid(centroid), 'geometry': _with_srid(geom),
309 'country_code': country,
310 'indexed_status': indexed_status, 'indexed_date': indexed_date,
311 'partition': pysql.Literal(0), 'geometry_sector': pysql.Literal(1)}
312 return temp_db_cursor.insert_row('placex', **args)
318 def osmline_table(temp_db_with_extensions, load_sql):
319 load_sql('tables/interpolation.sql')
323 def osmline_row(osmline_table, temp_db_cursor):
324 idseq = itertools.count(20001)
326 def _add(osm_id=None, geom='LINESTRING(12.0 11.0, 12.003 11.0)'):
327 return temp_db_cursor.insert_row(
328 'location_property_osmline',
329 place_id=pysql.SQL("nextval('seq_place')"),
330 osm_id=osm_id or next(idseq),
331 geometry_sector=pysql.Literal(20),
332 partition=pysql.Literal(0),
334 linegeo=_with_srid(geom))
340 def postcode_table(temp_db_with_extensions, load_sql):
341 load_sql('tables/postcodes.sql')
345 def postcode_row(postcode_table, temp_db_cursor):
346 def _add(country, postcode, x=34.5, y=-9.33, is_area=False):
347 geom = _with_srid(f"POINT({x} {y})")
348 return temp_db_cursor.insert_row(
349 'location_postcodes',
350 place_id=pysql.SQL("nextval('seq_place')"),
351 indexed_status=pysql.Literal(1),
352 country_code=country, postcode=postcode, is_area=is_area,
354 rank_search=pysql.Literal(16),
355 geometry=('ST_Expand(%s::geometry, 0.005)', geom))
361 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions, country_row):
362 for part in range(3):
363 country_row(partition=part)
365 cfg = Configuration(None)
366 cfg.set_libdirs(sql=tmp_path)
371 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
372 return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
376 def tokenizer_mock(monkeypatch, property_table):
377 """ Sets up the configuration so that the test dummy tokenizer will be
378 loaded when the tokenizer factory is used. Also returns a factory
379 with which a new dummy tokenizer may be created.
381 monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
383 def _import_dummy(*args, **kwargs):
384 return dummy_tokenizer
386 monkeypatch.setattr(nominatim_db.tokenizer.factory,
387 "_import_tokenizer", _import_dummy)
388 property_table.set('tokenizer', 'dummy')
390 def _create_tokenizer():
391 return dummy_tokenizer.DummyTokenizer(None)
393 return _create_tokenizer