]> git.openstreetmap.org Git - nominatim.git/blob - test/python/conftest.py
Merge pull request #4135 from mtmail/update-multiple-regions-documentation
[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
87     return temp_db
88
89
90 @pytest.fixture
91 def temp_db_conn(temp_db):
92     """ Connection to the test database.
93     """
94     with connection.connect('', autocommit=True, dbname=temp_db) as conn:
95         connection.register_hstore(conn)
96         yield conn
97
98
99 @pytest.fixture
100 def temp_db_cursor(temp_db):
101     """ Connection and cursor towards the test database. The connection will
102         be in auto-commit mode.
103     """
104     with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
105         connection.register_hstore(conn)
106         with conn.cursor() as cur:
107             yield cur
108
109
110 @pytest.fixture
111 def table_factory(temp_db_conn):
112     """ A fixture that creates new SQL tables, potentially filled with
113         content.
114     """
115     def mk_table(name, definition='id INT', content=None):
116         with psycopg.ClientCursor(temp_db_conn) as cur:
117             cur.execute(pysql.SQL("CREATE TABLE {} ({})")
118                              .format(pysql.Identifier(name),
119                                      pysql.SQL(definition)))
120             if content:
121                 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
122                            .format(pysql.Identifier(name),
123                                    pysql.SQL(',').join([pysql.Placeholder()
124                                                         for _ in range(len(content[0]))]))
125                 cur.executemany(sql, content)
126
127     return mk_table
128
129
130 @pytest.fixture
131 def def_config():
132     cfg = Configuration(None)
133     return cfg
134
135
136 @pytest.fixture
137 def project_env(tmp_path):
138     projdir = tmp_path / 'project'
139     projdir.mkdir()
140     cfg = Configuration(projdir)
141     return cfg
142
143
144 @pytest.fixture
145 def country_table(table_factory):
146     table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
147
148
149 @pytest.fixture
150 def country_row(country_table, temp_db_cursor):
151     def _add(partition=None, country=None, names=None):
152         temp_db_cursor.insert_row('country_name', partition=partition,
153                                   country_code=country, name=names)
154
155     return _add
156
157
158 @pytest.fixture
159 def load_sql(temp_db_conn, country_table):
160     conf = Configuration(None)
161
162     def _run(*filename, **kwargs):
163         for fn in filename:
164             SQLPreprocessor(temp_db_conn, conf).run_sql_file(temp_db_conn, fn, **kwargs)
165
166     return _run
167
168
169 @pytest.fixture
170 def property_table(load_sql, temp_db_conn):
171     load_sql('tables/nominatim_properties.sql')
172
173     class _PropTable:
174         def set(self, name, value):
175             properties.set_property(temp_db_conn, name, value)
176
177         def get(self, name):
178             return properties.get_property(temp_db_conn, name)
179
180     return _PropTable()
181
182
183 @pytest.fixture
184 def status_table(load_sql):
185     """ Create an empty version of the status table and
186         the status logging table.
187     """
188     load_sql('tables/status.sql')
189
190
191 @pytest.fixture
192 def place_table(temp_db_with_extensions, table_factory):
193     """ Create an empty version of the place table.
194     """
195     table_factory('place',
196                   """osm_id int8 NOT NULL,
197                      osm_type char(1) NOT NULL,
198                      class text NOT NULL,
199                      type text NOT NULL,
200                      name hstore,
201                      admin_level smallint,
202                      address HSTORE,
203                      extratags HSTORE,
204                      geometry GEOMETRY(Geometry,4326) NOT NULL""")
205
206
207 @pytest.fixture
208 def place_row(place_table, temp_db_cursor):
209     """ A factory for rows in the place table. The table is created as a
210         prerequisite to the fixture.
211     """
212     idseq = itertools.count(1001)
213
214     def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
215                 admin_level=None, address=None, extratags=None, geom='POINT(0 0)'):
216         args = {'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
217                 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
218                 'address': address, 'extratags': extratags,
219                 'geometry': _with_srid(geom)}
220         temp_db_cursor.insert_row('place', **args)
221
222     return _insert
223
224
225 @pytest.fixture
226 def place_postcode_table(temp_db_with_extensions, table_factory):
227     """ Create an empty version of the place_postcode table.
228     """
229     table_factory('place_postcode',
230                   """osm_type char(1) NOT NULL,
231                      osm_id bigint NOT NULL,
232                      postcode text NOT NULL,
233                      country_code TEXT,
234                      centroid GEOMETRY(Point, 4326) NOT NULL,
235                      geometry GEOMETRY(Geometry, 4326)""")
236
237
238 @pytest.fixture
239 def place_postcode_row(place_postcode_table, temp_db_cursor):
240     """ A factory for rows in the place_postcode table. The table is created as a
241         prerequisite to the fixture.
242     """
243     idseq = itertools.count(5001)
244
245     def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
246                 centroid='POINT(12.0 4.0)', geom=None):
247         temp_db_cursor.insert_row('place_postcode',
248                                   osm_type=osm_type, osm_id=osm_id or next(idseq),
249                                   postcode=postcode, country_code=country,
250                                   centroid=_with_srid(centroid),
251                                   geometry=_with_srid(geom))
252
253     return _insert
254
255
256 @pytest.fixture
257 def place_interpolation_table(temp_db_with_extensions, table_factory):
258     """ Create an empty version of the place_interpolation table.
259     """
260     table_factory('place_interpolation',
261                   """osm_id bigint NOT NULL,
262                      type TEXT,
263                      address HSTORE,
264                      nodes BIGINT[],
265                      geometry GEOMETRY(Geometry, 4326)""")
266
267
268 @pytest.fixture
269 def place_interpolation_row(place_interpolation_table, temp_db_cursor):
270     """ A factory for rows in the place_interpolation table. The table is created as a
271         prerequisite to the fixture.
272     """
273     idseq = itertools.count(30001)
274
275     def _insert(osm_id=None, typ='odd', address=None,
276                 nodes=None, geom='LINESTRING(0.1 0.21, 0.1 0.2)'):
277         params = {'osm_id': osm_id or next(idseq),
278                   'type': typ, 'address': address, 'nodes': nodes,
279                   'geometry': _with_srid(geom)}
280         temp_db_cursor.insert_row('place_interpolation', **params)
281
282     return _insert
283
284
285 @pytest.fixture
286 def placex_table(temp_db_with_extensions, temp_db_conn, load_sql, place_table):
287     """ Create an empty version of the placex table.
288     """
289     load_sql('tables/placex.sql')
290     temp_db_conn.execute("CREATE SEQUENCE IF NOT EXISTS seq_place START 1")
291
292
293 @pytest.fixture
294 def placex_row(placex_table, temp_db_cursor):
295     """ A factory for rows in the placex table. The table is created as a
296         prerequisite to the fixture.
297     """
298     idseq = itertools.count(1001)
299
300     def _add(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
301              admin_level=None, address=None, extratags=None, geom='POINT(10 4)',
302              country=None, housenumber=None, rank_search=30, rank_address=30,
303              centroid='POINT(10 4)', indexed_status=0, indexed_date=None,
304              importance=0.00001):
305         args = {'place_id': pysql.SQL("nextval('seq_place')"),
306                 'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
307                 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
308                 'address': address, 'housenumber': housenumber,
309                 'rank_search': rank_search, 'rank_address': rank_address,
310                 'extratags': extratags, 'importance': importance,
311                 'centroid': _with_srid(centroid), 'geometry': _with_srid(geom),
312                 'country_code': country,
313                 'indexed_status': indexed_status, 'indexed_date': indexed_date,
314                 'partition': pysql.Literal(0), 'geometry_sector': pysql.Literal(1)}
315         return temp_db_cursor.insert_row('placex', **args)
316
317     return _add
318
319
320 @pytest.fixture
321 def osmline_table(temp_db_with_extensions, load_sql):
322     load_sql('tables/interpolation.sql')
323
324
325 @pytest.fixture
326 def osmline_row(osmline_table, temp_db_cursor):
327     idseq = itertools.count(20001)
328
329     def _add(osm_id=None, geom='LINESTRING(12.0 11.0, 12.003 11.0)'):
330         return temp_db_cursor.insert_row(
331             'location_property_osmline',
332             place_id=pysql.SQL("nextval('seq_place')"),
333             osm_id=osm_id or next(idseq),
334             geometry_sector=pysql.Literal(20),
335             partition=pysql.Literal(0),
336             indexed_status=1,
337             linegeo=_with_srid(geom))
338
339     return _add
340
341
342 @pytest.fixture
343 def postcode_table(temp_db_with_extensions, load_sql):
344     load_sql('tables/postcodes.sql')
345
346
347 @pytest.fixture
348 def postcode_row(postcode_table, temp_db_cursor):
349     def _add(country, postcode, x=34.5, y=-9.33, is_area=False):
350         geom = _with_srid(f"POINT({x} {y})")
351         return temp_db_cursor.insert_row(
352             'location_postcodes',
353             place_id=pysql.SQL("nextval('seq_place')"),
354             indexed_status=pysql.Literal(1),
355             country_code=country, postcode=postcode, is_area=is_area,
356             centroid=geom,
357             rank_search=pysql.Literal(16),
358             geometry=('ST_Expand(%s::geometry, 0.005)', geom))
359
360     return _add
361
362
363 @pytest.fixture
364 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions, country_row):
365     for part in range(3):
366         country_row(partition=part)
367
368     cfg = Configuration(None)
369     cfg.set_libdirs(sql=tmp_path)
370     return cfg
371
372
373 @pytest.fixture
374 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
375     return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
376
377
378 @pytest.fixture
379 def tokenizer_mock(monkeypatch, property_table):
380     """ Sets up the configuration so that the test dummy tokenizer will be
381         loaded when the tokenizer factory is used. Also returns a factory
382         with which a new dummy tokenizer may be created.
383     """
384     monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
385
386     def _import_dummy(*args, **kwargs):
387         return dummy_tokenizer
388
389     monkeypatch.setattr(nominatim_db.tokenizer.factory,
390                         "_import_tokenizer", _import_dummy)
391     property_table.set('tokenizer', 'dummy')
392
393     def _create_tokenizer():
394         return dummy_tokenizer.DummyTokenizer(None)
395
396     return _create_tokenizer