]> git.openstreetmap.org Git - nominatim.git/blob - test/python/conftest.py
Update BDD and Python tests for categories
[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
12 if sys.platform == 'win32':
13     asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
14
15 import psycopg
16 from psycopg import sql as pysql
17 import pytest
18
19 # always test against the source
20 SRC_DIR = (Path(__file__) / '..' / '..' / '..').resolve()
21 sys.path.insert(0, str(SRC_DIR / 'src'))
22
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
27
28 import dummy_tokenizer
29 from cursor import CursorForTesting
30
31
32 def _with_srid(geom, default=None):
33     if geom is None:
34         return None if default is None else f"SRID=4326;{default}"
35
36     return f"SRID=4326;{geom}"
37
38
39 @pytest.fixture
40 def src_dir():
41     return SRC_DIR
42
43
44 @pytest.fixture
45 def temp_db(monkeypatch):
46     """ Create an empty database for the test. The database name is also
47         exported into NOMINATIM_DATABASE_DSN.
48     """
49     name = 'test_nominatim_python_unittest'
50
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))
55
56     monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
57
58     with psycopg.connect(dbname=name) as conn:
59         with conn.cursor() as cur:
60             cur.execute('CREATE EXTENSION hstore')
61
62     yield name
63
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))
67
68
69 @pytest.fixture
70 def dsn(temp_db):
71     return 'dbname=' + temp_db
72
73
74 @pytest.fixture
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')
80
81     return temp_db
82
83
84 @pytest.fixture
85 def temp_db_conn(temp_db):
86     """ Connection to the test database.
87     """
88     with connection.connect('', autocommit=True, dbname=temp_db) as conn:
89         connection.register_hstore(conn)
90         yield conn
91
92
93 @pytest.fixture
94 def temp_db_cursor(temp_db):
95     """ Connection and cursor towards the test database. The connection will
96         be in auto-commit mode.
97     """
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:
101             yield cur
102
103
104 @pytest.fixture
105 def table_factory(temp_db_conn):
106     """ A fixture that creates new SQL tables, potentially filled with
107         content.
108     """
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)))
114             if content:
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)
120
121     return mk_table
122
123
124 @pytest.fixture
125 def def_config():
126     cfg = Configuration(None)
127     return cfg
128
129
130 @pytest.fixture
131 def project_env(tmp_path):
132     projdir = tmp_path / 'project'
133     projdir.mkdir()
134     cfg = Configuration(projdir)
135     return cfg
136
137
138 @pytest.fixture
139 def country_table(table_factory):
140     table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
141
142
143 @pytest.fixture
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)
148
149     return _add
150
151
152 @pytest.fixture
153 def load_sql(temp_db_conn, country_table):
154     conf = Configuration(None)
155
156     def _run(*filename, **kwargs):
157         for fn in filename:
158             SQLPreprocessor(temp_db_conn, conf).run_sql_file(temp_db_conn, fn, **kwargs)
159
160     return _run
161
162
163 @pytest.fixture
164 def property_table(load_sql, temp_db_conn):
165     load_sql('tables/nominatim_properties.sql')
166
167     class _PropTable:
168         def set(self, name, value):
169             properties.set_property(temp_db_conn, name, value)
170
171         def get(self, name):
172             return properties.get_property(temp_db_conn, name)
173
174     return _PropTable()
175
176
177 @pytest.fixture
178 def status_table(load_sql):
179     """ Create an empty version of the status table and
180         the status logging table.
181     """
182     load_sql('tables/status.sql')
183
184
185 @pytest.fixture
186 def place_table(temp_db_with_extensions, table_factory):
187     """ Create an empty version of the place table.
188     """
189     table_factory('place',
190                   """osm_id int8 NOT NULL,
191                      osm_type char(1) NOT NULL,
192                      class text NOT NULL,
193                      type text NOT NULL,
194                      name hstore,
195                      admin_level smallint,
196                      address HSTORE,
197                      extratags HSTORE,
198                      categories ltree[],
199                      geometry GEOMETRY(Geometry,4326) NOT NULL""")
200
201
202 @pytest.fixture
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.
206     """
207     idseq = itertools.count(1001)
208
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,
211                 geom='POINT(0 0)'):
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)
218
219     return _insert
220
221
222 @pytest.fixture
223 def place_postcode_table(temp_db_with_extensions, table_factory):
224     """ Create an empty version of the place_postcode table.
225     """
226     table_factory('place_postcode',
227                   """osm_type char(1) NOT NULL,
228                      osm_id bigint NOT NULL,
229                      postcode text NOT NULL,
230                      country_code TEXT,
231                      centroid GEOMETRY(Point, 4326) NOT NULL,
232                      geometry GEOMETRY(Geometry, 4326)""")
233
234
235 @pytest.fixture
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.
239     """
240     idseq = itertools.count(5001)
241
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))
249
250     return _insert
251
252
253 @pytest.fixture
254 def place_interpolation_table(temp_db_with_extensions, table_factory):
255     """ Create an empty version of the place_interpolation table.
256     """
257     table_factory('place_interpolation',
258                   """osm_id bigint NOT NULL,
259                      type TEXT,
260                      address HSTORE,
261                      nodes BIGINT[],
262                      geometry GEOMETRY(Geometry, 4326)""")
263
264
265 @pytest.fixture
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.
269     """
270     idseq = itertools.count(30001)
271
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)
278
279     return _insert
280
281
282 @pytest.fixture
283 def placex_table(temp_db_with_extensions, temp_db_conn, load_sql, place_table):
284     """ Create an empty version of the placex table.
285     """
286     load_sql('tables/placex.sql')
287     temp_db_conn.execute("CREATE SEQUENCE IF NOT EXISTS seq_place START 1")
288
289
290 @pytest.fixture
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.
294     """
295     idseq = itertools.count(1001)
296
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)
313
314     return _add
315
316
317 @pytest.fixture
318 def osmline_table(temp_db_with_extensions, load_sql):
319     load_sql('tables/interpolation.sql')
320
321
322 @pytest.fixture
323 def osmline_row(osmline_table, temp_db_cursor):
324     idseq = itertools.count(20001)
325
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),
333             indexed_status=1,
334             linegeo=_with_srid(geom))
335
336     return _add
337
338
339 @pytest.fixture
340 def postcode_table(temp_db_with_extensions, load_sql):
341     load_sql('tables/postcodes.sql')
342
343
344 @pytest.fixture
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,
353             centroid=geom,
354             rank_search=pysql.Literal(16),
355             geometry=('ST_Expand(%s::geometry, 0.005)', geom))
356
357     return _add
358
359
360 @pytest.fixture
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)
364
365     cfg = Configuration(None)
366     cfg.set_libdirs(sql=tmp_path)
367     return cfg
368
369
370 @pytest.fixture
371 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
372     return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
373
374
375 @pytest.fixture
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.
380     """
381     monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
382
383     def _import_dummy(*args, **kwargs):
384         return dummy_tokenizer
385
386     monkeypatch.setattr(nominatim_db.tokenizer.factory,
387                         "_import_tokenizer", _import_dummy)
388     property_table.set('tokenizer', 'dummy')
389
390     def _create_tokenizer():
391         return dummy_tokenizer.DummyTokenizer(None)
392
393     return _create_tokenizer