]> git.openstreetmap.org Git - nominatim.git/blob - test/python/tools/test_database_import.py
6d6d75fdcb0f4bee7d476981b77e97e6ebadf7a4
[nominatim.git] / test / python / tools / test_database_import.py
1 """
2 Tests for functions to import a new database.
3 """
4 from pathlib import Path
5 from contextlib import closing
6
7 import pytest
8 import psycopg2
9
10 from nominatim.tools import database_import
11 from nominatim.errors import UsageError
12
13 class TestDatabaseSetup:
14     DBNAME = 'test_nominatim_python_unittest'
15
16     @pytest.fixture(autouse=True)
17     def setup_nonexistant_db(self):
18         conn = psycopg2.connect(database='postgres')
19
20         try:
21             conn.set_isolation_level(0)
22             with conn.cursor() as cur:
23                 cur.execute(f'DROP DATABASE IF EXISTS {self.DBNAME}')
24
25             yield True
26
27             with conn.cursor() as cur:
28                 cur.execute(f'DROP DATABASE IF EXISTS {self.DBNAME}')
29         finally:
30             conn.close()
31
32     @pytest.fixture
33     def cursor(self):
34         conn = psycopg2.connect(database=self.DBNAME)
35
36         try:
37             with conn.cursor() as cur:
38                 yield cur
39         finally:
40             conn.close()
41
42
43     def conn(self):
44         return closing(psycopg2.connect(database=self.DBNAME))
45
46
47     def test_setup_skeleton(self):
48         database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
49
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))')
54
55
56     def test_unsupported_pg_version(self, monkeypatch):
57         monkeypatch.setattr(database_import, 'POSTGRESQL_REQUIRED_VERSION', (100, 4))
58
59         with pytest.raises(UsageError, match='PostgreSQL server is too old.'):
60             database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
61
62
63     def test_create_db_explicit_ro_user(self):
64         database_import.setup_database_skeleton(f'dbname={self.DBNAME}',
65                                                 rouser='postgres')
66
67
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;')
72
73
74     def test_setup_extensions_old_postgis(self, monkeypatch):
75         monkeypatch.setattr(database_import, 'POSTGIS_REQUIRED_VERSION', (50, 50))
76
77         with pytest.raises(UsageError, match='PostGIS is too old.'):
78             database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
79
80
81 def test_setup_skeleton_already_exists(temp_db):
82     with pytest.raises(UsageError):
83         database_import.setup_database_skeleton(f'dbname={temp_db}')
84
85
86 def test_import_osm_data_simple(table_factory, osm2pgsql_options, capfd):
87     table_factory('place', content=((1, ), ))
88
89     database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options)
90     captured = capfd.readouterr()
91
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
98
99
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
103
104     files = [tmp_path / 'file1.osm', tmp_path / 'file2.osm']
105     for f in files:
106         f.write_text('test')
107
108     database_import.import_osm_data(files, osm2pgsql_options)
109     captured = capfd.readouterr()
110
111     assert 'file1.osm' in captured.out
112     assert 'file2.osm' in captured.out
113
114
115 def test_import_osm_data_simple_no_data(table_factory, osm2pgsql_options):
116     table_factory('place')
117
118     with pytest.raises(UsageError, match='No data imported'):
119         database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options)
120
121
122 def test_import_osm_data_simple_ignore_no_data(table_factory, osm2pgsql_options):
123     table_factory('place')
124
125     database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options,
126                                     ignore_errors=True)
127
128
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')
132
133     flatfile = tmp_path / 'flatfile'
134     flatfile.write_text('touch')
135
136     osm2pgsql_options['flatnode_file'] = str(flatfile.resolve())
137
138     database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options, drop=True)
139
140     assert not flatfile.exists()
141     assert not temp_db_conn.table_exists('planet_osm_nodes')
142
143
144 def test_import_osm_data_default_cache(table_factory, osm2pgsql_options, capfd):
145     table_factory('place', content=((1, ), ))
146
147     osm2pgsql_options['osm2pgsql_cache'] = 0
148
149     database_import.import_osm_data(Path(__file__), osm2pgsql_options)
150     captured = capfd.readouterr()
151
152     assert f'--cache {osm2pgsql_options["osm2pgsql_cache"]}' in captured.out
153
154
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']
161     if with_search:
162         tables.append('search_name')
163
164     for table in tables:
165         table_factory(table, content=((1, ), (2, ), (3, )))
166         assert temp_db_cursor.table_rows(table) == 3
167
168     database_import.truncate_data_tables(temp_db_conn)
169
170     for table in tables:
171         assert temp_db_cursor.table_rows(table) == 0
172
173
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
180                                """)
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)')
185
186     database_import.load_data(dsn, threads)
187
188     assert temp_db_cursor.table_rows('placex') == 30
189     assert temp_db_cursor.table_rows('location_property_osmline') == 1
190
191
192 class TestSetupSQL:
193
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()
198
199         self.config = def_config
200
201
202     def write_sql(self, fname, content):
203         (self.config.lib_dir.sql / fname).write_text(content)
204
205
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""")
211
212         database_import.create_tables(temp_db_conn, self.config, reverse)
213
214         temp_db_cursor.scalar('SELECT test()') == reverse
215
216
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""")
221
222         database_import.create_table_triggers(temp_db_conn, self.config)
223
224         temp_db_cursor.scalar('SELECT test()') == 'a'
225
226
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""")
231
232         database_import.create_partition_tables(temp_db_conn, self.config)
233
234         temp_db_cursor.scalar('SELECT test()') == 'b'
235
236
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""")
242
243         database_import.create_search_indices(temp_db_conn, self.config, drop)
244
245         temp_db_cursor.scalar('SELECT test()') == drop