]> git.openstreetmap.org Git - nominatim.git/blob - test/python/conftest.py
Merge remote-tracking branch 'upstream/master'
[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 import asyncio
10 from pathlib import Path
11 from packaging.version import Version
12 import pytest_asyncio
13
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}
19     else:
20         asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
21
22 import psycopg
23 from psycopg import sql as pysql
24 import pytest
25
26 # always test against the source
27 SRC_DIR = (Path(__file__) / '..' / '..' / '..').resolve()
28 sys.path.insert(0, str(SRC_DIR / 'src'))
29
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
34
35 import dummy_tokenizer
36 from cursor import CursorForTesting
37
38
39 def _with_srid(geom, default=None):
40     if geom is None:
41         return None if default is None else f"SRID=4326;{default}"
42
43     return f"SRID=4326;{geom}"
44
45
46 @pytest.fixture
47 def src_dir():
48     return SRC_DIR
49
50
51 @pytest.fixture
52 def temp_db(monkeypatch):
53     """ Create an empty database for the test. The database name is also
54         exported into NOMINATIM_DATABASE_DSN.
55     """
56     name = 'test_nominatim_python_unittest'
57
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))
62
63     monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
64
65     with psycopg.connect(dbname=name) as conn:
66         with conn.cursor() as cur:
67             cur.execute('CREATE EXTENSION hstore')
68
69     yield name
70
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))
74
75
76 @pytest.fixture
77 def dsn(temp_db):
78     return 'dbname=' + temp_db
79
80
81 @pytest.fixture
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')
87
88     return temp_db
89
90
91 @pytest.fixture
92 def temp_db_conn(temp_db):
93     """ Connection to the test database.
94     """
95     with connection.connect('', autocommit=True, dbname=temp_db) as conn:
96         connection.register_hstore(conn)
97         yield conn
98
99
100 @pytest.fixture
101 def temp_db_cursor(temp_db):
102     """ Connection and cursor towards the test database. The connection will
103         be in auto-commit mode.
104     """
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:
108             yield cur
109
110
111 @pytest.fixture
112 def table_factory(temp_db_conn):
113     """ A fixture that creates new SQL tables, potentially filled with
114         content.
115     """
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)))
121             if content:
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)
127
128     return mk_table
129
130
131 @pytest.fixture
132 def def_config():
133     cfg = Configuration(None)
134     return cfg
135
136
137 @pytest.fixture
138 def project_env(tmp_path):
139     projdir = tmp_path / 'project'
140     projdir.mkdir()
141     cfg = Configuration(projdir)
142     return cfg
143
144
145 @pytest.fixture
146 def country_table(table_factory):
147     table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
148
149
150 @pytest.fixture
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)
155
156     return _add
157
158
159 @pytest.fixture
160 def load_sql(temp_db_conn, country_table):
161     conf = Configuration(None)
162
163     def _run(*filename, **kwargs):
164         for fn in filename:
165             SQLPreprocessor(temp_db_conn, conf).run_sql_file(temp_db_conn, fn, **kwargs)
166
167     return _run
168
169
170 @pytest.fixture
171 def property_table(load_sql, temp_db_conn):
172     load_sql('tables/nominatim_properties.sql')
173
174     class _PropTable:
175         def set(self, name, value):
176             properties.set_property(temp_db_conn, name, value)
177
178         def get(self, name):
179             return properties.get_property(temp_db_conn, name)
180
181     return _PropTable()
182
183
184 @pytest.fixture
185 def status_table(load_sql):
186     """ Create an empty version of the status table and
187         the status logging table.
188     """
189     load_sql('tables/status.sql')
190
191
192 @pytest.fixture
193 def place_table(temp_db_with_extensions, table_factory):
194     """ Create an empty version of the place table.
195     """
196     table_factory('place',
197                   """osm_id int8 NOT NULL,
198                      osm_type char(1) NOT NULL,
199                      class text NOT NULL,
200                      type text NOT NULL,
201                      name hstore,
202                      admin_level smallint,
203                      address HSTORE,
204                      extratags HSTORE,
205                      categories ltree[],
206                      geometry GEOMETRY(Geometry,4326) NOT NULL""")
207
208
209 @pytest.fixture
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.
213     """
214     idseq = itertools.count(1001)
215
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,
218                 geom='POINT(0 0)'):
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)
225
226     return _insert
227
228
229 @pytest.fixture
230 def place_postcode_table(temp_db_with_extensions, table_factory):
231     """ Create an empty version of the place_postcode table.
232     """
233     table_factory('place_postcode',
234                   """osm_type char(1) NOT NULL,
235                      osm_id bigint NOT NULL,
236                      postcode text NOT NULL,
237                      country_code TEXT,
238                      centroid GEOMETRY(Point, 4326) NOT NULL,
239                      geometry GEOMETRY(Geometry, 4326)""")
240
241
242 @pytest.fixture
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.
246     """
247     idseq = itertools.count(5001)
248
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))
256
257     return _insert
258
259
260 @pytest.fixture
261 def place_interpolation_table(temp_db_with_extensions, table_factory):
262     """ Create an empty version of the place_interpolation table.
263     """
264     table_factory('place_interpolation',
265                   """osm_id bigint NOT NULL,
266                      type TEXT,
267                      address HSTORE,
268                      nodes BIGINT[],
269                      geometry GEOMETRY(Geometry, 4326)""")
270
271
272 @pytest.fixture
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.
276     """
277     idseq = itertools.count(30001)
278
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)
285
286     return _insert
287
288
289 @pytest.fixture
290 def placex_table(temp_db_with_extensions, temp_db_conn, load_sql, place_table):
291     """ Create an empty version of the placex table.
292     """
293     load_sql('tables/placex.sql')
294     temp_db_conn.execute("CREATE SEQUENCE IF NOT EXISTS seq_place START 1")
295
296
297 @pytest.fixture
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.
301     """
302     idseq = itertools.count(1001)
303
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)
320
321     return _add
322
323
324 @pytest.fixture
325 def osmline_table(temp_db_with_extensions, load_sql):
326     load_sql('tables/interpolation.sql')
327
328
329 @pytest.fixture
330 def osmline_row(osmline_table, temp_db_cursor):
331     idseq = itertools.count(20001)
332
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),
340             indexed_status=1,
341             linegeo=_with_srid(geom))
342
343     return _add
344
345
346 @pytest.fixture
347 def postcode_table(temp_db_with_extensions, load_sql):
348     load_sql('tables/postcodes.sql')
349
350
351 @pytest.fixture
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,
360             centroid=geom,
361             rank_search=pysql.Literal(16),
362             geometry=('ST_Expand(%s::geometry, 0.005)', geom))
363
364     return _add
365
366
367 @pytest.fixture
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)
371
372     cfg = Configuration(None)
373     cfg.set_libdirs(sql=tmp_path)
374     return cfg
375
376
377 @pytest.fixture
378 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
379     return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
380
381
382 @pytest.fixture
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.
387     """
388     monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
389
390     def _import_dummy(*args, **kwargs):
391         return dummy_tokenizer
392
393     monkeypatch.setattr(nominatim_db.tokenizer.factory,
394                         "_import_tokenizer", _import_dummy)
395     property_table.set('tokenizer', 'dummy')
396
397     def _create_tokenizer():
398         return dummy_tokenizer.DummyTokenizer(None)
399
400     return _create_tokenizer