"""Reading the species packs: search by name and place, details, range dots, and the Wikipedia article.""" import itertools from http import HTTPStatus from unittest import mock import pytest from modules.map import lib, species_search from modules.map.species import HIGH_GRID, LOOKUP_GRID, LOW_GRID, cell_center, cell_id from modules.map.species_search import cells_within, fts_query, haversine_km BEND = (44.06, -121.31) PRINEVILLE = (44.30, -120.83) # ~47 km east of Bend. CRATER_LAKE = (42.94, -122.10) # ~140 km from Bend. DENVER = (39.74, -104.99) # In us-central. ASPEN = dict(taxon_id=1, name='Populus tremuloides', common_name='quaking aspen', wiki_title='one', grp=1) GRASS = dict(taxon_id=2, name='Briza maxima', common_name='big quakinggrass', grp=1) DEER = dict(taxon_id=3, name='Odocoileus hemionus', common_name='mule deer', wiki_title='Mule_deer', grp=3) # Its (made up) common name is exactly "aspen". FLEABANE = dict(taxon_id=4, name='Erigeron speciosus', common_name='aspen', grp=1) @pytest.fixture def us_packs(test_directory, make_species_pack): make_species_pack('us-west', [ {**ASPEN, 'points': [BEND, BEND, BEND, CRATER_LAKE]}, {**GRASS, 'points': [PRINEVILLE] * 5}, {**DEER, 'points': [BEND] + [CRATER_LAKE] * 10}, {**FLEABANE, 'points': [PRINEVILLE]}, ]) make_species_pack('us-central', [ {**ASPEN, 'points': [DENVER, DENVER]}, ]) def taxa(results): return [i['taxon_id'] for i in results] # --- Cells ------------------------------------------------------------------------------------------------------------ def test_cells_within(): lat, lon = BEND cells = cells_within(lat, lon, 30) assert cell_id(lat, lon, LOOKUP_GRID) in cells # Every cell has some part within the radius: its center is within the radius plus half its diagonal (~7 km). assert all(haversine_km(lat, lon, *cell_center(i, LOOKUP_GRID)) < 30 + 8 for i in cells) assert cell_id(lat, lon + 0.2, LOOKUP_GRID) in cells # ~16 km east. assert cell_id(lat, lon + 0.6, LOOKUP_GRID) not in cells # ~48 km east. assert cell_id(*PRINEVILLE, LOOKUP_GRID) not in cells assert cell_id(*PRINEVILLE, LOOKUP_GRID) in cells_within(lat, lon, 60) # A tiny radius is still the point's own cell. assert cells_within(lat, lon, 0.001) == [cell_id(lat, lon, LOOKUP_GRID)] def test_cells_within_antimeridian_and_pole(): # Fiji: the radius crosses the antimeridian into the first column. cells = cells_within(-17.0, 179.99, 20) assert cell_id(-17.0, -179.95, LOOKUP_GRID) in cells assert cell_id(-17.0, 179.95, LOOKUP_GRID) in cells # Near the pole every column of the last rows is near. cells = cells_within(89.99, 0, 50) assert cell_id(89.95, 179.95, LOOKUP_GRID) in cells assert cell_id(89.95, -179.95, LOOKUP_GRID) in cells @pytest.mark.parametrize('q,expected', [ ('quaking asp', '"quaking"* "asp"*'), ("O'Brien", '"O"* "Brien"*'), ('"*', None), ('', None), ]) def test_fts_query(q, expected): assert fts_query(q) == expected # --- Search ----------------------------------------------------------------------------------------------------------- def test_search_no_packs(test_directory): assert species_search.search_species(q='aspen') == [] assert species_search.search_species(lat=BEND[0], lon=BEND[1]) == [] def test_search_by_name(us_packs): """Every word is a prefix; without a place the most observed come first. A species in two regions is merged.""" results = species_search.search_species(q='quak') assert taxa(results) == [1, 2] aspen, grass = results assert aspen['obs_count'] == 6 # 4 in us-west + 2 in us-central. assert aspen['regions'] == ['us-central', 'us-west'] assert aspen['bbox'] == [CRATER_LAKE[1], DENVER[0], DENVER[1], BEND[0]] assert aspen['near_count'] is None assert aspen['group'] == 'Plants' assert aspen['common_name'] == 'quaking aspen' assert taxa(species_search.search_species(q='quaking aspen')) == [1] assert taxa(species_search.search_species(q='odocoileus')) == [3] assert taxa(species_search.search_species(q='nothing')) == [] assert taxa(species_search.search_species(q='"*')) == [] def test_search_exact_name_first(us_packs): """A species named exactly what was searched comes first, however rarely it was seen.""" assert taxa(species_search.search_species(q='aspen')) == [4, 1] assert taxa(species_search.search_species(q='Populus tremuloides')) == [1] def test_search_near(us_packs): """Without a name: only species seen within the radius, the most seen nearby first.""" lat, lon = BEND results = species_search.search_species(lat=lat, lon=lon, radius_km=30) assert [(i['taxon_id'], i['near_count']) for i in results] == [(1, 3), (3, 1)] # Near counts are only nearby observations; totals are every region's. assert results[1]['obs_count'] == 11 # Prineville is within 60 km. Equal near counts are ordered by total observations. results = species_search.search_species(lat=lat, lon=lon, radius_km=60) assert [(i['taxon_id'], i['near_count']) for i in results] == [(2, 5), (1, 3), (3, 1), (4, 1)] # Nothing is seen in the ocean. assert species_search.search_species(lat=30.0, lon=-140.0) == [] def test_search_name_and_near(us_packs): """With a name and a place, matching species seen nearby come first; the others are still listed.""" lat, lon = BEND results = species_search.search_species(q='quak', lat=lat, lon=lon, radius_km=30) assert [(i['taxon_id'], i['near_count']) for i in results] == [(1, 3), (2, 0)] def test_search_group_and_limit(us_packs): lat, lon = BEND assert taxa(species_search.search_species(lat=lat, lon=lon, radius_km=60, group=3)) == [3] assert taxa(species_search.search_species(lat=lat, lon=lon, radius_km=60, group=1)) == [2, 1, 4] assert taxa(species_search.search_species(lat=lat, lon=lon, radius_km=60, limit=2)) == [2, 1] # Neither a name nor a place: the most observed. assert taxa(species_search.search_species(limit=2)) == [3, 1] # --- Details and range ------------------------------------------------------------------------------------------------ def test_get_species(us_packs): aspen = species_search.get_species(1) assert aspen['name'] == 'Populus tremuloides' assert aspen['obs_count'] == 6 assert aspen['regions'] == ['us-central', 'us-west'] assert species_search.get_species(999) is None @pytest.mark.parametrize('grid,size', [('low', LOW_GRID), ('high', HIGH_GRID)]) def test_get_species_range(us_packs, grid, size): """Every cell the species was seen in, in every region, each once: sorted, as differences.""" found = species_search.get_species_range(1, grid) assert found['grid'] == size assert found['count'] == 3 cells = list(itertools.accumulate(found['deltas'])) assert cells == sorted(cell_id(*point, size) for point in (BEND, CRATER_LAKE, DENVER)) assert species_search.get_species_range(999, grid) is None # --- Wikipedia -------------------------------------------------------------------------------------------------------- @pytest.mark.asyncio async def test_wikipedia_none(test_session, test_directory, zim_factory): """Without a Wikipedia Zim there is nowhere to read about a species.""" zim_factory('gutenberg_en_all_2026-01.zim') assert await species_search.find_wikipedia_article(test_session, 'one', 'Populus tremuloides') is None @pytest.mark.asyncio async def test_wikipedia_article(test_session, test_directory, zim_factory): """The article is found in the best Wikipedia Zim; a missing article falls back to a search for the name.""" mini = zim_factory('wikipedia_en_all_mini_2026-03.zim') maxi = zim_factory('wikipedia_en_all_maxi_2026-01.zim') old_maxi = zim_factory('wikipedia_en_all_maxi_2025-01.zim') zim_factory('wiktionary_en_all_maxi_2026-01.zim') test_session.commit() assert species_search.wikipedia_zims(test_session) == [maxi, old_maxi, mini] # The test Zim has an article at `one`. article = await species_search.find_wikipedia_article(test_session, 'one', 'Populus tremuloides') assert article == dict(zim_id=maxi.id, path='one', title='One', url=f'/api/zim/{maxi.id}/entry/one') search = dict(zim_id=None, path=None, title=None, url='/search?q=Populus%20tremuloides') assert await species_search.find_wikipedia_article(test_session, 'Populus_tremuloides', 'Populus tremuloides') == search assert await species_search.find_wikipedia_article(test_session, None, 'Populus tremuloides') == search # --- API -------------------------------------------------------------------------------------------------------------- @pytest.mark.asyncio async def test_species_search_api(async_client, us_packs): request, response = await async_client.get('/api/map/species', params={'q': 'quak'}) assert response.status_code == HTTPStatus.OK assert taxa(response.json['species']) == [1, 2] assert response.json['packs'] == 2 assert {'code': 1, 'name': 'Plants'} in response.json['groups'] params = {'lat': BEND[0], 'lon': BEND[1], 'radius_km': 60, 'group': 1, 'limit': 2} request, response = await async_client.get('/api/map/species', params=params) assert [(i['taxon_id'], i['near_count']) for i in response.json['species']] == [(2, 5), (1, 3)] @pytest.mark.asyncio @pytest.mark.parametrize('params', [ {'lat': 40}, {'lat': 100, 'lon': 0}, {'lat': 0, 'lon': 181}, {'lat': 'x', 'lon': 0}, {'radius_km': 0}, {'radius_km': 201}, {'group': 'plants'}, {'limit': 0}, {'limit': 501}, ]) async def test_species_search_api_invalid(async_client, test_directory, params): request, response = await async_client.get('/api/map/species', params=params) assert response.status_code == HTTPStatus.BAD_REQUEST @pytest.mark.asyncio async def test_species_detail_api(async_client, test_session, us_packs, zim_factory): request, response = await async_client.get('/api/map/species/1') assert response.status_code == HTTPStatus.OK assert response.json['common_name'] == 'quaking aspen' assert response.json['wikipedia'] is None zim = zim_factory('wikipedia_en_all_nopic_2026-01.zim') test_session.commit() request, response = await async_client.get('/api/map/species/1') assert response.json['wikipedia']['url'] == f'/api/zim/{zim.id}/entry/one' request, response = await async_client.get('/api/map/species/999') assert response.status_code == HTTPStatus.NOT_FOUND @pytest.mark.asyncio async def test_species_range_api(async_client, us_packs): for grid in ('low', 'high'): request, response = await async_client.get('/api/map/species/1/range', params={'grid': grid}) assert response.status_code == HTTPStatus.OK assert response.json['count'] == 3 request, response = await async_client.get('/api/map/species/1/range', params={'grid': 'medium'}) assert response.status_code == HTTPStatus.BAD_REQUEST request, response = await async_client.get('/api/map/species/999/range') assert response.status_code == HTTPStatus.NOT_FOUND # --- Months and what was seen here ------------------------------------------------------------------------------------- @pytest.fixture def dated_packs(test_directory, make_species_pack): """Aspen seen around Bend in May and October, and in us-central in October; deer at Bend in July.""" make_species_pack('us-west', [ {**ASPEN, 'points': [(*BEND, 5), (*BEND, 5), (*BEND, 10), CRATER_LAKE]}, # Crater Lake is undated. {**DEER, 'points': [(*BEND, 7)]}, {**GRASS, 'points': [(*PRINEVILLE, 4)]}, ]) make_species_pack('us-central', [{**ASPEN, 'points': [(*DENVER, 10)]}]) def test_species_months(dated_packs): """A species' months are summed over every region.""" aspen = species_search.get_species(1) assert aspen['months'] == [0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0] assert species_search.search_species(q='mule')[0]['months'][6] == 1 def test_species_here(dated_packs): """The species seen in the square of a point, the most seen first, with the months seen there.""" here = species_search.species_here(*BEND) assert here['species_count'] == 2 assert [(i['taxon_id'], i['here_count'], i['here_months']) for i in here['species']] == [(1, 3, [5, 10]), (3, 1, [7])] # The square holds the point, and is 0.1° wide. west, south, east, north = here['bbox'] assert west <= BEND[1] <= east and south <= BEND[0] <= north assert (east - west, north - south) == pytest.approx((LOOKUP_GRID, LOOKUP_GRID)) assert [i['taxon_id'] for i in species_search.species_here(*BEND, limit=1)['species']] == [1] # The species asked about is there however few times it was seen, even beyond the limit. deer = species_search.species_here(*BEND, limit=1, taxon_id=DEER['taxon_id'])['taxon'] assert (deer['taxon_id'], deer['here_count'], deer['here_months']) == (DEER['taxon_id'], 1, [7]) assert species_search.species_here(*BEND, taxon_id=GRASS['taxon_id'])['taxon'] is None, 'seen elsewhere only' assert species_search.species_here(30.0, -140.0) == { 'taxon': None, 'bbox': pytest.approx([-140.0, 30.0, -139.9, 30.1]), 'species_count': 0, 'species': []} def test_old_packs_have_no_months(test_directory, make_species_pack): """Packs built before months were kept still work, without months.""" make_species_pack('us-west', [{**ASPEN, 'points': [(*BEND, 5)]}], months=False) assert species_search.get_species(1)['months'] == [0] * 12 assert species_search.search_species(q='aspen')[0]['obs_count'] == 1 here = species_search.species_here(*BEND) assert [(i['taxon_id'], i['here_count'], i['here_months']) for i in here['species']] == [(1, 1, [])] @pytest.mark.asyncio async def test_species_here_api(async_client, dated_packs): request, response = await async_client.get('/api/map/species/here', params={'lat': BEND[0], 'lon': BEND[1], 'taxon_id': DEER['taxon_id']}) assert response.status_code == HTTPStatus.OK assert response.json['taxon']['here_months'] == [7] assert response.json['species'][0]['common_name'] == 'quaking aspen' assert response.json['species'][0]['here_months'] == [5, 10] for params in ({}, {'lat': BEND[0]}, {'lat': 'x', 'lon': 0}, {'lat': 91, 'lon': 0}, {'lat': 0, 'lon': 0, 'limit': 0}): request, response = await async_client.get('/api/map/species/here', params=params) assert response.status_code == HTTPStatus.BAD_REQUEST, params # --- Review fixes -------------------------------------------------------------------------------------------------- def test_only_newest_version_counted(test_directory, make_species_pack): """An older version of a region left beside the newer one is not counted again.""" make_species_pack('us-west', [{**ASPEN, 'points': [BEND] * 3}], version='20261023') make_species_pack('us-west', [{**ASPEN, 'points': [BEND] * 5}], version='20261123') assert [i['version'] for i in lib.get_species_files()] == ['20261123'] aspen = species_search.get_species(1) assert aspen['obs_count'] == 5 assert aspen['regions'] == ['us-west'] assert species_search.search_species(lat=BEND[0], lon=BEND[1])[0]['near_count'] == 5 def test_names_from_any_pack(test_directory, make_species_pack): """A name one region's pack lacks is taken from another's; the newest pack's name wins.""" make_species_pack('us-west', [{**ASPEN, 'common_name': None, 'wiki_title': None, 'points': [BEND]}], version='20261123') make_species_pack('us-central', [{**ASPEN, 'common_name': 'quaking aspen', 'points': [DENVER]}], version='20261023') aspen = species_search.get_species(1) assert (aspen['common_name'], aspen['wiki_title']) == ('quaking aspen', 'one') def test_other_names_searchable(test_directory, make_species_pack): make_species_pack('us-west', [{**ASPEN, 'other_names': 'trembling aspen; popple', 'points': [BEND]}]) found, = species_search.search_species(q='popple') assert found['taxon_id'] == 1 assert found['other_names'] == 'trembling aspen; popple' def test_bbox_across_antimeridian(test_directory, make_species_pack): """A species in packs on both sides of the antimeridian has no bbox, not one the long way around the world.""" make_species_pack('russia-east', [{**DEER, 'points': [(60.0, 179.5)]}]) make_species_pack('us-alaska', [{**DEER, 'points': [(60.0, -179.5)]}]) deer = species_search.get_species(DEER['taxon_id']) assert deer['bbox'] is None assert species_search.get_species_range(DEER['taxon_id'])['count'] == 2 def test_wikipedia_zims_prefer_all(test_session, test_directory, zim_factory): """Within a flavor, all of Wikipedia comes before a newer selection of it.""" top = zim_factory('wikipedia_en_top_maxi_2026-06.zim') everything = zim_factory('wikipedia_en_all_maxi_2026-01.zim') nopic = zim_factory('wikipedia_en_all_nopic_2026-06.zim') test_session.commit() assert species_search.wikipedia_zims(test_session) == [everything, top, nopic] @pytest.mark.asyncio async def test_wikipedia_stops_at_first_article(test_session, test_directory, zim_factory): """Zims are opened one at a time, best first, until one has the article.""" zim_factory('wikipedia_en_all_maxi_2026-01.zim') zim_factory('wikipedia_en_all_mini_2026-01.zim') test_session.commit() with mock.patch('modules.map.species_search.run_libzim_jobs', mock.AsyncMock(return_value=[{'found': 'one', 'title': 'One'}])) as run: article = await species_search.find_wikipedia_article(test_session, 'one', 'Populus tremuloides') assert article['path'] == 'one' run.assert_called_once() assert run.call_args[0][0][0]['path'].endswith('wikipedia_en_all_maxi_2026-01.zim') def test_planet_pack_is_read_alone(test_directory, make_species_pack): """With the planet pack downloaded, the regions' packs (which it holds) are not read too.""" make_species_pack('us-west', [{**ASPEN, 'points': [BEND] * 3}]) make_species_pack('planet', [{**ASPEN, 'points': [BEND] * 3 + [DENVER]}]) aspen = species_search.get_species(1) assert (aspen['obs_count'], aspen['regions']) == (4, ['planet']) assert species_search.search_species(lat=BEND[0], lon=BEND[1])[0]['near_count'] == 3 def test_overlapping_regions_not_counted_twice(test_directory, make_species_pack): """Regions overlap (us-west and mexico both hold southern Arizona): a square both hold is counted once, not twice.""" tucson = (32.22, -110.97) make_species_pack('us-west', [{**DEER, 'points': [tucson] * 4 + [BEND]}]) make_species_pack('mexico', [{**DEER, 'points': [tucson] * 4}]) found, = species_search.search_species(lat=tucson[0], lon=tucson[1]) assert found['near_count'] == 4 here = species_search.species_here(*tucson)['species'][0] assert here['here_count'] == 4 # Elsewhere one pack holds the square: its counts are its own. assert species_search.search_species(lat=BEND[0], lon=BEND[1])[0]['near_count'] == 1