]> git.openstreetmap.org Git - nominatim.git/blob - test/python/conftest.py
enable flake for Python tests
[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 @pytest.fixture
30 def src_dir():
31     return SRC_DIR
32
33
34 @pytest.fixture
35 def temp_db(monkeypatch):
36     """ Create an empty database for the test. The database name is also
37         exported into NOMINATIM_DATABASE_DSN.
38     """
39     name = 'test_nominatim_python_unittest'
40
41     with psycopg.connect(dbname='postgres', autocommit=True) as conn:
42         with conn.cursor() as cur:
43             cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
44             cur.execute(pysql.SQL('CREATE DATABASE') + pysql.Identifier(name))
45
46     monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
47
48     with psycopg.connect(dbname=name) as conn:
49         with conn.cursor() as cur:
50             cur.execute('CREATE EXTENSION hstore')
51
52     yield name
53
54     with psycopg.connect(dbname='postgres', autocommit=True) as conn:
55         with conn.cursor() as cur:
56             cur.execute('DROP DATABASE IF EXISTS {}'.format(name))
57
58
59 @pytest.fixture
60 def dsn(temp_db):
61     return 'dbname=' + temp_db
62
63
64 @pytest.fixture
65 def temp_db_with_extensions(temp_db):
66     with psycopg.connect(dbname=temp_db) as conn:
67         with conn.cursor() as cur:
68             cur.execute('CREATE EXTENSION postgis')
69
70     return temp_db
71
72
73 @pytest.fixture
74 def temp_db_conn(temp_db):
75     """ Connection to the test database.
76     """
77     with connection.connect('', autocommit=True, dbname=temp_db) as conn:
78         connection.register_hstore(conn)
79         yield conn
80
81
82 @pytest.fixture
83 def temp_db_cursor(temp_db):
84     """ Connection and cursor towards the test database. The connection will
85         be in auto-commit mode.
86     """
87     with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
88         connection.register_hstore(conn)
89         with conn.cursor() as cur:
90             yield cur
91
92
93 @pytest.fixture
94 def table_factory(temp_db_conn):
95     """ A fixture that creates new SQL tables, potentially filled with
96         content.
97     """
98     def mk_table(name, definition='id INT', content=None):
99         with psycopg.ClientCursor(temp_db_conn) as cur:
100             cur.execute('CREATE TABLE {} ({})'.format(name, definition))
101             if content:
102                 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
103                            .format(pysql.Identifier(name),
104                                    pysql.SQL(',').join([pysql.Placeholder()
105                                                         for _ in range(len(content[0]))]))
106                 cur.executemany(sql, content)
107
108     return mk_table
109
110
111 @pytest.fixture
112 def def_config():
113     cfg = Configuration(None)
114     cfg.set_libdirs(osm2pgsql=None)
115     return cfg
116
117
118 @pytest.fixture
119 def project_env(tmp_path):
120     projdir = tmp_path / 'project'
121     projdir.mkdir()
122     cfg = Configuration(projdir)
123     cfg.set_libdirs(osm2pgsql=None)
124     return cfg
125
126
127 @pytest.fixture
128 def property_table(table_factory, temp_db_conn):
129     table_factory('nominatim_properties', 'property TEXT, value TEXT')
130
131     return mocks.MockPropertyTable(temp_db_conn)
132
133
134 @pytest.fixture
135 def status_table(table_factory):
136     """ Create an empty version of the status table and
137         the status logging table.
138     """
139     table_factory('import_status',
140                   """lastimportdate timestamp with time zone NOT NULL,
141                      sequence_id integer,
142                      indexed boolean""")
143     table_factory('import_osmosis_log',
144                   """batchend timestamp,
145                      batchseq integer,
146                      batchsize bigint,
147                      starttime timestamp,
148                      endtime timestamp,
149                      event text""")
150
151
152 @pytest.fixture
153 def place_table(temp_db_with_extensions, table_factory):
154     """ Create an empty version of the place table.
155     """
156     table_factory('place',
157                   """osm_id int8 NOT NULL,
158                      osm_type char(1) NOT NULL,
159                      class text NOT NULL,
160                      type text NOT NULL,
161                      name hstore,
162                      admin_level smallint,
163                      address hstore,
164                      extratags hstore,
165                      geometry Geometry(Geometry,4326) NOT NULL""")
166
167
168 @pytest.fixture
169 def place_row(place_table, temp_db_cursor):
170     """ A factory for rows in the place table. The table is created as a
171         prerequisite to the fixture.
172     """
173     idseq = itertools.count(1001)
174     def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
175                 admin_level=None, address=None, extratags=None, geom=None):
176         temp_db_cursor.execute("INSERT INTO place VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
177                                (osm_id or next(idseq), osm_type, cls, typ, names,
178                                 admin_level, address, extratags,
179                                 geom or 'SRID=4326;POINT(0 0)'))
180
181     return _insert
182
183
184 @pytest.fixture
185 def placex_table(temp_db_with_extensions, temp_db_conn):
186     """ Create an empty version of the place table.
187     """
188     return mocks.MockPlacexTable(temp_db_conn)
189
190
191 @pytest.fixture
192 def osmline_table(temp_db_with_extensions, table_factory):
193     table_factory('location_property_osmline',
194                   """place_id BIGINT,
195                      osm_id BIGINT,
196                      parent_place_id BIGINT,
197                      geometry_sector INTEGER,
198                      indexed_date TIMESTAMP,
199                      startnumber INTEGER,
200                      endnumber INTEGER,
201                      partition SMALLINT,
202                      indexed_status SMALLINT,
203                      linegeo GEOMETRY,
204                      interpolationtype TEXT,
205                      address HSTORE,
206                      postcode TEXT,
207                      country_code VARCHAR(2)""")
208
209
210 @pytest.fixture
211 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions):
212     table_factory('country_name', 'partition INT', ((0, ), (1, ), (2, )))
213     cfg = Configuration(None)
214     cfg.set_libdirs(osm2pgsql=None, sql=tmp_path)
215     return cfg
216
217
218 @pytest.fixture
219 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
220     return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
221
222
223 @pytest.fixture
224 def tokenizer_mock(monkeypatch, property_table):
225     """ Sets up the configuration so that the test dummy tokenizer will be
226         loaded when the tokenizer factory is used. Also returns a factory
227         with which a new dummy tokenizer may be created.
228     """
229     monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
230
231     def _import_dummy(*args, **kwargs):
232         return dummy_tokenizer
233
234     monkeypatch.setattr(nominatim_db.tokenizer.factory,
235                         "_import_tokenizer", _import_dummy)
236     property_table.set('tokenizer', 'dummy')
237
238     def _create_tokenizer():
239         return dummy_tokenizer.DummyTokenizer(None, None)
240
241     return _create_tokenizer