mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 03:46:29 -05:00
* Add iNaturalist species pack build script
Builds one `inat-<region>-<version>.species.db` per map region from the
iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row
links to its English Wikipedia article (via Wikidata) so Kiwix supplies
the details, and carries its range as compressed per-cell dots (0.1° from
all observations, 0.02° from precise ones only). A cell lookup table
answers "what lives near here", and FTS5 searches names. Packs, meta4
files and a signed manifest are written for upload to the CDN.
modules/map/species.py holds the pack format shared with WROLPi.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Download iNaturalist species packs by subscription
A species subscription is one recurring (30 day) `species_catalog` Download
of the signed species manifest, saved in the downloads config like map
subscriptions. Each run creates a `species_pack` Download per subscribed
region, which aria2c checks against the manifest's signed hash before the
pack is moved into map/inat/; only then are the region's older packs
deleted.
The map's Manage tab gets a Species section: subscribe, unsubscribe (the
pack is kept), and delete a downloaded pack. Pack file names are built and
parsed in modules/map/species.py, shared with the build script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Search the downloaded species packs, with their range and Wikipedia article
- GET /api/map/species: search by name (every word a prefix), and/or what
was seen within radius_km of lat/lon. Nearby species come first, most
seen nearby first; an exact name match comes first of all.
- GET /api/map/species/<taxon_id>: details, and the species' article in
the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the
libzim worker's new `find` op, else a search link for its name.
- GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots.
Packs are read directly and read-only; a species in several regions is
merged (counts summed, bbox and range unioned).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Use iNaturalist's common names in the species packs
Wikidata's P1843 holds many English names per species and the one we got
was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for
showy milkweed). The build now reads iNaturalist's taxonomy archive
(VernacularNames-english.csv) and takes each species' first name not tied
to a place ("quaking aspen", not Canada's "trembling aspen"), else its
first name; Wikidata's is only a fallback. In us-west this names 30,642
of 52,015 species, up from 17,805.
--version publishes a rebuild of the same observations under a new
version, and --reuse-split rebuilds from the last build's region work
files instead of reading the observations again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species panel on the map: what lives here, and a species' range as dots
A 🌿 button opens the Species panel (it and nuclear mode share the
panel's place, so one closes the other). It lists the species seen
within 10/30/100 km of the middle of the map, following the map as it
moves, with how often each was seen nearby; it can search by name and
filter by group. Choosing a species draws its range: the 0.1° grid of
every observation below zoom 7, the 0.02° grid of precise ones from it
(or the 0.1° grid at every zoom when there is none), put back after a
style change and erased on Back or close. "Zoom to range" fits its
bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a
search, or where to download Wikipedia).
The panel is at most half the screen tall and clears the map's buttons,
so the range stays in sight on a phone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species tests: neutral Oregon fixtures
Bend, Prineville (~47 km apart) and Crater Lake replace the earlier
fixture points; the cases are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: zoom to a range without its outliers, beside the panel
"Zoom to range" fitted the species' bbox, so a few planted trees far
away (giant sequoias in Seattle and Los Angeles) zoomed the map out to
the whole coast, and the panel covered part of the range. It now fits
the range's dots less the outermost 2% on each side (from 20 dots), and
pads by the panel: beside it on a wide map, above it on a narrow one.
The outlying dots are still drawn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: the Species page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: months seen, a popup on each dot, and review fixes
Months: packs now keep how many observations each species had in each
month, and the months it was seen in each ~11 km square (a bit per
month). The species details show a bar per month; clicking a range dot
opens a popup of that square: how often the species was seen there and
in which months, and the other species seen there, any of which can be
opened (GET /api/map/species/here). Packs without months still work.
Review fixes:
- Common names: the archive's first listed English name, not the first
without a place (which was an alias: "Robin Redbreast", "Wanderer",
"Duck Hawk"); every other English name is kept in `other_names` and
is searchable, and shown as "Also called".
- Only the newest pack of each region is read, so a version left beside
a newer one is not counted twice; a finished download also removes
older versions. A name one pack lacks is taken from another.
- No bbox for a species whose packs are on both sides of the
antimeridian; Zoom to range takes the short way across it, drops at
least one outlier on each side from 20 dots, waits for the dots, and
measures the panel against the map.
- Wikipedia Zims are tried one at a time, best first, all of Wikipedia
before a selection of it.
- A failed search keeps the last list and says so; failed details no
longer suggest downloading Wikipedia, and the range is still drawn.
- Species range dots are left out of PDF exports.
- Unsubscribe (species and map regions) is red again; the Manage table
refreshes until a subscribed pack arrives; a refused Delete fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: less work for the WROLPi per search and range
Measured on a Pi 4 with the us-west pack, the panel's search (species
within 30 km, asked each time the map stops moving) took 146 ms, and a
wide species' fine range 280 ms and 2.7 MB of GeoJSON.
- Search ranks the matching species from bare (taxon, names, counts)
tuples and reads only the species it returns in full: 30 km 87 ms,
100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms.
- The range is sent as its sorted cells, as differences, and the
browser makes the dots: the red-tailed hawk's fine range 34 ms and
95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB.
A dot's popup asks for the species clicked, and always shows how often
and in which months it was seen in that square, not only when it is
among the most seen there. The popup is drawn over the Species panel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: a planet pack, every region in one file
`--planet` merges every region's pack into `inat-planet-<version>`
(counts and months summed, ranges, bboxes and lookup cells joined, the
first name a pack has), and adds it to the manifest; `--merge-only`
makes it from the region packs of a finished build. An observation
exactly on a shared region edge is in both regions' packs, so the
planet counts it twice; that is rare enough to leave.
On the device the planet is a choice in the Species catalog, and when
its pack is downloaded it is the only one read, so the regions it holds
are not counted again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: sizes of the 20261129 packs; no hang re-signing a manifest
The packs grew about 15% with months and other names; the planet pack
is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg
asks before replacing an existing signature and nothing could answer.
The old signature is now removed first. Help: a dot's popup, months,
other names, and the planet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: the planet from each observation once; overlaps counted once
Map regions overlap, some widely (southern Arizona is in us-west and
mexico, north Africa in five regions): about 42M of 173M observations
are in two or more. Merging the region packs counted those twice, so
the planet is now built like a region from every observation once.
Its work is split into 8 files by species and built a file at a time
(all at once its sets would need ~25 GB). `planet` is a region for
--regions, built by default, and the manifest lists every pack of the
version in the folder, so a planet-only run keeps the regions. The
merge and its flags are gone.
On a device with overlapping region packs, a square both hold was
counted twice in "near" and in a dot's popup; each square now counts
the larger of the packs' counts. Species totals still add up across
overlapping packs; the planet pack is exact.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: Species screenshots from the planet pack
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Zoom to range fits the cluster of dots nearest the view
On the planet pack, giant sequoia (planted in Britain, New Zealand and
elsewhere) zoomed out to the whole world: far more than the 2% of dots
the zoom left out were planted away from its groves. Dots in touching
2° squares (about 220 km, also across the antimeridian) are now one
cluster, and Zoom to range fits the cluster nearest the middle of the
map: California from Yosemite, the planted trees from London. A range
spread across a continent is one cluster. Help updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Planet is listed first on the Manage tab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
357 lines
17 KiB
Python
357 lines
17 KiB
Python
"""Subscribing to species packs and downloading them: lib helpers, the downloaders, and the API."""
|
|
import json
|
|
from http import HTTPStatus
|
|
from unittest import mock
|
|
|
|
import pytest
|
|
import yaml
|
|
|
|
from modules.map import lib
|
|
from modules.map.catalog import MAP_REGIONS, SPECIES_MANIFEST_URL
|
|
from modules.map.downloader import (
|
|
ExecutedMapCatalog,
|
|
PreparedSpeciesPack,
|
|
species_catalog_downloader,
|
|
species_pack_downloader,
|
|
)
|
|
from wrolpi.conftest import make_test_ctx
|
|
from wrolpi.downloader import Download, DownloadFrequency, import_downloads_config
|
|
|
|
SHA256 = 'a' * 64
|
|
CDN = 'https://cdn.example.com/maps/inat'
|
|
|
|
|
|
def make_pack(region: str, version: str, contents: bytes = b'pack'):
|
|
path = lib.get_species_directory() / f'inat-{region}-{version}.species.db'
|
|
path.write_bytes(contents)
|
|
return path
|
|
|
|
|
|
def manifest(version: str = '20261123', *regions: str) -> dict:
|
|
regions = regions or ('us-west', 'us-alaska')
|
|
urls = {i: f'{CDN}/{version}/inat-{i}-{version}.species.db' for i in regions}
|
|
return {'version': version, 'regions': urls, 'sha256': {url: SHA256 for url in urls.values()}}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# lib
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_species_catalog(test_directory):
|
|
"""Every map region with a bbox has a species pack; terrain does not."""
|
|
catalog = lib.get_species_catalog()
|
|
regions = {i['region'] for i in catalog}
|
|
assert regions == {i['region'] for i in MAP_REGIONS if i['bbox']} | {'planet'}
|
|
assert 'terrain-z0-8' not in regions
|
|
us_west, = [i for i in catalog if i['region'] == 'us-west']
|
|
assert us_west['name'] == 'United States (West)'
|
|
assert us_west['bbox'] == '-125.0,24.4,-104.0,49.4'
|
|
assert us_west['size_estimate'] > 0
|
|
|
|
|
|
def test_species_directory(test_directory, test_wrolpi_config):
|
|
"""Packs are kept in `inat/` of the map directory."""
|
|
assert lib.get_species_directory() == test_directory / 'map/inat'
|
|
assert lib.get_species_directory().is_dir()
|
|
|
|
|
|
def test_species_files(test_directory):
|
|
"""Only pack files are listed, with their region and version."""
|
|
make_pack('us-west', '20261123', b'12345')
|
|
make_pack('europe-ne-central', '20261123')
|
|
(lib.get_species_directory() / 'notes.txt').write_text('not a pack')
|
|
(lib.get_species_directory() / 'inat-us-west.species.db').write_text('no version')
|
|
|
|
files = lib.get_species_files()
|
|
assert [(i['region'], i['version']) for i in files] == [('europe-ne-central', '20261123'), ('us-west', '20261123')]
|
|
assert files[1]['size'] == 5
|
|
assert files[1]['name'] == 'inat-us-west-20261123.species.db'
|
|
|
|
|
|
def test_delete_species_files(test_directory):
|
|
"""Deleting a region's packs deletes every version of it, and no other region with the same prefix."""
|
|
old = make_pack('europe-ne', '20261023')
|
|
new = make_pack('europe-ne', '20261123')
|
|
other = make_pack('europe-ne-central', '20261123')
|
|
|
|
assert lib.delete_species_files('europe-ne') is True
|
|
assert not old.exists() and not new.exists()
|
|
assert other.exists()
|
|
assert lib.delete_species_files('europe-ne') is False
|
|
# A region never names a path.
|
|
assert lib.delete_species_files('../../etc') is False
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_species_subscribe(async_client, test_session, test_directory):
|
|
"""Subscriptions share one recurring Download of the species manifest."""
|
|
await lib.species_subscribe(test_session, 'us-alaska')
|
|
await lib.species_subscribe(test_session, 'us-west')
|
|
await lib.species_subscribe(test_session, 'us-west') # Not duplicated.
|
|
await lib.species_subscribe(test_session, 'planet')
|
|
await lib.species_unsubscribe(test_session, 'planet')
|
|
|
|
assert lib.get_species_subscriptions(test_session) == [{'region': 'us-alaska'}, {'region': 'us-west'}]
|
|
download = lib._get_species_download(test_session)
|
|
assert download.url == SPECIES_MANIFEST_URL
|
|
assert download.downloader == 'species_catalog'
|
|
assert download.frequency == DownloadFrequency.days30
|
|
assert download.status == 'new'
|
|
|
|
with pytest.raises(ValueError):
|
|
await lib.species_subscribe(test_session, 'atlantis')
|
|
# Terrain is a map region, but has no species.
|
|
with pytest.raises(ValueError):
|
|
await lib.species_subscribe(test_session, 'terrain-z0-8')
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_species_unsubscribe(async_client, test_session, test_directory):
|
|
"""Unsubscribing keeps the downloaded pack; the last one deletes the Download."""
|
|
pack = make_pack('us-alaska', '20261123')
|
|
await lib.species_subscribe(test_session, 'us-alaska')
|
|
await lib.species_subscribe(test_session, 'us-west')
|
|
|
|
await lib.species_unsubscribe(test_session, 'us-alaska')
|
|
assert lib.get_species_subscriptions(test_session) == [{'region': 'us-west'}]
|
|
assert pack.is_file()
|
|
|
|
await lib.species_unsubscribe(test_session, 'us-west')
|
|
assert lib.get_species_subscriptions(test_session) == []
|
|
assert lib._get_species_download(test_session) is None
|
|
|
|
with pytest.raises(ValueError):
|
|
await lib.species_unsubscribe(test_session, 'us-west')
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_species_subscriptions_config(async_client, test_session, test_directory, test_download_manager_config,
|
|
await_switches):
|
|
"""Subscriptions are saved to the downloads config, and come back when it is imported."""
|
|
await lib.species_subscribe(test_session, 'us-west')
|
|
await await_switches()
|
|
|
|
with test_download_manager_config.open() as fh:
|
|
downloads = yaml.safe_load(fh)['downloads']
|
|
saved, = [i for i in downloads if i['url'] == SPECIES_MANIFEST_URL]
|
|
assert saved['downloader'] == 'species_catalog'
|
|
assert saved['settings'] == {'regions': [{'region': 'us-west'}]}
|
|
|
|
test_session.query(Download).delete()
|
|
test_session.commit()
|
|
assert lib.get_species_subscriptions(test_session) == []
|
|
|
|
await import_downloads_config()
|
|
assert lib.get_species_subscriptions(test_session) == [{'region': 'us-west'}]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# SpeciesCatalogDownloader
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_catalog_creates_pack_downloads(test_session, test_directory):
|
|
"""A species_pack Download is created for each subscribed region in the manifest, with its signed hash."""
|
|
download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog')
|
|
executed = ExecutedMapCatalog(manifest=manifest(), subscribed_regions=[{'region': 'us-west'}, {'region': 'mars'}])
|
|
|
|
result = species_catalog_downloader.finalize_download(test_session, download, executed)
|
|
|
|
assert result.success is True
|
|
child, = test_session.query(Download).filter_by(downloader='species_pack').all()
|
|
assert child.url == f'{CDN}/20261123/inat-us-west-20261123.species.db'
|
|
assert child.settings == {'region': 'us-west', 'version': '20261123', 'sha256': SHA256}
|
|
assert child.status == 'new'
|
|
|
|
|
|
def test_catalog_replaces_old_version(test_session, test_directory):
|
|
"""A new version replaces the old version's Download; other regions' Downloads are left alone."""
|
|
download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog')
|
|
subscribed = [{'region': 'us-west'}, {'region': 'us-alaska'}]
|
|
species_catalog_downloader.finalize_download(
|
|
test_session, download, ExecutedMapCatalog(manifest=manifest('20261023'), subscribed_regions=subscribed))
|
|
test_session.commit()
|
|
|
|
# The next month only us-west was rebuilt.
|
|
new = manifest('20261123', 'us-west')
|
|
new['regions']['us-alaska'] = f'{CDN}/20261023/inat-us-alaska-20261023.species.db'
|
|
new['sha256'][new['regions']['us-alaska']] = SHA256
|
|
species_catalog_downloader.finalize_download(
|
|
test_session, download, ExecutedMapCatalog(manifest=new, subscribed_regions=subscribed))
|
|
test_session.commit()
|
|
|
|
urls = sorted(i.url for i in test_session.query(Download).filter_by(downloader='species_pack'))
|
|
assert urls == [f'{CDN}/20261023/inat-us-alaska-20261023.species.db',
|
|
f'{CDN}/20261123/inat-us-west-20261123.species.db']
|
|
|
|
|
|
@pytest.mark.parametrize('bad_manifest,error', [
|
|
({'regions': {}, 'version': '20261123'}, 'does not contain regions'),
|
|
({'regions': {'us-west': 'https://x'}}, 'does not contain regions'),
|
|
(manifest('20261123', 'mexico'), 'No subscribed species regions'),
|
|
])
|
|
def test_catalog_failures(test_session, test_directory, bad_manifest, error):
|
|
download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog')
|
|
executed = ExecutedMapCatalog(manifest=bad_manifest, subscribed_regions=[{'region': 'us-west'}])
|
|
result = species_catalog_downloader.finalize_download(test_session, download, executed)
|
|
assert result.success is False
|
|
assert error in result.error
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_catalog_fetches_species_manifest(test_session, test_directory):
|
|
"""The species catalog fetches (and verifies) the manifest at its Download's URL."""
|
|
download = Download(url=SPECIES_MANIFEST_URL, downloader='species_catalog', settings={'regions': []})
|
|
prepared = species_catalog_downloader.prepare_download(test_session, download)
|
|
with mock.patch('modules.map.lib.fetch_manifest', mock.AsyncMock(return_value=manifest())) as fetch:
|
|
executed = await species_catalog_downloader.execute_download(prepared, make_test_ctx())
|
|
fetch.assert_called_once_with(SPECIES_MANIFEST_URL)
|
|
assert executed.manifest == manifest()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# SpeciesPackDownloader
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize('settings', [
|
|
{},
|
|
{'region': 'us-west'},
|
|
{'region': 'us-west', 'version': 'latest'},
|
|
{'region': '../../etc', 'version': '20261123'},
|
|
{'region': 'US West', 'version': '20261123'},
|
|
])
|
|
def test_pack_prepare_invalid(test_session, test_directory, settings):
|
|
"""A pack's region and version must make a pack name; nothing else is downloaded."""
|
|
download = Download(url=f'{CDN}/x.species.db', downloader='species_pack', settings=settings)
|
|
prepared = species_pack_downloader.prepare_download(test_session, download)
|
|
assert prepared.error == 'Invalid region or version in download settings'
|
|
|
|
|
|
def test_pack_prepare_already_done(test_session, test_directory):
|
|
make_pack('us-west', '20261123')
|
|
download = Download(url=f'{CDN}/20261123/inat-us-west-20261123.species.db', downloader='species_pack',
|
|
settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256})
|
|
prepared = species_pack_downloader.prepare_download(test_session, download)
|
|
assert prepared.already_done is True
|
|
assert prepared.output_path == test_directory / 'map/inat/inat-us-west-20261123.species.db'
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pack_refuses_without_signed_hash(test_session, test_directory):
|
|
"""With no hash in the manifest and no meta4, nothing is downloaded."""
|
|
url = f'{CDN}/20261123/inat-us-west-20261123.species.db'
|
|
download = Download(url=url, downloader='species_pack', settings={'region': 'us-west', 'version': '20261123'})
|
|
prepared = species_pack_downloader.prepare_download(test_session, download)
|
|
|
|
with mock.patch.object(species_pack_downloader, 'get_meta4_contents', mock.AsyncMock(return_value=None)), \
|
|
mock.patch.object(species_pack_downloader, 'download_file') as download_file:
|
|
executed = await species_pack_downloader.execute_download(prepared, make_test_ctx(), download)
|
|
|
|
assert 'No signed hash' in executed.error
|
|
download_file.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pack_download_replaces_old_version(test_session, test_directory):
|
|
"""The new pack is moved in only after aria2c checked it against the signed hash; then old versions go."""
|
|
old = make_pack('us-west', '20261023', b'old')
|
|
neighbor = make_pack('us-west-coast', '20261023', b'not this region') # Hypothetical region with the prefix.
|
|
url = f'{CDN}/20261123/inat-us-west-20261123.species.db'
|
|
download = Download(url=url, downloader='species_pack',
|
|
settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256})
|
|
prepared = species_pack_downloader.prepare_download(test_session, download)
|
|
|
|
async def fake_download_file(download_, url_, destination, **kwargs):
|
|
assert SHA256.encode() in kwargs['meta4_xml']
|
|
# Not in the species directory until it is checked.
|
|
assert destination == test_directory / 'map/.partial'
|
|
path = destination / 'inat-us-west-20261123.species.db'
|
|
path.write_bytes(b'new')
|
|
return path
|
|
|
|
with mock.patch.object(species_pack_downloader, 'download_file', fake_download_file):
|
|
executed = await species_pack_downloader.execute_download(prepared, make_test_ctx(), download)
|
|
|
|
assert executed.error is None
|
|
assert (test_directory / 'map/inat/inat-us-west-20261123.species.db').read_bytes() == b'new'
|
|
assert not old.exists()
|
|
assert neighbor.exists()
|
|
assert species_pack_downloader.finalize_download(test_session, download, executed).success is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pack_download_failure_keeps_old_version(test_session, test_directory):
|
|
"""A failed (or rejected) download leaves the region's current pack in place."""
|
|
old = make_pack('us-west', '20261023', b'old')
|
|
url = f'{CDN}/20261123/inat-us-west-20261123.species.db'
|
|
download = Download(url=url, downloader='species_pack',
|
|
settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256})
|
|
prepared = species_pack_downloader.prepare_download(test_session, download)
|
|
|
|
with mock.patch.object(species_pack_downloader, 'download_file',
|
|
mock.AsyncMock(side_effect=RuntimeError('aria2c failed with return code 32'))):
|
|
executed = await species_pack_downloader.execute_download(prepared, make_test_ctx(), download)
|
|
|
|
assert 'Download failed' in executed.error
|
|
assert old.read_bytes() == b'old'
|
|
assert not (test_directory / 'map/inat/inat-us-west-20261123.species.db').exists()
|
|
assert species_pack_downloader.finalize_download(test_session, download, executed).success is False
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pack_skipped(test_session, test_directory):
|
|
prepared = PreparedSpeciesPack(region='us-west', already_done=True)
|
|
executed = await species_pack_downloader.execute_download(prepared, make_test_ctx())
|
|
assert executed.skipped is True
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# API
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_species_api(async_client, test_session, test_directory):
|
|
"""The species catalog can be fetched, subscribed to, and unsubscribed from; packs can be deleted."""
|
|
request, response = await async_client.get('/api/map/species/subscribe')
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json['subscriptions'] == []
|
|
assert response.json['files'] == []
|
|
assert 'us-west' in [i['region'] for i in response.json['catalog']]
|
|
|
|
request, response = await async_client.post('/api/map/species/subscribe', content=json.dumps({'region': 'us-west'}))
|
|
assert response.status_code == HTTPStatus.CREATED
|
|
request, response = await async_client.post('/api/map/species/subscribe', content=json.dumps({'region': 'mars'}))
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
make_pack('us-west', '20261123', b'12345')
|
|
request, response = await async_client.get('/api/map/species/subscribe')
|
|
assert response.json['subscriptions'] == [{'region': 'us-west'}]
|
|
assert [(i['region'], i['version'], i['size']) for i in response.json['files']] == [('us-west', '20261123', 5)]
|
|
|
|
request, response = await async_client.delete('/api/map/species/subscribe/us-west')
|
|
assert response.status_code == HTTPStatus.NO_CONTENT
|
|
request, response = await async_client.delete('/api/map/species/subscribe/us-west')
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
request, response = await async_client.delete('/api/map/species/files/us-west')
|
|
assert response.status_code == HTTPStatus.NO_CONTENT
|
|
request, response = await async_client.delete('/api/map/species/files/us-west')
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
request, response = await async_client.get('/api/map/species/subscribe')
|
|
assert response.json['subscriptions'] == []
|
|
assert response.json['files'] == []
|
|
|
|
|
|
def test_pack_already_done_removes_old_versions(test_session, test_directory):
|
|
"""A download that stopped before deleting the older versions is finished on the next run."""
|
|
old = make_pack('us-west', '20261023', b'old')
|
|
make_pack('us-west', '20261123', b'new')
|
|
download = Download(url=f'{CDN}/20261123/inat-us-west-20261123.species.db', downloader='species_pack',
|
|
settings={'region': 'us-west', 'version': '20261123', 'sha256': SHA256})
|
|
prepared = species_pack_downloader.prepare_download(test_session, download)
|
|
assert prepared.already_done is True
|
|
assert not old.exists()
|