]> git.openstreetmap.org Git - nominatim.git/blob - test/python/conftest.py
switch table definitions in conftest to use production 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
21 from nominatim_db.db.sql_preprocessor import SQLPreprocessor
22 import nominatim_db.tokenizer.factory
23
24 import dummy_tokenizer
25 import mocks
26 from cursor import CursorForTesting
27
28
29 def _with_srid(geom, default=None):
30     if geom is None:
31         return None if default is None else f"SRID=4326;{default}"
32
33     return f"SRID=4326;{geom}"
34
35
36 @pytest.fixture
37 def src_dir():
38     return SRC_DIR
39
40
41 @pytest.fixture
42 def temp_db(monkeypatch):
43     """ Create an empty database for the test. The database name is also
44         exported into NOMINATIM_DATABASE_DSN.
45     """
46     name = 'test_nominatim_python_unittest'
47
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))
52
53     monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
54
55     with psycopg.connect(dbname=name) as conn:
56         with conn.cursor() as cur:
57             cur.execute('CREATE EXTENSION hstore')
58
59     yield name
60
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))
64
65
66 @pytest.fixture
67 def dsn(temp_db):
68     return 'dbname=' + temp_db
69
70
71 @pytest.fixture
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')
76
77     return temp_db
78
79
80 @pytest.fixture
81 def temp_db_conn(temp_db):
82     """ Connection to the test database.
83     """
84     with connection.connect('', autocommit=True, dbname=temp_db) as conn:
85         connection.register_hstore(conn)
86         yield conn
87
88
89 @pytest.fixture
90 def temp_db_cursor(temp_db):
91     """ Connection and cursor towards the test database. The connection will
92         be in auto-commit mode.
93     """
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:
97             yield cur
98
99
100 @pytest.fixture
101 def table_factory(temp_db_conn):
102     """ A fixture that creates new SQL tables, potentially filled with
103         content.
104     """
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)))
110             if content:
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)
116
117     return mk_table
118
119
120 @pytest.fixture
121 def def_config():
122     cfg = Configuration(None)
123     return cfg
124
125
126 @pytest.fixture
127 def project_env(tmp_path):
128     projdir = tmp_path / 'project'
129     projdir.mkdir()
130     cfg = Configuration(projdir)
131     return cfg
132
133
134 @pytest.fixture
135 def country_table(table_factory):
136     table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
137
138
139 @pytest.fixture
140 def country_row(country_table, temp_db_cursor):
141     def _add(partition=None, country=None, names=None):
142         temp_db_cursor.insert_row('country_name', partition=partition,
143                                   country_code=country, name=names)
144
145     return _add
146
147
148 @pytest.fixture
149 def load_sql(temp_db_conn, country_row):
150     proc = SQLPreprocessor(temp_db_conn, Configuration(None))
151
152     def _run(filename, **kwargs):
153         proc.run_sql_file(temp_db_conn, filename, **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     return mocks.MockPropertyTable(temp_db_conn)
163
164
165 @pytest.fixture
166 def status_table(load_sql):
167     """ Create an empty version of the status table and
168         the status logging table.
169     """
170     load_sql('tables/status.sql')
171
172
173 @pytest.fixture
174 def place_table(temp_db_with_extensions, table_factory):
175     """ Create an empty version of the place table.
176     """
177     table_factory('place',
178                   """osm_id int8 NOT NULL,
179                      osm_type char(1) NOT NULL,
180                      class text NOT NULL,
181                      type text NOT NULL,
182                      name hstore,
183                      admin_level smallint,
184                      address hstore,
185                      extratags hstore,
186                      geometry Geometry(Geometry,4326) NOT NULL""")
187
188
189 @pytest.fixture
190 def place_row(place_table, temp_db_cursor):
191     """ A factory for rows in the place table. The table is created as a
192         prerequisite to the fixture.
193     """
194     idseq = itertools.count(1001)
195
196     def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
197                 admin_level=None, address=None, extratags=None, geom='POINT(0 0)'):
198         args = {'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
199                 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
200                 'address': address, 'extratags': extratags,
201                 'geometry': _with_srid(geom)}
202         temp_db_cursor.insert_row('place', **args)
203
204     return _insert
205
206
207 @pytest.fixture
208 def place_postcode_table(temp_db_with_extensions, table_factory):
209     """ Create an empty version of the place_postcode table.
210     """
211     table_factory('place_postcode',
212                   """osm_type char(1) NOT NULL,
213                      osm_id bigint NOT NULL,
214                      postcode text NOT NULL,
215                      country_code text,
216                      centroid Geometry(Point, 4326) NOT NULL,
217                      geometry Geometry(Geometry, 4326)""")
218
219
220 @pytest.fixture
221 def place_postcode_row(place_postcode_table, temp_db_cursor):
222     """ A factory for rows in the place_postcode table. The table is created as a
223         prerequisite to the fixture.
224     """
225     idseq = itertools.count(5001)
226
227     def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
228                 centroid='POINT(12.0 4.0)', geom=None):
229         temp_db_cursor.insert_row('place_postcode',
230                                   osm_type=osm_type, osm_id=osm_id or next(idseq),
231                                   postcode=postcode, country_code=country,
232                                   centroid=_with_srid(centroid),
233                                   geometry=_with_srid(geom))
234
235     return _insert
236
237
238 @pytest.fixture
239 def placex_table(temp_db_with_extensions, temp_db_conn):
240     """ Create an empty version of the place table.
241     """
242     return mocks.MockPlacexTable(temp_db_conn)
243
244
245 @pytest.fixture
246 def osmline_table(temp_db_with_extensions, load_sql):
247     load_sql('tables/interpolation.sql')
248
249
250 @pytest.fixture
251 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions, country_row):
252     for part in range(3):
253         country_row(partition=part)
254
255     cfg = Configuration(None)
256     cfg.set_libdirs(sql=tmp_path)
257     return cfg
258
259
260 @pytest.fixture
261 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
262     return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
263
264
265 @pytest.fixture
266 def tokenizer_mock(monkeypatch, property_table):
267     """ Sets up the configuration so that the test dummy tokenizer will be
268         loaded when the tokenizer factory is used. Also returns a factory
269         with which a new dummy tokenizer may be created.
270     """
271     monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
272
273     def _import_dummy(*args, **kwargs):
274         return dummy_tokenizer
275
276     monkeypatch.setattr(nominatim_db.tokenizer.factory,
277                         "_import_tokenizer", _import_dummy)
278     property_table.set('tokenizer', 'dummy')
279
280     def _create_tokenizer():
281         return dummy_tokenizer.DummyTokenizer(None)
282
283     return _create_tokenizer