1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2025 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Helper functions to compare expected values.
14 from psycopg import sql as pysql
15 from psycopg.rows import dict_row, tuple_row
16 from .geometry_alias import ALIASES
19 'exactly': lambda exp, act: exp == act,
20 'more than': lambda exp, act: act > exp,
21 'less than': lambda exp, act: act < exp,
26 return json.dumps(obj, sort_keys=True, indent=2)
29 def within_box(value, expect):
30 coord = [float(x) for x in expect.split(',')]
32 if isinstance(value, str):
33 value = value.split(',')
34 value = list(map(float, value))
37 return coord[0] <= value[0] <= coord[2] \
38 and coord[1] <= value[1] <= coord[3]
41 return value[0] >= coord[0] and value[1] <= coord[1] \
42 and value[2] >= coord[2] and value[3] <= coord[3]
44 raise ValueError("Not a coordinate or bbox.")
48 None: lambda val, exp: str(val) == exp,
49 'i': lambda val, exp: str(val).lower() == exp.lower(),
50 'fm': lambda val, exp: re.fullmatch(exp, val) is not None,
51 'dict': lambda val, exp: val is None if exp == '-' else (val == eval('{' + exp + '}')),
55 OSM_TYPE = {'node': 'n', 'way': 'w', 'relation': 'r',
56 'N': 'n', 'W': 'w', 'R': 'r'}
60 """ Returns the given attribute as a string.
62 The key parameter determines how the value is formatted before
63 returning. To refer to sub attributes, use '+' to add more keys
64 (e.g. 'name+ref' will access obj['name']['ref']). A '!' introduces
65 a formatting suffix. If no suffix is given, the value will be
66 converted using the str() function.
70 !:... - use a formatting expression according to Python Mini Format Spec
71 !i - make case-insensitive comparison
72 !fm - consider comparison string a regular expression and match full value
73 !wkt - convert the expected value to a WKT string before comparing
74 !in_box - the expected value is a comma-separated bbox description
77 def __init__(self, obj, key, grid=None):
81 self.key, self.fmt = key.rsplit('!', 1)
86 if self.key == 'object':
87 assert 'osm_id' in obj
88 assert 'osm_type' in obj
89 self.subobj = OSM_TYPE[obj['osm_type']] + str(obj['osm_id'])
93 self.subobj = self.obj
94 for sub in self.key.split('+'):
96 assert sub in self.subobj, \
97 f"Missing attribute {done}. Full object:\n{_pretty(self.obj)}"
98 self.subobj = self.subobj[sub]
100 def __eq__(self, other):
101 if not isinstance(other, str):
102 raise NotImplementedError()
104 # work around bad quoting by pytest-bdd
105 other = other.replace(r'\\', '\\')
107 if self.fmt in COMPARISON_FUNCS:
108 return COMPARISON_FUNCS[self.fmt](self.subobj, other)
110 if self.fmt.startswith(':'):
111 return other == f"{{{self.fmt}}}".format(self.subobj)
113 if self.fmt == 'wkt':
114 return self.compare_wkt(self.subobj, other)
116 raise RuntimeError(f"Unknown format string '{self.fmt}'.")
119 k = self.key.replace('+', '][')
122 return f"result[{k}]({self.subobj})"
124 def compare_wkt(self, value, expected):
125 """ Compare a WKT value against a compact geometry format.
126 The function understands the following formats:
128 country:<country code>
129 Point geometry guaranteed to be in the given country
137 <P> may either be a coordinate of the form '<x> <y>' or a single
138 number. In the latter case it must refer to a point in
139 a previously defined grid.
141 m = re.fullmatch(r'(POINT)\(([0-9. -]*)\)', value) \
142 or re.fullmatch(r'(LINESTRING)\(([0-9,. -]*)\)', value) \
143 or re.fullmatch(r'(POLYGON)\(\(([0-9,. -]*)\)\)', value)
147 converted = [list(map(float, pt.split(' ', 1)))
148 for pt in map(str.strip, m[2].split(','))]
150 if expected.startswith('country:'):
151 ccode = geom[8:].upper()
152 assert ccode in ALIASES, f"Geometry error: unknown country {ccode}"
153 return m[1] == 'POINT' and \
154 all(math.isclose(p1, p2) for p1, p2 in zip(converted[0], ALIASES[ccode]))
156 if ',' not in expected:
157 return m[1] == 'POINT' and \
158 all(math.isclose(p1, p2) for p1, p2 in zip(converted[0], self.get_point(expected)))
160 if '(' not in expected:
161 return m[1] == 'LINESTRING' and \
162 all(math.isclose(p1[0], p2[0]) and math.isclose(p1[1], p2[1]) for p1, p2 in
163 zip(converted, (self.get_point(p) for p in expected.split(','))))
165 if m[1] != 'POLYGON':
168 # Polygon comparison is tricky because the polygons don't necessarily
169 # end at the same point or have the same winding order.
170 # Brute force all possible variants of the expected polygon
171 exp_coords = [self.get_point(p) for p in expected[1:-1].split(',')]
172 if exp_coords[0] != exp_coords[-1]:
173 raise RuntimeError(f"Invalid polygon {expected}. "
174 "First and last point need to be the same")
175 for line in (exp_coords[:-1], exp_coords[-1:0:-1]):
176 for i in range(len(line)):
177 if all(math.isclose(p1[0], p2[0]) and math.isclose(p1[1], p2[1]) for p1, p2 in
178 zip(converted, line[i:] + line[:i])):
183 def get_point(self, pt):
186 return list(map(float, pt.split(' ', 1)))
190 return self.grid.get(pt)
193 def check_table_content(conn, tablename, data, grid=None, exact=False):
194 lines = set(range(1, len(data)))
199 cols.extend(('osm_id', 'osm_type'))
201 name, fmt = col.rsplit('!', 1)
203 cols.append(f"ST_AsText({name}) as {name}")
205 cols.append(name.split('+')[0])
207 cols.append(col.split('+')[0])
209 with conn.cursor(row_factory=dict_row) as cur:
210 cur.execute(pysql.SQL(f"SELECT {','.join(cols)} FROM")
211 + pysql.Identifier(tablename))
215 table_content += '\n' + str(row)
217 for col, value in zip(data[0], data[i]):
218 if ResultAttr(row, col, grid=grid) != value:
224 assert not exact, f"Unexpected row in table {tablename}: {row}"
227 "Rows not found:\n" \
228 + '\n'.join(str(data[i]) for i in lines) \
229 + "\nTable content:\n" \
233 def check_table_has_lines(conn, tablename, osm_type, osm_id, osm_class):
234 sql = pysql.SQL("""SELECT count(*) FROM {}
235 WHERE osm_type = %s and osm_id = %s""").format(pysql.Identifier(tablename))
236 params = [osm_type, int(osm_id)]
238 sql += pysql.SQL(' AND class = %s')
239 params.append(osm_class)
241 with conn.cursor(row_factory=tuple_row) as cur:
242 assert cur.execute(sql, params).fetchone()[0] == 0