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