]> git.openstreetmap.org Git - nominatim.git/blob - test/bdd/steps/steps_osm_data.py
0082bd081e3056445ea3dd6383fb3db4cea9611c
[nominatim.git] / test / bdd / steps / steps_osm_data.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 import tempfile
8 import random
9 import os
10 from pathlib import Path
11
12 from nominatim.tools.exec_utils import run_osm2pgsql
13
14 from geometry_alias import ALIASES
15
16 def get_osm2pgsql_options(nominatim_env, fname, append):
17     return dict(import_file=fname,
18                 osm2pgsql=str(nominatim_env.build_dir / 'osm2pgsql' / 'osm2pgsql'),
19                 osm2pgsql_cache=50,
20                 osm2pgsql_style=str(nominatim_env.get_test_config().get_import_style_file()),
21                 osm2pgsql_style_path=nominatim_env.get_test_config().config_dir,
22                 threads=1,
23                 dsn=nominatim_env.get_libpq_dsn(),
24                 flatnode_file='',
25                 tablespaces=dict(slim_data='', slim_index='',
26                                  main_data='', main_index=''),
27                 append=append
28                )
29
30
31 def write_opl_file(opl, grid):
32     """ Create a temporary OSM file from OPL and return the file name. It is
33         the responsibility of the caller to delete the file again.
34
35         Node with missing coordinates, can retrieve their coordinates from
36         a supplied grid. Failing that a random coordinate is assigned.
37     """
38     with tempfile.NamedTemporaryFile(suffix='.opl', delete=False) as fd:
39         for line in opl.splitlines():
40             if line.startswith('n') and line.find(' x') < 0:
41                 coord = grid.grid_node(int(line[1:].split(' ')[0]))
42                 if coord is None:
43                     coord = (random.random() * 360 - 180,
44                              random.random() * 180 - 90)
45                 line += " x%f y%f" % coord
46             fd.write(line.encode('utf-8'))
47             fd.write(b'\n')
48
49         return fd.name
50
51 @given(u'the ([0-9.]+ )?grid(?: with origin (?P<origin>.*))?')
52 def define_node_grid(context, grid_step, origin):
53     """
54     Define a grid of node positions.
55     Use a table to define the grid. The nodes must be integer ids. Optionally
56     you can give the grid distance. The default is 0.00001 degrees.
57     """
58     if grid_step is not None:
59         grid_step = float(grid_step.strip())
60     else:
61         grid_step = 0.00001
62
63     if origin:
64         if ',' in origin:
65             # TODO coordinate
66             coords = origin.split(',')
67             if len(coords) != 2:
68                 raise RuntimeError('Grid origin expects orgin with x,y coordinates.')
69             origin = (float(coords[0]), float(coords[1]))
70         elif origin in ALIASES:
71             origin = ALIASES[origin]
72         else:
73             raise RuntimeError('Grid origin must be either coordinate or alias.')
74     else:
75         origin = (0.0, 0.0)
76
77     context.osm.set_grid([context.table.headings] + [list(h) for h in context.table],
78                          grid_step, origin)
79
80
81 @when(u'loading osm data')
82 def load_osm_file(context):
83     """
84     Load the given data into a freshly created test data using osm2pgsql.
85     No further indexing is done.
86
87     The data is expected as attached text in OPL format.
88     """
89     # create an OSM file and import it
90     fname = write_opl_file(context.text, context.osm)
91     try:
92         run_osm2pgsql(get_osm2pgsql_options(context.nominatim, fname, append=False))
93     finally:
94         os.remove(fname)
95
96     ### reintroduce the triggers/indexes we've lost by having osm2pgsql set up place again
97     cur = context.db.cursor()
98     cur.execute("""CREATE TRIGGER place_before_delete BEFORE DELETE ON place
99                     FOR EACH ROW EXECUTE PROCEDURE place_delete()""")
100     cur.execute("""CREATE TRIGGER place_before_insert BEFORE INSERT ON place
101                    FOR EACH ROW EXECUTE PROCEDURE place_insert()""")
102     cur.execute("""CREATE UNIQUE INDEX idx_place_osm_unique on place using btree(osm_id,osm_type,class,type)""")
103     context.db.commit()
104
105
106 @when(u'updating osm data')
107 def update_from_osm_file(context):
108     """
109     Update a database previously populated with 'loading osm data'.
110     Needs to run indexing on the existing data first to yield the correct result.
111
112     The data is expected as attached text in OPL format.
113     """
114     context.nominatim.copy_from_place(context.db)
115     context.nominatim.run_nominatim('index')
116     context.nominatim.run_nominatim('refresh', '--functions')
117
118     # create an OSM file and import it
119     fname = write_opl_file(context.text, context.osm)
120     try:
121         run_osm2pgsql(get_osm2pgsql_options(context.nominatim, fname, append=True))
122     finally:
123         os.remove(fname)