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