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.
9 from pathlib import Path
12 from psycopg import sql as pysql
15 # always test against the source
16 SRC_DIR = (Path(__file__) / '..' / '..' / '..').resolve()
17 sys.path.insert(0, str(SRC_DIR / 'src'))
19 from nominatim_db.config import Configuration
20 from nominatim_db.db import connection
21 from nominatim_db.db.sql_preprocessor import SQLPreprocessor
22 import nominatim_db.tokenizer.factory
24 import dummy_tokenizer
26 from cursor import CursorForTesting
29 def _with_srid(geom, default=None):
31 return None if default is None else f"SRID=4326;{default}"
33 return f"SRID=4326;{geom}"
42 def temp_db(monkeypatch):
43 """ Create an empty database for the test. The database name is also
44 exported into NOMINATIM_DATABASE_DSN.
46 name = 'test_nominatim_python_unittest'
48 with psycopg.connect(dbname='postgres', autocommit=True) as conn:
49 with conn.cursor() as cur:
50 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
51 cur.execute(pysql.SQL('CREATE DATABASE') + pysql.Identifier(name))
53 monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
55 with psycopg.connect(dbname=name) as conn:
56 with conn.cursor() as cur:
57 cur.execute('CREATE EXTENSION hstore')
61 with psycopg.connect(dbname='postgres', autocommit=True) as conn:
62 with conn.cursor() as cur:
63 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
68 return 'dbname=' + temp_db
72 def temp_db_with_extensions(temp_db):
73 with psycopg.connect(dbname=temp_db) as conn:
74 with conn.cursor() as cur:
75 cur.execute('CREATE EXTENSION postgis')
81 def temp_db_conn(temp_db):
82 """ Connection to the test database.
84 with connection.connect('', autocommit=True, dbname=temp_db) as conn:
85 connection.register_hstore(conn)
90 def temp_db_cursor(temp_db):
91 """ Connection and cursor towards the test database. The connection will
92 be in auto-commit mode.
94 with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
95 connection.register_hstore(conn)
96 with conn.cursor() as cur:
101 def table_factory(temp_db_conn):
102 """ A fixture that creates new SQL tables, potentially filled with
105 def mk_table(name, definition='id INT', content=None):
106 with psycopg.ClientCursor(temp_db_conn) as cur:
107 cur.execute(pysql.SQL("CREATE TABLE {} ({})")
108 .format(pysql.Identifier(name),
109 pysql.SQL(definition)))
111 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
112 .format(pysql.Identifier(name),
113 pysql.SQL(',').join([pysql.Placeholder()
114 for _ in range(len(content[0]))]))
115 cur.executemany(sql, content)
122 cfg = Configuration(None)
127 def project_env(tmp_path):
128 projdir = tmp_path / 'project'
130 cfg = Configuration(projdir)
135 def property_table(table_factory, temp_db_conn):
136 table_factory('nominatim_properties', 'property TEXT, value TEXT')
138 return mocks.MockPropertyTable(temp_db_conn)
142 def status_table(table_factory):
143 """ Create an empty version of the status table and
144 the status logging table.
146 table_factory('import_status',
147 """lastimportdate timestamp with time zone NOT NULL,
150 table_factory('import_osmosis_log',
151 """batchend timestamp,
160 def place_table(temp_db_with_extensions, table_factory):
161 """ Create an empty version of the place table.
163 table_factory('place',
164 """osm_id int8 NOT NULL,
165 osm_type char(1) NOT NULL,
169 admin_level smallint,
172 geometry Geometry(Geometry,4326) NOT NULL""")
176 def place_row(place_table, temp_db_cursor):
177 """ A factory for rows in the place table. The table is created as a
178 prerequisite to the fixture.
180 idseq = itertools.count(1001)
182 def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
183 admin_level=None, address=None, extratags=None, geom='POINT(0 0)'):
184 args = {'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
185 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
186 'address': address, 'extratags': extratags,
187 'geometry': _with_srid(geom)}
188 temp_db_cursor.insert_row('place', **args)
194 def place_postcode_table(temp_db_with_extensions, table_factory):
195 """ Create an empty version of the place_postcode table.
197 table_factory('place_postcode',
198 """osm_type char(1) NOT NULL,
199 osm_id bigint NOT NULL,
200 postcode text NOT NULL,
202 centroid Geometry(Point, 4326) NOT NULL,
203 geometry Geometry(Geometry, 4326)""")
207 def place_postcode_row(place_postcode_table, temp_db_cursor):
208 """ A factory for rows in the place_postcode table. The table is created as a
209 prerequisite to the fixture.
211 idseq = itertools.count(5001)
213 def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
214 centroid='POINT(12.0 4.0)', geom=None):
215 temp_db_cursor.insert_row('place_postcode',
216 osm_type=osm_type, osm_id=osm_id or next(idseq),
217 postcode=postcode, country_code=country,
218 centroid=_with_srid(centroid),
219 geometry=_with_srid(geom))
225 def placex_table(temp_db_with_extensions, temp_db_conn):
226 """ Create an empty version of the place table.
228 return mocks.MockPlacexTable(temp_db_conn)
232 def osmline_table(temp_db_with_extensions, table_factory):
233 table_factory('location_property_osmline',
236 parent_place_id BIGINT,
237 geometry_sector INTEGER,
238 indexed_date TIMESTAMP,
242 indexed_status SMALLINT,
244 interpolationtype TEXT,
247 country_code VARCHAR(2)""")
251 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions):
252 table_factory('country_name', 'partition INT', ((0, ), (1, ), (2, )))
253 cfg = Configuration(None)
254 cfg.set_libdirs(sql=tmp_path)
259 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
260 return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
264 def tokenizer_mock(monkeypatch, property_table):
265 """ Sets up the configuration so that the test dummy tokenizer will be
266 loaded when the tokenizer factory is used. Also returns a factory
267 with which a new dummy tokenizer may be created.
269 monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
271 def _import_dummy(*args, **kwargs):
272 return dummy_tokenizer
274 monkeypatch.setattr(nominatim_db.tokenizer.factory,
275 "_import_tokenizer", _import_dummy)
276 property_table.set('tokenizer', 'dummy')
278 def _create_tokenizer():
279 return dummy_tokenizer.DummyTokenizer(None)
281 return _create_tokenizer