]> git.openstreetmap.org Git - nominatim.git/blob - test/python/api/conftest.py
more unit tests for search
[nominatim.git] / test / python / api / conftest.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Helper fixtures for API call tests.
9 """
10 from pathlib import Path
11 import pytest
12 import time
13 import datetime as dt
14
15 import sqlalchemy as sa
16
17 import nominatim.api as napi
18 from nominatim.db.sql_preprocessor import SQLPreprocessor
19 import nominatim.api.logging as loglib
20
21 class APITester:
22
23     def __init__(self):
24         self.api = napi.NominatimAPI(Path('/invalid'))
25         self.async_to_sync(self.api._async_api.setup_database())
26
27
28     def async_to_sync(self, func):
29         """ Run an asynchronous function until completion using the
30             internal loop of the API.
31         """
32         return self.api._loop.run_until_complete(func)
33
34
35     def add_data(self, table, data):
36         """ Insert data into the given table.
37         """
38         sql = getattr(self.api._async_api._tables, table).insert()
39         self.async_to_sync(self.exec_async(sql, data))
40
41
42     def add_placex(self, **kw):
43         name = kw.get('name')
44         if isinstance(name, str):
45             name = {'name': name}
46
47         centroid = kw.get('centroid', (23.0, 34.0))
48         geometry = kw.get('geometry', 'POINT(%f %f)' % centroid)
49
50         self.add_data('placex',
51                      {'place_id': kw.get('place_id', 1000),
52                       'osm_type': kw.get('osm_type', 'W'),
53                       'osm_id': kw.get('osm_id', 4),
54                       'class_': kw.get('class_', 'highway'),
55                       'type': kw.get('type', 'residential'),
56                       'name': name,
57                       'address': kw.get('address'),
58                       'extratags': kw.get('extratags'),
59                       'parent_place_id': kw.get('parent_place_id'),
60                       'linked_place_id': kw.get('linked_place_id'),
61                       'admin_level': kw.get('admin_level', 15),
62                       'country_code': kw.get('country_code'),
63                       'housenumber': kw.get('housenumber'),
64                       'postcode': kw.get('postcode'),
65                       'wikipedia': kw.get('wikipedia'),
66                       'rank_search': kw.get('rank_search', 30),
67                       'rank_address': kw.get('rank_address', 30),
68                       'importance': kw.get('importance'),
69                       'centroid': 'POINT(%f %f)' % centroid,
70                       'indexed_status': kw.get('indexed_status', 0),
71                       'indexed_date': kw.get('indexed_date',
72                                              dt.datetime(2022, 12, 7, 14, 14, 46, 0)),
73                       'geometry': geometry})
74
75
76     def add_address_placex(self, object_id, **kw):
77         self.add_placex(**kw)
78         self.add_data('addressline',
79                       {'place_id': object_id,
80                        'address_place_id': kw.get('place_id', 1000),
81                        'distance': kw.get('distance', 0.0),
82                        'cached_rank_address': kw.get('rank_address', 30),
83                        'fromarea': kw.get('fromarea', False),
84                        'isaddress': kw.get('isaddress', True)})
85
86
87     def add_osmline(self, **kw):
88         self.add_data('osmline',
89                      {'place_id': kw.get('place_id', 10000),
90                       'osm_id': kw.get('osm_id', 4004),
91                       'parent_place_id': kw.get('parent_place_id'),
92                       'indexed_date': kw.get('indexed_date',
93                                              dt.datetime(2022, 12, 7, 14, 14, 46, 0)),
94                       'startnumber': kw.get('startnumber', 2),
95                       'endnumber': kw.get('endnumber', 6),
96                       'step': kw.get('step', 2),
97                       'address': kw.get('address'),
98                       'postcode': kw.get('postcode'),
99                       'country_code': kw.get('country_code'),
100                       'linegeo': kw.get('geometry', 'LINESTRING(1.1 -0.2, 1.09 -0.22)')})
101
102
103     def add_tiger(self, **kw):
104         self.add_data('tiger',
105                      {'place_id': kw.get('place_id', 30000),
106                       'parent_place_id': kw.get('parent_place_id'),
107                       'startnumber': kw.get('startnumber', 2),
108                       'endnumber': kw.get('endnumber', 6),
109                       'step': kw.get('step', 2),
110                       'postcode': kw.get('postcode'),
111                       'linegeo': kw.get('geometry', 'LINESTRING(1.1 -0.2, 1.09 -0.22)')})
112
113
114     def add_postcode(self, **kw):
115         self.add_data('postcode',
116                      {'place_id': kw.get('place_id', 1000),
117                       'parent_place_id': kw.get('parent_place_id'),
118                       'country_code': kw.get('country_code'),
119                       'postcode': kw.get('postcode'),
120                       'rank_search': kw.get('rank_search', 20),
121                       'rank_address': kw.get('rank_address', 22),
122                       'indexed_date': kw.get('indexed_date',
123                                              dt.datetime(2022, 12, 7, 14, 14, 46, 0)),
124                       'geometry': kw.get('geometry', 'POINT(23 34)')})
125
126
127     def add_country(self, country_code, geometry):
128         self.add_data('country_grid',
129                       {'country_code': country_code,
130                        'area': 0.1,
131                        'geometry': geometry})
132
133
134     def add_country_name(self, country_code, names, partition=0):
135         self.add_data('country_name',
136                       {'country_code': country_code,
137                        'name': names,
138                        'partition': partition})
139
140
141     def add_search_name(self, place_id, **kw):
142         centroid = kw.get('centroid', (23.0, 34.0))
143         self.add_data('search_name',
144                       {'place_id': place_id,
145                        'importance': kw.get('importance', 0.00001),
146                        'search_rank': kw.get('search_rank', 30),
147                        'address_rank': kw.get('address_rank', 30),
148                        'name_vector': kw.get('names', []),
149                        'nameaddress_vector': kw.get('address', []),
150                        'country_code': kw.get('country_code', 'xx'),
151                        'centroid': 'POINT(%f %f)' % centroid})
152
153
154     def add_class_type_table(self, cls, typ):
155         self.async_to_sync(
156             self.exec_async(sa.text(f"""CREATE TABLE place_classtype_{cls}_{typ}
157                                          AS (SELECT place_id, centroid FROM placex
158                                              WHERE class = '{cls}' AND type = '{typ}')
159                                      """)))
160
161
162     async def exec_async(self, sql, *args, **kwargs):
163         async with self.api._async_api.begin() as conn:
164             return await conn.execute(sql, *args, **kwargs)
165
166
167     async def create_tables(self):
168         async with self.api._async_api._engine.begin() as conn:
169             await conn.run_sync(self.api._async_api._tables.meta.create_all)
170
171
172 @pytest.fixture
173 def apiobj(temp_db_with_extensions, temp_db_conn, monkeypatch):
174     """ Create an asynchronous SQLAlchemy engine for the test DB.
175     """
176     monkeypatch.setenv('NOMINATIM_USE_US_TIGER_DATA', 'yes')
177     testapi = APITester()
178     testapi.async_to_sync(testapi.create_tables())
179
180     proc = SQLPreprocessor(temp_db_conn, testapi.api.config)
181     proc.run_sql_file(temp_db_conn, 'functions/address_lookup.sql')
182     proc.run_sql_file(temp_db_conn, 'functions/ranking.sql')
183
184     loglib.set_log_output('text')
185     yield testapi
186     print(loglib.get_and_disable())
187
188     testapi.api.close()