Merge pull request #2181 from lonvia/port-more-tool-functions-to-python

Port more tool functions to python
This commit is contained in:
Sarah Hoffmann
2021-02-22 16:11:21 +01:00
committed by GitHub
24 changed files with 749 additions and 530 deletions

View File

@@ -8,6 +8,7 @@ import psycopg2.extras
sys.path.insert(1, str((Path(__file__) / '..' / '..' / '..' / '..').resolve()))
from nominatim.config import Configuration
from nominatim.tools import refresh
from steps.utils import run_script
class NominatimEnvironment:
@@ -104,7 +105,8 @@ class NominatimEnvironment:
self.website_dir.cleanup()
self.website_dir = tempfile.TemporaryDirectory()
self.run_setup_script('setup-website')
cfg = Configuration(None, self.src_dir / 'settings', environ=self.test_env)
refresh.setup_website(Path(self.website_dir.name) / 'website', self.src_dir / 'lib-php', cfg)
def db_drop_database(self, name):
@@ -182,6 +184,7 @@ class NominatimEnvironment:
try:
self.run_setup_script('all', osm_file=self.api_test_file)
self.run_setup_script('import-tiger-data')
self.run_setup_script('drop')
phrase_file = str((testdata / 'specialphrases_testdb.sql').resolve())
run_script(['psql', '-d', self.api_test_db, '-f', phrase_file])

View File

@@ -159,31 +159,11 @@ class DBTest extends \PHPUnit\Framework\TestCase
# Tables, Indices
{
$this->assertEmpty($oDB->getListOfTables());
$oDB->exec('CREATE TABLE table1 (id integer, city varchar, country varchar)');
$oDB->exec('CREATE TABLE table2 (id integer, city varchar, country varchar)');
$this->assertEquals(
array('table1', 'table2'),
$oDB->getListOfTables()
);
$this->assertTrue($oDB->deleteTable('table2'));
$this->assertTrue($oDB->deleteTable('table99'));
$this->assertEquals(
array('table1'),
$oDB->getListOfTables()
);
$this->assertTrue($oDB->tableExists('table1'));
$this->assertFalse($oDB->tableExists('table99'));
$this->assertFalse($oDB->tableExists(null));
$this->assertEmpty($oDB->getListOfIndices());
$oDB->exec('CREATE UNIQUE INDEX table1_index ON table1 (id)');
$this->assertEquals(
array('table1_index'),
$oDB->getListOfIndices()
);
$this->assertEmpty($oDB->getListOfIndices('table2'));
}
# select queries

View File

@@ -15,26 +15,6 @@ class LibTest extends \PHPUnit\Framework\TestCase
$this->assertSame("''", addQuotes(''));
}
public function testCreatePointsAroundCenter()
{
// you might say we're creating a circle
$aPoints = createPointsAroundCenter(0, 0, 2);
$this->assertEquals(
101,
count($aPoints)
);
$this->assertEquals(
array(
array('', 0, 2),
array('', 0.12558103905863, 1.9960534568565),
array('', 0.25066646712861, 1.984229402629)
),
array_splice($aPoints, 0, 3)
);
}
public function testParseLatLon()
{
// no coordinates expected
@@ -132,12 +112,4 @@ class LibTest extends \PHPUnit\Framework\TestCase
// start == end
$this->closestHouseNumberEvenOddOther(50, 50, 0.5, array('even' => 50, 'odd' => 50, 'other' => 50));
}
public function testGetSearchRankLabel()
{
$this->assertEquals('unknown', getSearchRankLabel(null));
$this->assertEquals('continent', getSearchRankLabel(0));
$this->assertEquals('continent', getSearchRankLabel(1));
$this->assertEquals('other: 30', getSearchRankLabel(30));
}
}

View File

@@ -36,6 +36,14 @@ class _TestingCursor(psycopg2.extras.DictCursor):
return set((tuple(row) for row in self))
def table_exists(self, table):
""" Check that a table with the given name exists in the database.
"""
num = self.scalar("""SELECT count(*) FROM pg_tables
WHERE tablename = %s""", (table, ))
return num == 1
@pytest.fixture
def temp_db(monkeypatch):
""" Create an empty database for the test. The database name is also

View File

@@ -15,6 +15,9 @@ import nominatim.clicmd.api
import nominatim.clicmd.refresh
import nominatim.clicmd.admin
import nominatim.indexer.indexer
import nominatim.tools.admin
import nominatim.tools.check_database
import nominatim.tools.freeze
import nominatim.tools.refresh
import nominatim.tools.replication
from nominatim.errors import UsageError
@@ -50,6 +53,14 @@ def mock_run_legacy(monkeypatch):
monkeypatch.setattr(nominatim.cli, 'run_legacy_script', mock)
return mock
@pytest.fixture
def mock_func_factory(monkeypatch):
def get_mock(module, func):
mock = MockParamCapture()
monkeypatch.setattr(module, func, mock)
return mock
return get_mock
def test_cli_help(capsys):
""" Running nominatim tool without arguments prints help.
@@ -62,7 +73,6 @@ def test_cli_help(capsys):
@pytest.mark.parametrize("command,script", [
(('import', '--continue', 'load-data'), 'setup'),
(('freeze',), 'setup'),
(('special-phrases',), 'specialphrases'),
(('add-data', '--tiger-data', 'tiger'), 'setup'),
(('add-data', '--file', 'foo.osm'), 'update'),
@@ -75,26 +85,42 @@ def test_legacy_commands_simple(mock_run_legacy, command, script):
assert mock_run_legacy.last_args[0] == script + '.php'
def test_freeze_command(mock_func_factory, temp_db):
mock_drop = mock_func_factory(nominatim.tools.freeze, 'drop_update_tables')
mock_flatnode = mock_func_factory(nominatim.tools.freeze, 'drop_flatnode_file')
assert 0 == call_nominatim('freeze')
assert mock_drop.called == 1
assert mock_flatnode.called == 1
@pytest.mark.parametrize("params", [('--warm', ),
('--warm', '--reverse-only'),
('--warm', '--search-only'),
('--check-database', )])
def test_admin_command_legacy(monkeypatch, params):
mock_run_legacy = MockParamCapture()
monkeypatch.setattr(nominatim.clicmd.admin, 'run_legacy_script', mock_run_legacy)
('--warm', '--search-only')])
def test_admin_command_legacy(mock_func_factory, params):
mock_run_legacy = mock_func_factory(nominatim.clicmd.admin, 'run_legacy_script')
assert 0 == call_nominatim('admin', *params)
assert mock_run_legacy.called == 1
@pytest.mark.parametrize("func, params", [('analyse_indexing', ('--analyse-indexing', ))])
def test_admin_command_tool(temp_db, monkeypatch, func, params):
mock = MockParamCapture()
monkeypatch.setattr(nominatim.tools.admin, func, mock)
def test_admin_command_tool(temp_db, mock_func_factory, func, params):
mock = mock_func_factory(nominatim.tools.admin, func)
assert 0 == call_nominatim('admin', *params)
assert mock.called == 1
def test_admin_command_check_database(mock_func_factory):
mock = mock_func_factory(nominatim.tools.check_database, 'check_database')
assert 0 == call_nominatim('admin', '--check-database')
assert mock.called == 1
@pytest.mark.parametrize("name,oid", [('file', 'foo.osm'), ('diff', 'foo.osc'),
('node', 12), ('way', 8), ('relation', 32)])
def test_add_data_command(mock_run_legacy, name, oid):
@@ -109,12 +135,10 @@ def test_add_data_command(mock_run_legacy, name, oid):
(['--boundaries-only'], 1, 0),
(['--no-boundaries'], 0, 1),
(['--boundaries-only', '--no-boundaries'], 0, 0)])
def test_index_command(monkeypatch, temp_db_cursor, params, do_bnds, do_ranks):
def test_index_command(mock_func_factory, temp_db_cursor, params, do_bnds, do_ranks):
temp_db_cursor.execute("CREATE TABLE import_status (indexed bool)")
bnd_mock = MockParamCapture()
monkeypatch.setattr(nominatim.indexer.indexer.Indexer, 'index_boundaries', bnd_mock)
rank_mock = MockParamCapture()
monkeypatch.setattr(nominatim.indexer.indexer.Indexer, 'index_by_rank', rank_mock)
bnd_mock = mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_boundaries')
rank_mock = mock_func_factory(nominatim.indexer.indexer.Indexer, 'index_by_rank')
assert 0 == call_nominatim('index', *params)
@@ -125,11 +149,9 @@ def test_index_command(monkeypatch, temp_db_cursor, params, do_bnds, do_ranks):
@pytest.mark.parametrize("command,params", [
('wiki-data', ('setup.php', '--import-wikipedia-articles')),
('importance', ('update.php', '--recompute-importance')),
('website', ('setup.php', '--setup-website')),
])
def test_refresh_legacy_command(monkeypatch, temp_db, command, params):
mock_run_legacy = MockParamCapture()
monkeypatch.setattr(nominatim.clicmd.refresh, 'run_legacy_script', mock_run_legacy)
def test_refresh_legacy_command(mock_func_factory, temp_db, command, params):
mock_run_legacy = mock_func_factory(nominatim.clicmd.refresh, 'run_legacy_script')
assert 0 == call_nominatim('refresh', '--' + command)
@@ -142,18 +164,17 @@ def test_refresh_legacy_command(monkeypatch, temp_db, command, params):
('word-counts', 'recompute_word_counts'),
('address-levels', 'load_address_levels_from_file'),
('functions', 'create_functions'),
('website', 'setup_website'),
])
def test_refresh_command(monkeypatch, temp_db, command, func):
func_mock = MockParamCapture()
monkeypatch.setattr(nominatim.tools.refresh, func, func_mock)
def test_refresh_command(mock_func_factory, temp_db, command, func):
func_mock = mock_func_factory(nominatim.tools.refresh, func)
assert 0 == call_nominatim('refresh', '--' + command)
assert func_mock.called == 1
def test_refresh_importance_computed_after_wiki_import(monkeypatch, temp_db):
mock_run_legacy = MockParamCapture()
monkeypatch.setattr(nominatim.clicmd.refresh, 'run_legacy_script', mock_run_legacy)
def test_refresh_importance_computed_after_wiki_import(mock_func_factory, temp_db):
mock_run_legacy = mock_func_factory(nominatim.clicmd.refresh, 'run_legacy_script')
assert 0 == call_nominatim('refresh', '--importance', '--wiki-data')
@@ -165,9 +186,8 @@ def test_refresh_importance_computed_after_wiki_import(monkeypatch, temp_db):
(('--init', '--no-update-functions'), 'init_replication'),
(('--check-for-updates',), 'check_for_updates')
])
def test_replication_command(monkeypatch, temp_db, params, func):
func_mock = MockParamCapture()
monkeypatch.setattr(nominatim.tools.replication, func, func_mock)
def test_replication_command(mock_func_factory, temp_db, params, func):
func_mock = mock_func_factory(nominatim.tools.replication, func)
assert 0 == call_nominatim('replication', *params)
assert func_mock.called == 1
@@ -188,11 +208,10 @@ def test_replication_update_bad_interval_for_geofabrik(monkeypatch, temp_db):
@pytest.mark.parametrize("state", [nominatim.tools.replication.UpdateState.UP_TO_DATE,
nominatim.tools.replication.UpdateState.NO_CHANGES])
def test_replication_update_once_no_index(monkeypatch, temp_db, temp_db_conn,
def test_replication_update_once_no_index(mock_func_factory, temp_db, temp_db_conn,
status_table, state):
status.set_status(temp_db_conn, date=dt.datetime.now(dt.timezone.utc), seq=1)
func_mock = MockParamCapture(retval=state)
monkeypatch.setattr(nominatim.tools.replication, 'update', func_mock)
func_mock = mock_func_factory(nominatim.tools.replication, 'update')
assert 0 == call_nominatim('replication', '--once', '--no-index')
@@ -236,9 +255,8 @@ def test_replication_update_continuous_no_change(monkeypatch, temp_db_conn, stat
assert sleep_mock.last_args[0] == 60
def test_serve_command(monkeypatch):
func = MockParamCapture()
monkeypatch.setattr(nominatim.cli, 'run_php_server', func)
def test_serve_command(mock_func_factory):
func = mock_func_factory(nominatim.cli, 'run_php_server')
call_nominatim('serve')
@@ -254,9 +272,8 @@ def test_serve_command(monkeypatch):
('details', '--place_id', '10001'),
('status',)
])
def test_api_commands_simple(monkeypatch, params):
mock_run_api = MockParamCapture()
monkeypatch.setattr(nominatim.clicmd.api, 'run_api_script', mock_run_api)
def test_api_commands_simple(mock_func_factory, params):
mock_run_api = mock_func_factory(nominatim.clicmd.api, 'run_api_script')
assert 0 == call_nominatim(*params)

View File

@@ -20,12 +20,31 @@ def test_connection_table_exists(db, temp_db_cursor):
assert db.table_exists('foobar') == True
def test_connection_index_exists(db, temp_db_cursor):
assert db.index_exists('some_index') == False
temp_db_cursor.execute('CREATE TABLE foobar (id INT)')
temp_db_cursor.execute('CREATE INDEX some_index ON foobar(id)')
assert db.index_exists('some_index') == True
assert db.index_exists('some_index', table='foobar') == True
assert db.index_exists('some_index', table='bar') == False
def test_connection_server_version_tuple(db):
ver = db.server_version_tuple()
assert isinstance(ver, tuple)
assert len(ver) == 2
assert ver[0] > 8
def test_cursor_scalar(db, temp_db_cursor):
temp_db_cursor.execute('CREATE TABLE dummy (id INT)')
with db.cursor() as cur:
assert cur.scalar('SELECT count(*) FROM dummy') == 0
def test_cursor_scalar_many_rows(db):
with db.cursor() as cur:
with pytest.raises(RuntimeError):

View File

@@ -0,0 +1,76 @@
"""
Tests for database integrity checks.
"""
import pytest
from nominatim.tools import check_database as chkdb
def test_check_database_unknown_db(def_config, monkeypatch):
monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'pgsql:dbname=fjgkhughwgh2423gsags')
assert 1 == chkdb.check_database(def_config)
def test_check_conection_good(temp_db_conn, def_config):
assert chkdb.check_connection(temp_db_conn, def_config) == chkdb.CheckState.OK
def test_check_conection_bad(def_config):
badconn = chkdb._BadConnection('Error')
assert chkdb.check_connection(badconn, def_config) == chkdb.CheckState.FATAL
def test_check_placex_table_good(temp_db_cursor, temp_db_conn, def_config):
temp_db_cursor.execute('CREATE TABLE placex (place_id int)')
assert chkdb.check_placex_table(temp_db_conn, def_config) == chkdb.CheckState.OK
def test_check_placex_table_bad(temp_db_conn, def_config):
assert chkdb.check_placex_table(temp_db_conn, def_config) == chkdb.CheckState.FATAL
def test_check_placex_table_size_good(temp_db_cursor, temp_db_conn, def_config):
temp_db_cursor.execute('CREATE TABLE placex (place_id int)')
temp_db_cursor.execute('INSERT INTO placex VALUES (1), (2)')
assert chkdb.check_placex_size(temp_db_conn, def_config) == chkdb.CheckState.OK
def test_check_placex_table_size_bad(temp_db_cursor, temp_db_conn, def_config):
temp_db_cursor.execute('CREATE TABLE placex (place_id int)')
assert chkdb.check_placex_size(temp_db_conn, def_config) == chkdb.CheckState.FATAL
def test_check_module_bad(temp_db_conn, def_config):
assert chkdb.check_module(temp_db_conn, def_config) == chkdb.CheckState.FAIL
def test_check_indexing_good(temp_db_cursor, temp_db_conn, def_config):
temp_db_cursor.execute('CREATE TABLE placex (place_id int, indexed_status smallint)')
temp_db_cursor.execute('INSERT INTO placex VALUES (1, 0), (2, 0)')
assert chkdb.check_indexing(temp_db_conn, def_config) == chkdb.CheckState.OK
def test_check_indexing_bad(temp_db_cursor, temp_db_conn, def_config):
temp_db_cursor.execute('CREATE TABLE placex (place_id int, indexed_status smallint)')
temp_db_cursor.execute('INSERT INTO placex VALUES (1, 0), (2, 2)')
assert chkdb.check_indexing(temp_db_conn, def_config) == chkdb.CheckState.FAIL
def test_check_database_indexes_bad(temp_db_conn, def_config):
assert chkdb.check_database_indexes(temp_db_conn, def_config) == chkdb.CheckState.FAIL
def test_check_tiger_table_disabled(temp_db_conn, def_config, monkeypatch):
monkeypatch.setenv('NOMINATIM_USE_US_TIGER_DATA' , 'no')
assert chkdb.check_tiger_table(temp_db_conn, def_config) == chkdb.CheckState.NOT_APPLICABLE
def test_check_tiger_table_enabled(temp_db_cursor, temp_db_conn, def_config, monkeypatch):
monkeypatch.setenv('NOMINATIM_USE_US_TIGER_DATA' , 'yes')
assert chkdb.check_tiger_table(temp_db_conn, def_config) == chkdb.CheckState.FAIL
temp_db_cursor.execute('CREATE TABLE location_property_tiger (place_id int)')
assert chkdb.check_tiger_table(temp_db_conn, def_config) == chkdb.CheckState.FAIL
temp_db_cursor.execute('INSERT INTO location_property_tiger VALUES (1), (2)')
assert chkdb.check_tiger_table(temp_db_conn, def_config) == chkdb.CheckState.OK

View File

@@ -0,0 +1,51 @@
"""
Tests for freeze functions (removing unused database parts).
"""
import pytest
from nominatim.tools import freeze
NOMINATIM_RUNTIME_TABLES = [
'country_name', 'country_osm_grid',
'location_postcode', 'location_property_osmline', 'location_property_tiger',
'placex', 'place_adressline',
'search_name',
'word'
]
NOMINATIM_DROP_TABLES = [
'address_levels',
'location_area', 'location_area_country', 'location_area_large_100',
'location_road_1',
'place', 'planet_osm_nodes', 'planet_osm_rels', 'planet_osm_ways',
'search_name_111',
'wikipedia_article', 'wikipedia_redirect'
]
def test_drop_tables(temp_db_conn, temp_db_cursor):
for table in NOMINATIM_RUNTIME_TABLES + NOMINATIM_DROP_TABLES:
temp_db_cursor.execute('CREATE TABLE {} (id int)'.format(table))
freeze.drop_update_tables(temp_db_conn)
for table in NOMINATIM_RUNTIME_TABLES:
assert temp_db_cursor.table_exists(table)
for table in NOMINATIM_DROP_TABLES:
assert not temp_db_cursor.table_exists(table)
def test_drop_flatnode_file_no_file():
freeze.drop_flatnode_file('')
def test_drop_flatnode_file_file_already_gone(tmp_path):
freeze.drop_flatnode_file(str(tmp_path / 'something.store'))
def test_drop_flatnode_file_delte(tmp_path):
flatfile = tmp_path / 'flatnode.store'
flatfile.write_text('Some content')
freeze.drop_flatnode_file(str(flatfile))
assert not flatfile.exists()

View File

@@ -0,0 +1,70 @@
"""
Tests for setting up the website scripts.
"""
from pathlib import Path
import subprocess
import pytest
from nominatim.tools import refresh
@pytest.fixture
def envdir(tmpdir):
(tmpdir / 'php').mkdir()
(tmpdir / 'php' / 'website').mkdir()
return tmpdir
@pytest.fixture
def test_script(envdir):
def _create_file(code):
outfile = envdir / 'php' / 'website' / 'search.php'
outfile.write_text('<?php\n{}\n'.format(code), 'utf-8')
return _create_file
def run_website_script(envdir, config):
refresh.setup_website(envdir, envdir / 'php', config)
proc = subprocess.run(['/usr/bin/env', 'php', '-Cq',
envdir / 'search.php'], check=False)
return proc.returncode
@pytest.mark.parametrize("setting,retval", (('yes', 10), ('no', 20)))
def test_setup_website_check_bool(def_config, monkeypatch, envdir, test_script,
setting, retval):
monkeypatch.setenv('NOMINATIM_CORS_NOACCESSCONTROL', setting)
test_script('exit(CONST_NoAccessControl ? 10 : 20);')
assert run_website_script(envdir, def_config) == retval
@pytest.mark.parametrize("setting", (0, 10, 99067))
def test_setup_website_check_int(def_config, monkeypatch, envdir, test_script, setting):
monkeypatch.setenv('NOMINATIM_LOOKUP_MAX_COUNT', str(setting))
test_script('exit(CONST_Places_Max_ID_count == {} ? 10 : 20);'.format(setting))
assert run_website_script(envdir, def_config) == 10
def test_setup_website_check_empty_str(def_config, monkeypatch, envdir, test_script):
monkeypatch.setenv('NOMINATIM_DEFAULT_LANGUAGE', '')
test_script('exit(CONST_Default_Language === false ? 10 : 20);')
assert run_website_script(envdir, def_config) == 10
def test_setup_website_check_str(def_config, monkeypatch, envdir, test_script):
monkeypatch.setenv('NOMINATIM_DEFAULT_LANGUAGE', 'ffde 2')
test_script('exit(CONST_Default_Language === "ffde 2" ? 10 : 20);')
assert run_website_script(envdir, def_config) == 10