2 Tests for functions to import a new database.
4 from pathlib import Path
5 from contextlib import closing
10 from nominatim.tools import database_import
11 from nominatim.errors import UsageError
13 class TestDatabaseSetup:
14 DBNAME = 'test_nominatim_python_unittest'
16 @pytest.fixture(autouse=True)
17 def setup_nonexistant_db(self):
18 conn = psycopg2.connect(database='postgres')
21 conn.set_isolation_level(0)
22 with conn.cursor() as cur:
23 cur.execute(f'DROP DATABASE IF EXISTS {self.DBNAME}')
27 with conn.cursor() as cur:
28 cur.execute(f'DROP DATABASE IF EXISTS {self.DBNAME}')
34 conn = psycopg2.connect(database=self.DBNAME)
37 with conn.cursor() as cur:
44 return closing(psycopg2.connect(database=self.DBNAME))
47 def test_setup_skeleton(self):
48 database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
50 # Check that all extensions are set up.
51 with self.conn() as conn:
52 with conn.cursor() as cur:
53 cur.execute('CREATE TABLE t (h HSTORE, geom GEOMETRY(Geometry, 4326))')
56 def test_unsupported_pg_version(self, monkeypatch):
57 monkeypatch.setattr(database_import, 'POSTGRESQL_REQUIRED_VERSION', (100, 4))
59 with pytest.raises(UsageError, match='PostgreSQL server is too old.'):
60 database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
63 def test_create_db_explicit_ro_user(self):
64 database_import.setup_database_skeleton(f'dbname={self.DBNAME}',
68 def test_create_db_missing_ro_user(self):
69 with pytest.raises(UsageError, match='Missing read-only user.'):
70 database_import.setup_database_skeleton(f'dbname={self.DBNAME}',
71 rouser='sdfwkjkjgdugu2;jgsafkljas;')
74 def test_setup_extensions_old_postgis(self, monkeypatch):
75 monkeypatch.setattr(database_import, 'POSTGIS_REQUIRED_VERSION', (50, 50))
77 with pytest.raises(UsageError, match='PostGIS is too old.'):
78 database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
81 def test_setup_skeleton_already_exists(temp_db):
82 with pytest.raises(UsageError):
83 database_import.setup_database_skeleton(f'dbname={temp_db}')
86 def test_import_osm_data_simple(table_factory, osm2pgsql_options, capfd):
87 table_factory('place', content=((1, ), ))
89 database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options)
90 captured = capfd.readouterr()
92 assert '--create' in captured.out
93 assert '--output gazetteer' in captured.out
94 assert f'--style {osm2pgsql_options["osm2pgsql_style"]}' in captured.out
95 assert f'--number-processes {osm2pgsql_options["threads"]}' in captured.out
96 assert f'--cache {osm2pgsql_options["osm2pgsql_cache"]}' in captured.out
97 assert 'file.pbf' in captured.out
100 def test_import_osm_data_multifile(table_factory, tmp_path, osm2pgsql_options, capfd):
101 table_factory('place', content=((1, ), ))
102 osm2pgsql_options['osm2pgsql_cache'] = 0
104 files = [tmp_path / 'file1.osm', tmp_path / 'file2.osm']
108 database_import.import_osm_data(files, osm2pgsql_options)
109 captured = capfd.readouterr()
111 assert 'file1.osm' in captured.out
112 assert 'file2.osm' in captured.out
115 def test_import_osm_data_simple_no_data(table_factory, osm2pgsql_options):
116 table_factory('place')
118 with pytest.raises(UsageError, match='No data imported'):
119 database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options)
122 def test_import_osm_data_simple_ignore_no_data(table_factory, osm2pgsql_options):
123 table_factory('place')
125 database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options,
129 def test_import_osm_data_drop(table_factory, temp_db_conn, tmp_path, osm2pgsql_options):
130 table_factory('place', content=((1, ), ))
131 table_factory('planet_osm_nodes')
133 flatfile = tmp_path / 'flatfile'
134 flatfile.write_text('touch')
136 osm2pgsql_options['flatnode_file'] = str(flatfile.resolve())
138 database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options, drop=True)
140 assert not flatfile.exists()
141 assert not temp_db_conn.table_exists('planet_osm_nodes')
144 def test_import_osm_data_default_cache(table_factory, osm2pgsql_options, capfd):
145 table_factory('place', content=((1, ), ))
147 osm2pgsql_options['osm2pgsql_cache'] = 0
149 database_import.import_osm_data(Path(__file__), osm2pgsql_options)
150 captured = capfd.readouterr()
152 assert f'--cache {osm2pgsql_options["osm2pgsql_cache"]}' in captured.out
155 @pytest.mark.parametrize("with_search", (True, False))
156 def test_truncate_database_tables(temp_db_conn, temp_db_cursor, table_factory, with_search):
157 tables = ['placex', 'place_addressline', 'location_area',
158 'location_area_country',
159 'location_property_tiger', 'location_property_osmline',
160 'location_postcode', 'location_road_23']
162 tables.append('search_name')
165 table_factory(table, content=((1, ), (2, ), (3, )))
166 assert temp_db_cursor.table_rows(table) == 3
168 database_import.truncate_data_tables(temp_db_conn)
171 assert temp_db_cursor.table_rows(table) == 0
174 @pytest.mark.parametrize("threads", (1, 5))
175 def test_load_data(dsn, place_row, placex_table, osmline_table,
176 word_table, temp_db_cursor, threads):
177 for func in ('precompute_words', 'getorcreate_housenumber_id', 'make_standard_name'):
178 temp_db_cursor.execute(f"""CREATE FUNCTION {func} (src TEXT)
179 RETURNS TEXT AS $$ SELECT 'a'::TEXT $$ LANGUAGE SQL
181 for oid in range(100, 130):
182 place_row(osm_id=oid)
183 place_row(osm_type='W', osm_id=342, cls='place', typ='houses',
184 geom='SRID=4326;LINESTRING(0 0, 10 10)')
186 database_import.load_data(dsn, threads)
188 assert temp_db_cursor.table_rows('placex') == 30
189 assert temp_db_cursor.table_rows('location_property_osmline') == 1
194 @pytest.fixture(autouse=True)
195 def init_env(self, temp_db, tmp_path, def_config, sql_preprocessor_cfg):
196 def_config.lib_dir.sql = tmp_path / 'sql'
197 def_config.lib_dir.sql.mkdir()
199 self.config = def_config
202 def write_sql(self, fname, content):
203 (self.config.lib_dir.sql / fname).write_text(content)
206 @pytest.mark.parametrize("reverse", [True, False])
207 def test_create_tables(self, temp_db_conn, temp_db_cursor, reverse):
208 self.write_sql('tables.sql',
209 """CREATE FUNCTION test() RETURNS bool
210 AS $$ SELECT {{db.reverse_only}} $$ LANGUAGE SQL""")
212 database_import.create_tables(temp_db_conn, self.config, reverse)
214 temp_db_cursor.scalar('SELECT test()') == reverse
217 def test_create_table_triggers(self, temp_db_conn, temp_db_cursor):
218 self.write_sql('table-triggers.sql',
219 """CREATE FUNCTION test() RETURNS TEXT
220 AS $$ SELECT 'a'::text $$ LANGUAGE SQL""")
222 database_import.create_table_triggers(temp_db_conn, self.config)
224 temp_db_cursor.scalar('SELECT test()') == 'a'
227 def test_create_partition_tables(self, temp_db_conn, temp_db_cursor):
228 self.write_sql('partition-tables.src.sql',
229 """CREATE FUNCTION test() RETURNS TEXT
230 AS $$ SELECT 'b'::text $$ LANGUAGE SQL""")
232 database_import.create_partition_tables(temp_db_conn, self.config)
234 temp_db_cursor.scalar('SELECT test()') == 'b'
237 @pytest.mark.parametrize("drop", [True, False])
238 def test_create_search_indices(self, temp_db_conn, temp_db_cursor, drop):
239 self.write_sql('indices.sql',
240 """CREATE FUNCTION test() RETURNS bool
241 AS $$ SELECT {{drop}} $$ LANGUAGE SQL""")
243 database_import.create_search_indices(temp_db_conn, self.config, drop)
245 temp_db_cursor.scalar('SELECT test()') == drop