]> git.openstreetmap.org Git - nominatim.git/blob - test/python/conftest.py
Merge pull request #3979 from jayaddison/issue-2714-prep/extract-rank-zero-specialcasing
[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(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 property_table(table_factory, temp_db_conn):
136     table_factory('nominatim_properties', 'property TEXT, value TEXT')
137
138     return mocks.MockPropertyTable(temp_db_conn)
139
140
141 @pytest.fixture
142 def status_table(table_factory):
143     """ Create an empty version of the status table and
144         the status logging table.
145     """
146     table_factory('import_status',
147                   """lastimportdate timestamp with time zone NOT NULL,
148                      sequence_id integer,
149                      indexed boolean""")
150     table_factory('import_osmosis_log',
151                   """batchend timestamp,
152                      batchseq integer,
153                      batchsize bigint,
154                      starttime timestamp,
155                      endtime timestamp,
156                      event text""")
157
158
159 @pytest.fixture
160 def place_table(temp_db_with_extensions, table_factory):
161     """ Create an empty version of the place table.
162     """
163     table_factory('place',
164                   """osm_id int8 NOT NULL,
165                      osm_type char(1) NOT NULL,
166                      class text NOT NULL,
167                      type text NOT NULL,
168                      name hstore,
169                      admin_level smallint,
170                      address hstore,
171                      extratags hstore,
172                      geometry Geometry(Geometry,4326) NOT NULL""")
173
174
175 @pytest.fixture
176 def place_row(place_table, temp_db_cursor):
177     """ A factory for rows in the place table. The table is created as a
178         prerequisite to the fixture.
179     """
180     idseq = itertools.count(1001)
181     def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
182                 admin_level=None, address=None, extratags=None, geom=None):
183         temp_db_cursor.execute("INSERT INTO place VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
184                                (osm_id or next(idseq), osm_type, cls, typ, names,
185                                 admin_level, address, extratags,
186                                 geom or 'SRID=4326;POINT(0 0)'))
187
188     return _insert
189
190
191 @pytest.fixture
192 def place_postcode_table(temp_db_with_extensions, table_factory):
193     """ Create an empty version of the place_postcode table.
194     """
195     table_factory('place_postcode',
196                   """osm_type char(1) NOT NULL,
197                      osm_id bigint NOT NULL,
198                      postcode text NOT NULL,
199                      country_code text,
200                      centroid Geometry(Point, 4326) NOT NULL,
201                      geometry Geometry(Geometry, 4326)""")
202
203
204 @pytest.fixture
205 def place_postcode_row(place_postcode_table, temp_db_cursor):
206     """ A factory for rows in the place table. The table is created as a
207         prerequisite to the fixture.
208     """
209     idseq = itertools.count(5001)
210     def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
211                 centroid=None, geom=None):
212         temp_db_cursor.execute("INSERT INTO place_postcode VALUES (%s, %s, %s, %s, %s, %s)",
213                                (osm_type, osm_id or next(idseq),
214                                 postcode, country,
215                                 _with_srid(centroid, 'POINT(12.0 4.0)'),
216                                 _with_srid(geom)))
217
218     return _insert
219
220
221 @pytest.fixture
222 def placex_table(temp_db_with_extensions, temp_db_conn):
223     """ Create an empty version of the place table.
224     """
225     return mocks.MockPlacexTable(temp_db_conn)
226
227
228 @pytest.fixture
229 def osmline_table(temp_db_with_extensions, table_factory):
230     table_factory('location_property_osmline',
231                   """place_id BIGINT,
232                      osm_id BIGINT,
233                      parent_place_id BIGINT,
234                      geometry_sector INTEGER,
235                      indexed_date TIMESTAMP,
236                      startnumber INTEGER,
237                      endnumber INTEGER,
238                      partition SMALLINT,
239                      indexed_status SMALLINT,
240                      linegeo GEOMETRY,
241                      interpolationtype TEXT,
242                      address HSTORE,
243                      postcode TEXT,
244                      country_code VARCHAR(2)""")
245
246
247 @pytest.fixture
248 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions):
249     table_factory('country_name', 'partition INT', ((0, ), (1, ), (2, )))
250     cfg = Configuration(None)
251     cfg.set_libdirs(sql=tmp_path)
252     return cfg
253
254
255 @pytest.fixture
256 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
257     return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
258
259
260 @pytest.fixture
261 def tokenizer_mock(monkeypatch, property_table):
262     """ Sets up the configuration so that the test dummy tokenizer will be
263         loaded when the tokenizer factory is used. Also returns a factory
264         with which a new dummy tokenizer may be created.
265     """
266     monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
267
268     def _import_dummy(*args, **kwargs):
269         return dummy_tokenizer
270
271     monkeypatch.setattr(nominatim_db.tokenizer.factory,
272                         "_import_tokenizer", _import_dummy)
273     property_table.set('tokenizer', 'dummy')
274
275     def _create_tokenizer():
276         return dummy_tokenizer.DummyTokenizer(None)
277
278     return _create_tokenizer