4 from pathlib import Path
11 SRC_DIR = Path(__file__) / '..' / '..' / '..'
13 # always test against the source
14 sys.path.insert(0, str(SRC_DIR.resolve()))
16 from nominatim.config import Configuration
17 from nominatim.db import connection
18 from nominatim.db.sql_preprocessor import SQLPreprocessor
19 from nominatim.db import properties
21 import dummy_tokenizer
24 class _TestingCursor(psycopg2.extras.DictCursor):
25 """ Extension to the DictCursor class that provides execution
26 short-cuts that simplify writing assertions.
29 def scalar(self, sql, params=None):
30 """ Execute a query with a single return value and return this value.
31 Raises an assertion when not exactly one row is returned.
33 self.execute(sql, params)
34 assert self.rowcount == 1
35 return self.fetchone()[0]
37 def row_set(self, sql, params=None):
38 """ Execute a query and return the result as a set of tuples.
40 self.execute(sql, params)
42 return set((tuple(row) for row in self))
44 def table_exists(self, table):
45 """ Check that a table with the given name exists in the database.
47 num = self.scalar("""SELECT count(*) FROM pg_tables
48 WHERE tablename = %s""", (table, ))
51 def table_rows(self, table):
52 """ Return the number of rows in the given table.
54 return self.scalar('SELECT count(*) FROM ' + table)
58 def temp_db(monkeypatch):
59 """ Create an empty database for the test. The database name is also
60 exported into NOMINATIM_DATABASE_DSN.
62 name = 'test_nominatim_python_unittest'
63 conn = psycopg2.connect(database='postgres')
65 conn.set_isolation_level(0)
66 with conn.cursor() as cur:
67 cur.execute('DROP DATABASE IF EXISTS {}'.format(name))
68 cur.execute('CREATE DATABASE {}'.format(name))
72 monkeypatch.setenv('NOMINATIM_DATABASE_DSN' , 'dbname=' + name)
76 conn = psycopg2.connect(database='postgres')
78 conn.set_isolation_level(0)
79 with conn.cursor() as cur:
80 cur.execute('DROP DATABASE IF EXISTS {}'.format(name))
87 return 'dbname=' + temp_db
91 def temp_db_with_extensions(temp_db):
92 conn = psycopg2.connect(database=temp_db)
93 with conn.cursor() as cur:
94 cur.execute('CREATE EXTENSION hstore; CREATE EXTENSION postgis;')
101 def temp_db_conn(temp_db):
102 """ Connection to the test database.
104 with connection.connect('dbname=' + temp_db) as conn:
109 def temp_db_cursor(temp_db):
110 """ Connection and cursor towards the test database. The connection will
111 be in auto-commit mode.
113 conn = psycopg2.connect('dbname=' + temp_db)
114 conn.set_isolation_level(0)
115 with conn.cursor(cursor_factory=_TestingCursor) as cur:
121 def table_factory(temp_db_cursor):
122 def mk_table(name, definition='id INT', content=None):
123 temp_db_cursor.execute('CREATE TABLE {} ({})'.format(name, definition))
124 if content is not None:
125 psycopg2.extras.execute_values(
126 temp_db_cursor, "INSERT INTO {} VALUES %s".format(name), content)
133 cfg = Configuration(None, SRC_DIR.resolve() / 'settings')
134 cfg.set_libdirs(module='.', osm2pgsql='.',
135 php=SRC_DIR / 'lib-php',
136 sql=SRC_DIR / 'lib-sql',
137 data=SRC_DIR / 'data')
142 return SRC_DIR.resolve()
145 def tmp_phplib_dir():
146 with tempfile.TemporaryDirectory() as phpdir:
147 (Path(phpdir) / 'admin').mkdir()
153 def property_table(table_factory):
154 table_factory('nominatim_properties', 'property TEXT, value TEXT')
157 def status_table(temp_db_conn):
158 """ Create an empty version of the status table and
159 the status logging table.
161 with temp_db_conn.cursor() as cur:
162 cur.execute("""CREATE TABLE import_status (
163 lastimportdate timestamp with time zone NOT NULL,
167 cur.execute("""CREATE TABLE import_osmosis_log (
175 temp_db_conn.commit()
179 def place_table(temp_db_with_extensions, temp_db_conn):
180 """ Create an empty version of the place table.
182 with temp_db_conn.cursor() as cur:
183 cur.execute("""CREATE TABLE place (
184 osm_id int8 NOT NULL,
185 osm_type char(1) NOT NULL,
189 admin_level smallint,
192 geometry Geometry(Geometry,4326) NOT NULL)""")
193 temp_db_conn.commit()
197 def place_row(place_table, temp_db_cursor):
198 """ A factory for rows in the place table. The table is created as a
199 prerequisite to the fixture.
201 idseq = itertools.count(1001)
202 def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
203 admin_level=None, address=None, extratags=None, geom=None):
204 temp_db_cursor.execute("INSERT INTO place VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
205 (osm_id or next(idseq), osm_type, cls, typ, names,
206 admin_level, address, extratags,
207 geom or 'SRID=4326;POINT(0 0)'))
212 def placex_table(temp_db_with_extensions, temp_db_conn):
213 """ Create an empty version of the place table.
215 return mocks.MockPlacexTable(temp_db_conn)
219 def osmline_table(temp_db_with_extensions, temp_db_conn):
220 with temp_db_conn.cursor() as cur:
221 cur.execute("""CREATE TABLE location_property_osmline (
224 parent_place_id BIGINT,
225 geometry_sector INTEGER,
226 indexed_date TIMESTAMP,
230 indexed_status SMALLINT,
232 interpolationtype TEXT,
235 country_code VARCHAR(2))""")
236 temp_db_conn.commit()
240 def word_table(temp_db_conn):
241 return mocks.MockWordTable(temp_db_conn)
245 def osm2pgsql_options(temp_db):
246 return dict(osm2pgsql='echo',
248 osm2pgsql_style='style.file',
250 dsn='dbname=' + temp_db,
252 tablespaces=dict(slim_data='', slim_index='',
253 main_data='', main_index=''))
256 def sql_preprocessor(temp_db_conn, tmp_path, monkeypatch, table_factory):
257 table_factory('country_name', 'partition INT', ((0, ), (1, ), (2, )))
258 cfg = Configuration(None, SRC_DIR.resolve() / 'settings')
259 cfg.set_libdirs(module='.', osm2pgsql='.', php=SRC_DIR / 'lib-php',
260 sql=tmp_path, data=SRC_DIR / 'data')
262 return SQLPreprocessor(temp_db_conn, cfg)
266 def tokenizer_mock(monkeypatch, property_table, temp_db_conn, tmp_path):
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.
271 monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
273 def _import_dummy(module, *args, **kwargs):
274 return dummy_tokenizer
276 monkeypatch.setattr(importlib, "import_module", _import_dummy)
277 properties.set_property(temp_db_conn, 'tokenizer', 'dummy')
279 def _create_tokenizer():
280 return dummy_tokenizer.DummyTokenizer(None, None)
282 return _create_tokenizer