]> 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) 2025 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('DROP DATABASE IF EXISTS {}'.format(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('CREATE TABLE {} ({})'.format(name, definition))
108             if content:
109                 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
110                            .format(pysql.Identifier(name),
111                                    pysql.SQL(',').join([pysql.Placeholder()
112                                                         for _ in range(len(content[0]))]))
113                 cur.executemany(sql, content)
114
115     return mk_table
116
117
118 @pytest.fixture
119 def def_config():
120     cfg = Configuration(None)
121     return cfg
122
123
124 @pytest.fixture
125 def project_env(tmp_path):
126     projdir = tmp_path / 'project'
127     projdir.mkdir()
128     cfg = Configuration(projdir)
129     return cfg
130
131
132 @pytest.fixture
133 def property_table(table_factory, temp_db_conn):
134     table_factory('nominatim_properties', 'property TEXT, value TEXT')
135
136     return mocks.MockPropertyTable(temp_db_conn)
137
138
139 @pytest.fixture
140 def status_table(table_factory):
141     """ Create an empty version of the status table and
142         the status logging table.
143     """
144     table_factory('import_status',
145                   """lastimportdate timestamp with time zone NOT NULL,
146                      sequence_id integer,
147                      indexed boolean""")
148     table_factory('import_osmosis_log',
149                   """batchend timestamp,
150                      batchseq integer,
151                      batchsize bigint,
152                      starttime timestamp,
153                      endtime timestamp,
154                      event text""")
155
156
157 @pytest.fixture
158 def place_table(temp_db_with_extensions, table_factory):
159     """ Create an empty version of the place table.
160     """
161     table_factory('place',
162                   """osm_id int8 NOT NULL,
163                      osm_type char(1) NOT NULL,
164                      class text NOT NULL,
165                      type text NOT NULL,
166                      name hstore,
167                      admin_level smallint,
168                      address hstore,
169                      extratags hstore,
170                      geometry Geometry(Geometry,4326) NOT NULL""")
171
172
173 @pytest.fixture
174 def place_row(place_table, temp_db_cursor):
175     """ A factory for rows in the place table. The table is created as a
176         prerequisite to the fixture.
177     """
178     idseq = itertools.count(1001)
179     def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
180                 admin_level=None, address=None, extratags=None, geom=None):
181         temp_db_cursor.execute("INSERT INTO place VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
182                                (osm_id or next(idseq), osm_type, cls, typ, names,
183                                 admin_level, address, extratags,
184                                 geom or 'SRID=4326;POINT(0 0)'))
185
186     return _insert
187
188
189 @pytest.fixture
190 def place_postcode_table(temp_db_with_extensions, table_factory):
191     """ Create an empty version of the place_postcode table.
192     """
193     table_factory('place_postcode',
194                   """osm_type char(1) NOT NULL,
195                      osm_id bigint NOT NULL,
196                      postcode text NOT NULL,
197                      country_code text,
198                      centroid Geometry(Point, 4326) NOT NULL,
199                      geometry Geometry(Geometry, 4326)""")
200
201
202 @pytest.fixture
203 def place_postcode_row(place_postcode_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(5001)
208     def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
209                 centroid=None, geom=None):
210         temp_db_cursor.execute("INSERT INTO place_postcode VALUES (%s, %s, %s, %s, %s, %s)",
211                                (osm_type, osm_id or next(idseq),
212                                 postcode, country,
213                                 _with_srid(centroid, 'POINT(12.0 4.0)'),
214                                 _with_srid(geom)))
215
216     return _insert
217
218
219 @pytest.fixture
220 def placex_table(temp_db_with_extensions, temp_db_conn):
221     """ Create an empty version of the place table.
222     """
223     return mocks.MockPlacexTable(temp_db_conn)
224
225
226 @pytest.fixture
227 def osmline_table(temp_db_with_extensions, table_factory):
228     table_factory('location_property_osmline',
229                   """place_id BIGINT,
230                      osm_id BIGINT,
231                      parent_place_id BIGINT,
232                      geometry_sector INTEGER,
233                      indexed_date TIMESTAMP,
234                      startnumber INTEGER,
235                      endnumber INTEGER,
236                      partition SMALLINT,
237                      indexed_status SMALLINT,
238                      linegeo GEOMETRY,
239                      interpolationtype TEXT,
240                      address HSTORE,
241                      postcode TEXT,
242                      country_code VARCHAR(2)""")
243
244
245 @pytest.fixture
246 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions):
247     table_factory('country_name', 'partition INT', ((0, ), (1, ), (2, )))
248     cfg = Configuration(None)
249     cfg.set_libdirs(sql=tmp_path)
250     return cfg
251
252
253 @pytest.fixture
254 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
255     return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
256
257
258 @pytest.fixture
259 def tokenizer_mock(monkeypatch, property_table):
260     """ Sets up the configuration so that the test dummy tokenizer will be
261         loaded when the tokenizer factory is used. Also returns a factory
262         with which a new dummy tokenizer may be created.
263     """
264     monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
265
266     def _import_dummy(*args, **kwargs):
267         return dummy_tokenizer
268
269     monkeypatch.setattr(nominatim_db.tokenizer.factory,
270                         "_import_tokenizer", _import_dummy)
271     property_table.set('tokenizer', 'dummy')
272
273     def _create_tokenizer():
274         return dummy_tokenizer.DummyTokenizer(None)
275
276     return _create_tokenizer