]> git.openstreetmap.org Git - nominatim.git/blob - test/python/conftest.py
make database import unit tests against real SQL
[nominatim.git] / test / python / conftest.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2026 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 import itertools
8 import sys
9 from pathlib import Path
10
11 import psycopg
12 from psycopg import sql as pysql
13 import pytest
14
15 # always test against the source
16 SRC_DIR = (Path(__file__) / '..' / '..' / '..').resolve()
17 sys.path.insert(0, str(SRC_DIR / 'src'))
18
19 from nominatim_db.config import Configuration
20 from nominatim_db.db import connection, properties
21 from nominatim_db.db.sql_preprocessor import SQLPreprocessor
22 import nominatim_db.tokenizer.factory
23
24 import dummy_tokenizer
25 from cursor import CursorForTesting
26
27
28 def _with_srid(geom, default=None):
29     if geom is None:
30         return None if default is None else f"SRID=4326;{default}"
31
32     return f"SRID=4326;{geom}"
33
34
35 @pytest.fixture
36 def src_dir():
37     return SRC_DIR
38
39
40 @pytest.fixture
41 def temp_db(monkeypatch):
42     """ Create an empty database for the test. The database name is also
43         exported into NOMINATIM_DATABASE_DSN.
44     """
45     name = 'test_nominatim_python_unittest'
46
47     with psycopg.connect(dbname='postgres', autocommit=True) as conn:
48         with conn.cursor() as cur:
49             cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
50             cur.execute(pysql.SQL('CREATE DATABASE') + pysql.Identifier(name))
51
52     monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
53
54     with psycopg.connect(dbname=name) as conn:
55         with conn.cursor() as cur:
56             cur.execute('CREATE EXTENSION hstore')
57
58     yield name
59
60     with psycopg.connect(dbname='postgres', autocommit=True) as conn:
61         with conn.cursor() as cur:
62             cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
63
64
65 @pytest.fixture
66 def dsn(temp_db):
67     return 'dbname=' + temp_db
68
69
70 @pytest.fixture
71 def temp_db_with_extensions(temp_db):
72     with psycopg.connect(dbname=temp_db) as conn:
73         with conn.cursor() as cur:
74             cur.execute('CREATE EXTENSION postgis')
75
76     return temp_db
77
78
79 @pytest.fixture
80 def temp_db_conn(temp_db):
81     """ Connection to the test database.
82     """
83     with connection.connect('', autocommit=True, dbname=temp_db) as conn:
84         connection.register_hstore(conn)
85         yield conn
86
87
88 @pytest.fixture
89 def temp_db_cursor(temp_db):
90     """ Connection and cursor towards the test database. The connection will
91         be in auto-commit mode.
92     """
93     with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
94         connection.register_hstore(conn)
95         with conn.cursor() as cur:
96             yield cur
97
98
99 @pytest.fixture
100 def table_factory(temp_db_conn):
101     """ A fixture that creates new SQL tables, potentially filled with
102         content.
103     """
104     def mk_table(name, definition='id INT', content=None):
105         with psycopg.ClientCursor(temp_db_conn) as cur:
106             cur.execute(pysql.SQL("CREATE TABLE {} ({})")
107                              .format(pysql.Identifier(name),
108                                      pysql.SQL(definition)))
109             if content:
110                 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
111                            .format(pysql.Identifier(name),
112                                    pysql.SQL(',').join([pysql.Placeholder()
113                                                         for _ in range(len(content[0]))]))
114                 cur.executemany(sql, content)
115
116     return mk_table
117
118
119 @pytest.fixture
120 def def_config():
121     cfg = Configuration(None)
122     return cfg
123
124
125 @pytest.fixture
126 def project_env(tmp_path):
127     projdir = tmp_path / 'project'
128     projdir.mkdir()
129     cfg = Configuration(projdir)
130     return cfg
131
132
133 @pytest.fixture
134 def country_table(table_factory):
135     table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
136
137
138 @pytest.fixture
139 def country_row(country_table, temp_db_cursor):
140     def _add(partition=None, country=None, names=None):
141         temp_db_cursor.insert_row('country_name', partition=partition,
142                                   country_code=country, name=names)
143
144     return _add
145
146
147 @pytest.fixture
148 def load_sql(temp_db_conn, country_table):
149     conf = Configuration(None)
150
151     def _run(*filename, **kwargs):
152         for fn in filename:
153             SQLPreprocessor(temp_db_conn, conf).run_sql_file(temp_db_conn, fn, **kwargs)
154
155     return _run
156
157
158 @pytest.fixture
159 def property_table(load_sql, temp_db_conn):
160     load_sql('tables/nominatim_properties.sql')
161
162     class _PropTable:
163         def set(self, name, value):
164             properties.set_property(temp_db_conn, name, value)
165
166         def get(self, name):
167             return properties.get_property(temp_db_conn, name)
168
169     return _PropTable()
170
171
172 @pytest.fixture
173 def status_table(load_sql):
174     """ Create an empty version of the status table and
175         the status logging table.
176     """
177     load_sql('tables/status.sql')
178
179
180 @pytest.fixture
181 def place_table(temp_db_with_extensions, table_factory):
182     """ Create an empty version of the place table.
183     """
184     table_factory('place',
185                   """osm_id int8 NOT NULL,
186                      osm_type char(1) NOT NULL,
187                      class text NOT NULL,
188                      type text NOT NULL,
189                      name hstore,
190                      admin_level smallint,
191                      address hstore,
192                      extratags hstore,
193                      geometry Geometry(Geometry,4326) NOT NULL""")
194
195
196 @pytest.fixture
197 def place_row(place_table, temp_db_cursor):
198     """ A factory for rows in the place table. The table is created as a
199         prerequisite to the fixture.
200     """
201     idseq = itertools.count(1001)
202
203     def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
204                 admin_level=None, address=None, extratags=None, geom='POINT(0 0)'):
205         args = {'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
206                 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
207                 'address': address, 'extratags': extratags,
208                 'geometry': _with_srid(geom)}
209         temp_db_cursor.insert_row('place', **args)
210
211     return _insert
212
213
214 @pytest.fixture
215 def place_postcode_table(temp_db_with_extensions, table_factory):
216     """ Create an empty version of the place_postcode table.
217     """
218     table_factory('place_postcode',
219                   """osm_type char(1) NOT NULL,
220                      osm_id bigint NOT NULL,
221                      postcode text NOT NULL,
222                      country_code text,
223                      centroid Geometry(Point, 4326) NOT NULL,
224                      geometry Geometry(Geometry, 4326)""")
225
226
227 @pytest.fixture
228 def place_postcode_row(place_postcode_table, temp_db_cursor):
229     """ A factory for rows in the place_postcode table. The table is created as a
230         prerequisite to the fixture.
231     """
232     idseq = itertools.count(5001)
233
234     def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
235                 centroid='POINT(12.0 4.0)', geom=None):
236         temp_db_cursor.insert_row('place_postcode',
237                                   osm_type=osm_type, osm_id=osm_id or next(idseq),
238                                   postcode=postcode, country_code=country,
239                                   centroid=_with_srid(centroid),
240                                   geometry=_with_srid(geom))
241
242     return _insert
243
244
245 @pytest.fixture
246 def placex_table(temp_db_with_extensions, temp_db_conn, load_sql, place_table):
247     """ Create an empty version of the placex table.
248     """
249     load_sql('tables/placex.sql')
250     temp_db_conn.execute("CREATE SEQUENCE IF NOT EXISTS seq_place START 1")
251
252
253 @pytest.fixture
254 def placex_row(placex_table, temp_db_cursor):
255     """ A factory for rows in the placex table. The table is created as a
256         prerequisite to the fixture.
257     """
258     idseq = itertools.count(1001)
259
260     def _add(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
261              admin_level=None, address=None, extratags=None, geom='POINT(10 4)',
262              country=None, housenumber=None, rank_search=30, rank_address=30,
263              centroid='POINT(10 4)', indexed_status=0, indexed_date=None):
264         args = {'place_id': pysql.SQL("nextval('seq_place')"),
265                 'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
266                 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
267                 'address': address, 'housenumber': housenumber,
268                 'rank_search': rank_search, 'rank_address': rank_address,
269                 'extratags': extratags,
270                 'centroid': _with_srid(centroid), 'geometry': _with_srid(geom),
271                 'country_code': country,
272                 'indexed_status': indexed_status, 'indexed_date': indexed_date,
273                 'partition': pysql.Literal(0), 'geometry_sector': pysql.Literal(1)}
274         return temp_db_cursor.insert_row('placex', **args)
275
276     return _add
277
278
279 @pytest.fixture
280 def osmline_table(temp_db_with_extensions, load_sql):
281     load_sql('tables/interpolation.sql')
282
283
284 @pytest.fixture
285 def osmline_row(osmline_table, temp_db_cursor):
286     idseq = itertools.count(20001)
287
288     def _add(osm_id=None, geom='LINESTRING(12.0 11.0, 12.003 11.0)'):
289         return temp_db_cursor.insert_row(
290             'location_property_osmline',
291             place_id=pysql.SQL("nextval('seq_place')"),
292             osm_id=osm_id or next(idseq),
293             geometry_sector=pysql.Literal(20),
294             partition=pysql.Literal(0),
295             indexed_status=1,
296             linegeo=_with_srid(geom))
297
298     return _add
299
300
301 @pytest.fixture
302 def postcode_table(temp_db_with_extensions, load_sql):
303     load_sql('tables/postcodes.sql')
304
305
306 @pytest.fixture
307 def postcode_row(postcode_table, temp_db_cursor):
308     def _add(country, postcode, x=34.5, y=-9.33):
309         geom = _with_srid(f"POINT({x} {y})")
310         return temp_db_cursor.insert_row(
311             'location_postcodes',
312             place_id=pysql.SQL("nextval('seq_place')"),
313             indexed_status=pysql.Literal(1),
314             country_code=country, postcode=postcode,
315             centroid=geom,
316             rank_search=pysql.Literal(16),
317             geometry=('ST_Expand(%s::geometry, 0.005)', geom))
318
319     return _add
320
321
322 @pytest.fixture
323 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions, country_row):
324     for part in range(3):
325         country_row(partition=part)
326
327     cfg = Configuration(None)
328     cfg.set_libdirs(sql=tmp_path)
329     return cfg
330
331
332 @pytest.fixture
333 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
334     return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
335
336
337 @pytest.fixture
338 def tokenizer_mock(monkeypatch, property_table):
339     """ Sets up the configuration so that the test dummy tokenizer will be
340         loaded when the tokenizer factory is used. Also returns a factory
341         with which a new dummy tokenizer may be created.
342     """
343     monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
344
345     def _import_dummy(*args, **kwargs):
346         return dummy_tokenizer
347
348     monkeypatch.setattr(nominatim_db.tokenizer.factory,
349                         "_import_tokenizer", _import_dummy)
350     property_table.set('tokenizer', 'dummy')
351
352     def _create_tokenizer():
353         return dummy_tokenizer.DummyTokenizer(None)
354
355     return _create_tokenizer