]> git.openstreetmap.org Git - nominatim.git/blob - test/python/test_tools_database_import.py
move setup function to python
[nominatim.git] / test / python / test_tools_database_import.py
1 """
2 Tests for functions to import a new database.
3 """
4 import pytest
5 import psycopg2
6 import sys
7 from pathlib import Path
8
9 from nominatim.tools import database_import
10 from nominatim.errors import UsageError
11
12 @pytest.fixture
13 def nonexistant_db():
14     dbname = 'test_nominatim_python_unittest'
15
16     conn = psycopg2.connect(database='postgres')
17
18     conn.set_isolation_level(0)
19     with conn.cursor() as cur:
20         cur.execute('DROP DATABASE IF EXISTS {}'.format(dbname))
21
22     yield dbname
23
24     with conn.cursor() as cur:
25         cur.execute('DROP DATABASE IF EXISTS {}'.format(dbname))
26
27 @pytest.mark.parametrize("no_partitions", (True, False))
28 def test_setup_skeleton(src_dir, nonexistant_db, no_partitions):
29     database_import.setup_database_skeleton('dbname=' + nonexistant_db,
30                                             src_dir / 'data', no_partitions)
31
32     conn = psycopg2.connect(database=nonexistant_db)
33
34     try:
35         with conn.cursor() as cur:
36             cur.execute("SELECT distinct partition FROM country_name")
37             partitions = set([r[0] for r in list(cur)])
38             if no_partitions:
39                 assert partitions == set([0])
40             else:
41                 assert len(partitions) > 10
42     finally:
43         conn.close()
44
45
46 def test_create_db_success(nonexistant_db):
47     database_import.create_db('dbname=' + nonexistant_db, rouser='www-data')
48
49     conn = psycopg2.connect(database=nonexistant_db)
50     conn.close()
51
52
53 def test_create_db_already_exists(temp_db):
54     with pytest.raises(UsageError):
55         database_import.create_db('dbname=' + temp_db)
56
57
58 def test_create_db_unsupported_version(nonexistant_db, monkeypatch):
59     monkeypatch.setattr(database_import, 'POSTGRESQL_REQUIRED_VERSION', (100, 4))
60
61     with pytest.raises(UsageError, match='PostgreSQL server is too old.'):
62         database_import.create_db('dbname=' + nonexistant_db)
63
64
65 def test_create_db_missing_ro_user(nonexistant_db):
66     with pytest.raises(UsageError, match='Missing read-only user.'):
67         database_import.create_db('dbname=' + nonexistant_db, rouser='sdfwkjkjgdugu2;jgsafkljas;')
68
69
70 def test_setup_extensions(temp_db_conn, temp_db_cursor):
71     database_import.setup_extensions(temp_db_conn)
72
73     temp_db_cursor.execute('CREATE TABLE t (h HSTORE, geom GEOMETRY(Geometry, 4326))')
74
75
76 def test_setup_extensions_old_postgis(temp_db_conn, monkeypatch):
77     monkeypatch.setattr(database_import, 'POSTGIS_REQUIRED_VERSION', (50, 50))
78
79     with pytest.raises(UsageError, match='PostGIS version is too old.'):
80         database_import.setup_extensions(temp_db_conn)
81
82
83 def test_install_module(tmp_path):
84     src_dir = tmp_path / 'source'
85     src_dir.mkdir()
86     (src_dir / 'nominatim.so').write_text('TEST nomiantim.so')
87
88     project_dir = tmp_path / 'project'
89     project_dir.mkdir()
90
91     database_import.install_module(src_dir, project_dir, '')
92
93     outfile = project_dir / 'module' / 'nominatim.so'
94
95     assert outfile.exists()
96     assert outfile.read_text() == 'TEST nomiantim.so'
97     assert outfile.stat().st_mode == 33261
98
99
100 def test_install_module_custom(tmp_path):
101     (tmp_path / 'nominatim.so').write_text('TEST nomiantim.so')
102
103     database_import.install_module(tmp_path, tmp_path, str(tmp_path.resolve()))
104
105     assert not (tmp_path / 'module').exists()
106
107
108 def test_install_module_fail_access(temp_db_conn, tmp_path):
109     (tmp_path / 'nominatim.so').write_text('TEST nomiantim.so')
110
111     with pytest.raises(UsageError, match='.*module cannot be accessed.*'):
112         database_import.install_module(tmp_path, tmp_path, '',
113                                        conn=temp_db_conn)
114
115
116 def test_import_base_data(src_dir, temp_db, temp_db_cursor):
117     temp_db_cursor.execute('CREATE EXTENSION hstore')
118     temp_db_cursor.execute('CREATE EXTENSION postgis')
119     database_import.import_base_data('dbname=' + temp_db, src_dir / 'data')
120
121     assert temp_db_cursor.scalar('SELECT count(*) FROM country_name') > 0
122
123
124 def test_import_base_data_ignore_partitions(src_dir, temp_db, temp_db_cursor):
125     temp_db_cursor.execute('CREATE EXTENSION hstore')
126     temp_db_cursor.execute('CREATE EXTENSION postgis')
127     database_import.import_base_data('dbname=' + temp_db, src_dir / 'data',
128                                      ignore_partitions=True)
129
130     assert temp_db_cursor.scalar('SELECT count(*) FROM country_name') > 0
131     assert temp_db_cursor.scalar('SELECT count(*) FROM country_name WHERE partition != 0') == 0
132
133
134 def test_import_osm_data_simple(temp_db_cursor,osm2pgsql_options):
135     temp_db_cursor.execute('CREATE TABLE place (id INT)')
136     temp_db_cursor.execute('INSERT INTO place values (1)')
137
138     database_import.import_osm_data('file.pdf', osm2pgsql_options)
139
140
141 def test_import_osm_data_simple_no_data(temp_db_cursor,osm2pgsql_options):
142     temp_db_cursor.execute('CREATE TABLE place (id INT)')
143
144     with pytest.raises(UsageError, match='No data.*'):
145         database_import.import_osm_data('file.pdf', osm2pgsql_options)
146
147
148 def test_import_osm_data_drop(temp_db_conn, temp_db_cursor, tmp_path, osm2pgsql_options):
149     temp_db_cursor.execute('CREATE TABLE place (id INT)')
150     temp_db_cursor.execute('CREATE TABLE planet_osm_nodes (id INT)')
151     temp_db_cursor.execute('INSERT INTO place values (1)')
152
153     flatfile = tmp_path / 'flatfile'
154     flatfile.write_text('touch')
155
156     osm2pgsql_options['flatnode_file'] = str(flatfile.resolve())
157
158     database_import.import_osm_data('file.pdf', osm2pgsql_options, drop=True)
159
160     assert not flatfile.exists()
161     assert not temp_db_conn.table_exists('planet_osm_nodes')
162
163
164 def test_import_osm_data_default_cache(temp_db_cursor,osm2pgsql_options):
165     temp_db_cursor.execute('CREATE TABLE place (id INT)')
166     temp_db_cursor.execute('INSERT INTO place values (1)')
167
168     osm2pgsql_options['osm2pgsql_cache'] = 0
169
170     database_import.import_osm_data(Path(__file__), osm2pgsql_options)
171
172
173 def test_truncate_database_tables(temp_db_conn, temp_db_cursor, table_factory):
174     tables = ('word', 'placex', 'place_addressline', 'location_area',
175               'location_area_country', 'location_property',
176               'location_property_tiger', 'location_property_osmline',
177               'location_postcode', 'search_name', 'location_road_23')
178     for table in tables:
179         table_factory(table, content=(1, 2, 3))
180
181     database_import.truncate_data_tables(temp_db_conn, max_word_frequency=23)
182
183     for table in tables:
184         assert temp_db_cursor.table_rows(table) == 0
185
186
187 @pytest.mark.parametrize("threads", (1, 5))
188 def test_load_data(dsn, src_dir, place_row, placex_table, osmline_table, word_table,
189                    temp_db_cursor, threads):
190     for func in ('make_keywords', 'getorcreate_housenumber_id', 'make_standard_name'):
191         temp_db_cursor.execute("""CREATE FUNCTION {} (src TEXT)
192                                   RETURNS TEXT AS $$ SELECT 'a' $$ LANGUAGE SQL
193                                """.format(func))
194     for oid in range(100, 130):
195         place_row(osm_id=oid)
196     place_row(osm_type='W', osm_id=342, cls='place', typ='houses',
197               geom='SRID=4326;LINESTRING(0 0, 10 10)')
198
199     database_import.load_data(dsn, src_dir / 'data', threads)
200
201     assert temp_db_cursor.table_rows('placex') == 30
202     assert temp_db_cursor.table_rows('location_property_osmline') == 1