import csv import gzip import hashlib import io import json import sqlite3 import zipfile from unittest import mock import pytest from modules.map.species import HIGH_GRID, LOW_GRID, LOOKUP_GRID, cell_id, decode_cells, decode_months, mask_months from wrolpi.scripts import build_inat_regions as build # A tiny taxonomy: (taxon_id, ancestry, rank, name). TAXA = [ (48460, '', 'stateofmatter', 'Life'), (1, '48460', 'kingdom', 'Animalia'), (3, '48460/1', 'class', 'Aves'), (12727, '48460/1/3', 'species', 'Turdus migratorius'), (999001, '48460/1/3/12727', 'subspecies', 'Turdus migratorius migratorius'), (47158, '48460/1', 'class', 'Insecta'), (88, '48460/1/47158', 'species', 'Coccinella septempunctata'), (6000, '48460/1', 'species', 'Animalia incertae'), (47126, '48460', 'kingdom', 'Plantae'), (54000, '48460/47126', 'genus', 'Acer'), (54001, '48460/47126/54000', 'species', 'Acer macrophyllum'), ] BEND = (44.06, -121.31) PRINEVILLE = (44.30, -120.83) BOUNDARY = (39.74, -104.0) # On the edge of us-west and us-central: in both. # (lat, lon, taxon_id, uncertainty, withheld, eventDate) OBSERVATIONS = [ (*BEND, 12727, '10', '', '2026-05-01T08:00:00-07:00'), (*BEND, 12727, '', '', '2026-05-20'), (*PRINEVILLE, 999001, '', '', '2025-06-10T09:30:00Z'), # A subspecies: counted as its species. (*BOUNDARY, 12727, '', '', '2026-07-04'), (*BEND, 54001, '', 'Coordinate uncertainty increased to 26807m at the request of the observer', '2024-10-01'), (*PRINEVILLE, 54001, '30000', '', ''), # Imprecise, and no date. (*BEND, 54000, '', '', '2026-01-01'), # Genus only: skipped. (*BEND, 424242, '', '', '2026-01-01'), # Unknown taxon: skipped. ('', '', 12727, '', 'Coordinates hidden at the request of the observer', '2026-01-01'), # No coordinates: skipped. (-50.0, -30.0, 88, '', '', '2026-01-01'), # In no region: skipped. (*BEND, 88, '', '', '2026-06-15'), (*BEND, 6000, '', '', 'spring 2026'), # Not a date. ] COLUMNS = ['id', 'informationWithheld', 'decimalLatitude', 'decimalLongitude', 'coordinateUncertaintyInMeters', 'taxonID', 'scientificName', 'eventDate'] US_REGIONS = [ {'region': 'us-west', 'bbox': '-125.0,24.4,-104.0,49.4'}, {'region': 'us-central', 'bbox': '-104.0,24.4,-87.0,49.4'}, {'region': 'us-east', 'bbox': '-87.0,24.4,-66.9,49.4'}, {'region': 'terrain-z0-8', 'bbox': None}, ] # iNaturalist's English names: (taxon_id, name, locality), in the archive's order. As in the real archive, the name # iNaturalist shows is listed first and is tied to a place; aliases without a place come after it. The first wins. VERNACULAR = [ (12727, 'American Robin', 'United States'), (12727, 'Robin Redbreast', ''), (12727, 'robin redbreast', ''), # The same name again. (12727, 'Migratory Thrush', ''), (54001, 'bigleaf maple', 'Oregon, US'), (54001, '', ''), (999001, 'Eastern American Robin', ''), ] WIKIDATA = { '12727': {'title': 'American_robin', 'common': 'American robin'}, '54001': {'title': 'Acer_macrophyllum', 'common': 'bigleaf maple'}, '88': {}, } @pytest.fixture def taxa_path(test_directory): path = test_directory / 'taxa.csv.gz' with gzip.open(path, 'wt', newline='') as fh: writer = csv.writer(fh, delimiter='\t') writer.writerow(['taxon_id', 'ancestry', 'rank_level', 'rank', 'name', 'active']) for taxon_id, ancestry, rank, name in TAXA: writer.writerow([taxon_id, ancestry, '', rank, name, 'true']) return path @pytest.fixture def taxonomy_path(test_directory): """iNaturalist's taxonomy archive, with only the English names.""" path = test_directory / 'inaturalist-taxonomy.dwca.zip' fh = io.StringIO() writer = csv.writer(fh) writer.writerow(['id', 'vernacularName', 'language', 'locality', 'countryCode', 'source', 'lexicon', 'contributor', 'created']) for taxon_id, name, locality in VERNACULAR: writer.writerow([taxon_id, name, 'en', locality, '', '', 'English', '', '2026-01-01T00:00:00Z']) with zipfile.ZipFile(path, 'w') as zf: zf.writestr('VernacularNames-english.csv', fh.getvalue()) return path @pytest.fixture def taxa(taxa_path): return build.Taxa.load(taxa_path) @pytest.fixture def dwca_path(test_directory): path = test_directory / 'dwca.zip' buffer = io.StringIO() writer = csv.writer(buffer) writer.writerow(COLUMNS) for i, (lat, lon, taxon_id, uncertainty, withheld, event_date) in enumerate(OBSERVATIONS): writer.writerow([i, withheld, lat, lon, uncertainty, taxon_id, 'name, with a comma', event_date]) with zipfile.ZipFile(path, 'w') as zf: zf.writestr('eml.xml', '\n 2026-11-23\n') zf.writestr('observations.csv', buffer.getvalue()) return path def test_dwca_version(dwca_path): assert build.dwca_version(dwca_path) == '20261123' def test_read_observations(dwca_path): observations = list(build.read_observations(dwca_path)) # Only the observation without coordinates is dropped here. assert len(observations) == len(OBSERVATIONS) - 1 precise = {(lat, lon, taxon_id): p for lat, lon, taxon_id, p, _ in observations} assert precise[(*BEND, 12727)] is True assert precise[(*BEND, 54001)] is False, 'withheld' assert precise[(*PRINEVILLE, 54001)] is False, 'uncertainty over 5 km' months = {(lat, lon, taxon_id): month for lat, lon, taxon_id, _, month in observations} assert months[(*PRINEVILLE, 999001)] == 6 assert months[(*PRINEVILLE, 54001)] == 0, 'no date' assert months[(*BEND, 6000)] == 0, 'not a date' @pytest.mark.parametrize('event_date,month', [ ('2025-09-04T14:22:00+02:00', 9), ('2025-12-31', 12), ('2025-01', 1), ('2025', 0), ('2025-13-01', 0), ('2025-00-01', 0), ('', 0), ('spring 2026', 0), ]) def test_observation_month(event_date, month): assert build.observation_month(event_date) == month def test_taxa(taxa): assert taxa.species_of(12727) == 12727 assert taxa.species_of(999001) == 12727 assert taxa.species_of(54000) is None, 'a genus has no species' assert taxa.species_of(424242) is None assert taxa.group_of(12727) == 2 # Birds assert taxa.group_of(88) == 7 # Insects, not Animalia's "other". assert taxa.group_of(54001) == 1 # Plants assert taxa.group_of(6000) == 0 def test_bbox_regions(): regions = build.bbox_regions(US_REGIONS) assert [name for name, _ in regions] == ['us-west', 'us-central', 'us-east'], 'terrain has no bbox' assert regions[0][1] == (-125.0, 24.4, -104.0, 49.4) # Every real map region parses. assert len(build.bbox_regions()) > 20 def test_split_by_region(test_directory, dwca_path, taxa): regions = build.bbox_regions(US_REGIONS) paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory) assert set(paths) == {'us-west', 'us-central'}, 'us-east received nothing' assert not (test_directory / 'us-east.tsv').exists() west = [line.split('\t') for line in paths['us-west'][0].read_text().splitlines()] central = [line.split('\t') for line in paths['us-central'][0].read_text().splitlines()] # Bend robin x2, Prineville subspecies, boundary robin, 2 maples, ladybug, other. assert len(west) == 8 assert central == [['39.74', '-104.0', '12727', '1', '7']], 'the boundary is in both regions' assert ['44.3', '-120.83', '12727', '1', '6'] in west, 'the subspecies became its species' assert build.species_in(paths['us-west'][0]) == {12727, 54001, 88, 6000} @pytest.fixture def west_pack(test_directory, dwca_path, taxa): regions = build.bbox_regions(US_REGIONS) paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory) db_path = test_directory / build.pack_name('us-west', '20261123') stats = build.build_pack(paths['us-west'], 'us-west', regions[0][1], taxa, WIKIDATA, '20261123', db_path) return db_path, stats def test_load_english_names(taxonomy_path): assert build.load_english_names(taxonomy_path) == { 12727: ['American Robin', 'Robin Redbreast', 'Migratory Thrush'], 54001: ['bigleaf maple'], 999001: ['Eastern American Robin'], } def test_build_pack_common_names(test_directory, dwca_path, taxa, taxonomy_path): """iNaturalist's first name is the common name, before Wikidata's; every other name is searchable.""" regions = build.bbox_regions(US_REGIONS) paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory) db_path = test_directory / build.pack_name('us-west', '20261123') wikidata = {**WIKIDATA, '88': {'title': 'Coccinella_septempunctata', 'common': 'seven-spot ladybird'}} build.build_pack(paths['us-west'], 'us-west', regions[0][1], taxa, wikidata, '20261123', db_path, build.load_english_names(taxonomy_path)) with sqlite3.connect(db_path) as db: names = {taxon: (common, other) for taxon, common, other in db.execute('SELECT taxon_id, common_name, other_names FROM species')} match = 'SELECT rowid FROM species_fts WHERE species_fts MATCH ?' assert db.execute(match, ('"redbreast"*',)).fetchall() == [(12727,)], 'an alias finds its species' assert db.execute(match, ('"american"* "robin"*',)).fetchall() == [(12727,)] assert names == { # Wikidata's name ("American robin") is the same name; it is not repeated. 12727: ('American Robin', 'Robin Redbreast; Migratory Thrush'), 54001: ('bigleaf maple', None), 88: ('seven-spot ladybird', None), 6000: (None, None), } def test_build_pack(west_pack): db_path, stats = west_pack assert db_path.name == 'inat-us-west-20261123.species.db' assert stats['species'] == 4 assert stats['observations'] == 8 assert stats['precise'] == 6 db = sqlite3.connect(db_path) meta = dict(db.execute('SELECT key, value FROM meta')) assert meta['version'] == '20261123' assert meta['region'] == 'us-west' assert meta['license'] == 'CC BY-NC 4.0' assert '10.15468/ab3s5x' in meta['attribution'] assert meta['observations'] == '8' species = {row[0]: row for row in db.execute( 'SELECT taxon_id, name, common_name, wiki_title, grp, obs_count, min_lat, min_lon, max_lat, max_lon,' ' range_low, range_high FROM species')} robin = species[12727] assert robin[1:6] == ('Turdus migratorius', 'American robin', 'American_robin', 2, 4) assert robin[6:10] == (BOUNDARY[0], BEND[1], PRINEVILLE[0], BOUNDARY[1]) assert decode_cells(robin[10]) == sorted({cell_id(*p, LOW_GRID) for p in (BEND, PRINEVILLE, BOUNDARY)}) assert decode_cells(robin[11]) == sorted({cell_id(*p, HIGH_GRID) for p in (BEND, PRINEVILLE, BOUNDARY)}) maple = species[54001] assert maple[2:6] == ('bigleaf maple', 'Acer_macrophyllum', 1, 2) assert maple[6:10] == (None, None, None, None), 'no precise observation, no bbox' assert decode_cells(maple[10]) == sorted({cell_id(*p, LOW_GRID) for p in (BEND, PRINEVILLE)}), 'blurred still count' assert maple[11] is None, 'blurred observations make no precise dots' assert species[88][2:4] == (None, None), 'Wikidata had nothing' assert species[6000][4] == 0 # The lookup cells add up to every observation, and find the species around Bend. assert db.execute('SELECT SUM(obs_count) FROM cell_species').fetchone()[0] == 8 bend = cell_id(*BEND, LOOKUP_GRID) assert dict(db.execute('SELECT taxon_id, obs_count FROM cell_species WHERE cell = ?', (bend,))) == { 12727: 2, 54001: 1, 88: 1, 6000: 1} # Months: how many each month of the year, and the months seen in each lookup cell. months = dict(db.execute('SELECT taxon_id, months FROM species')) assert decode_months(months[12727]) == [0, 0, 0, 0, 2, 1, 1, 0, 0, 0, 0, 0], 'May, May, June (Prineville), July' assert decode_months(months[54001]) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 'the undated maple is not a month' assert months[6000] is None, 'never dated' in_bend = dict(db.execute('SELECT taxon_id, months FROM cell_species WHERE cell = ?', (bend,))) assert {taxon: mask_months(mask) for taxon, mask in in_bend.items()} == {12727: [5], 54001: [10], 88: [6], 6000: []} # Names are searchable. match = 'SELECT rowid FROM species_fts WHERE species_fts MATCH ?' assert db.execute(match, ('bigleaf',)).fetchall() == [(54001,)] assert db.execute(match, ('turdus',)).fetchall() == [(12727,)] def test_parse_wikidata_bindings(): bindings = [ {'inat': {'value': '1'}, 'article': {'value': 'https://en.wikipedia.org/wiki/Artemisia_(plant)'}}, {'inat': {'value': '1'}, 'article': {'value': 'https://en.wikipedia.org/wiki/Second'}, 'common': {'value': 'sagebrush'}}, {'inat': {'value': '2'}, 'article': {'value': 'https://en.wikipedia.org/wiki/Caf%C3%A9'}}, {'inat': {'value': '3'}}, {'article': {'value': 'https://en.wikipedia.org/wiki/No_taxon'}}, ] assert build.parse_wikidata_bindings(bindings) == { '1': {'title': 'Artemisia_(plant)', 'common': 'sagebrush'}, '2': {'title': 'Café'}, '3': {}, } def test_fetch_wikidata_caches(test_directory): cache_path = test_directory / 'wikidata.json' asked = [] def query(taxon_ids): asked.append(list(taxon_ids)) return [{'inat': {'value': '1'}, 'article': {'value': 'https://en.wikipedia.org/wiki/One'}}] assert build.fetch_wikidata([1, 2], cache_path, query=query, delay=0) == {'1': {'title': 'One'}, '2': {}} assert asked == [['1', '2']] # Both are cached, even the taxon Wikidata knows nothing about. assert build.fetch_wikidata([2, 1], cache_path, query=query, delay=0) == {'1': {'title': 'One'}, '2': {}} assert len(asked) == 1 def test_fetch_wikidata_failure_not_cached(test_directory): """A batch that fails is not cached, so the next build asks again.""" cache_path = test_directory / 'wikidata.json' def failing(taxon_ids): raise RuntimeError('timeout') assert build.fetch_wikidata([1, 2, 3], cache_path, query=failing, delay=0) == {} assert not cache_path.exists() def test_fetch_wikidata_splits_failing_batch(test_directory): """A failing batch is split; the halves that work are kept.""" ids = [str(i) for i in range(40)] def query(taxon_ids): if '0' in taxon_ids: raise RuntimeError('this one is cursed') return [{'inat': {'value': i}, 'common': {'value': f'name {i}'}} for i in taxon_ids] found = build.fetch_wikidata(ids, test_directory / 'wikidata.json', query=query, delay=0) # Halved until the batch of 10 holding '0' failed alone; the other 30 were answered. (Ids sort as text.) failed = sorted(ids)[:10] assert len(found) == 30 assert not set(failed) & set(found), 'the failed batch is not cached' assert found['39'] == {'common': 'name 39'} def assert_not_exists(path): assert not path.exists(), f'{path} is still there when the manifest is signed' def test_write_manifest(test_directory, west_pack): db_path, _ = west_pack # A signature from an earlier build: gpg would ask before replacing it, and wait forever for an answer. old_signature = test_directory / 'manifest.json.sig' old_signature.write_text('old') with mock.patch.object(build, 'write_meta4', return_value='abc123') as write_meta4, \ mock.patch.object(build, 'sign_manifest', side_effect=lambda path: assert_not_exists(old_signature)) \ as sign_manifest: manifest_path = build.write_manifest(test_directory, '20261123', 'https://cdn.example/inat', {'us-west': db_path}) url = 'https://cdn.example/inat/20261123/inat-us-west-20261123.species.db' manifest = json.loads(manifest_path.read_text()) assert manifest['version'] == '20261123' assert manifest['regions'] == {'us-west': url} assert manifest['sizes'] == {'us-west': db_path.stat().st_size} assert manifest['sha256'] == {url: 'abc123'} assert manifest['license'] == 'CC BY-NC 4.0' write_meta4.assert_called_once_with(str(db_path), url) sign_manifest.assert_called_once_with(str(manifest_path)) def test_write_manifest_unsigned(test_directory, west_pack): """Without signing, the manifest still has each pack's sha256, for `sign_build` to sign elsewhere.""" db_path, _ = west_pack with mock.patch.object(build, 'write_meta4') as write_meta4, \ mock.patch.object(build, 'sign_manifest') as sign_manifest: manifest_path = build.write_manifest(test_directory, '20261123', 'https://cdn.example/inat', {'us-west': db_path}, sign=False) url = 'https://cdn.example/inat/20261123/inat-us-west-20261123.species.db' assert json.loads(manifest_path.read_text())['sha256'] == {url: hashlib.sha256(db_path.read_bytes()).hexdigest()} write_meta4.assert_not_called() sign_manifest.assert_not_called() CDN = 'https://cdn.example/inat' URL = f'{CDN}/20261123/inat-us-west-20261123.species.db' def unsigned_build(output_dir, **changes): """The manifest of an unsigned build, without the packs (they stay on the build host).""" manifest = dict(version='20261123', license='CC BY-NC 4.0', attribution='...', regions={'us-west': URL}, sizes={'us-west': 1234}, sha256={URL: 'a' * 64}) manifest.update(changes) output_dir.mkdir(parents=True, exist_ok=True) (output_dir / 'manifest.json').write_text(json.dumps(manifest)) def test_sign_build(test_directory): """Signs an unsigned build's hashes (a meta4 per pack) and its manifest, without the packs.""" output_dir = test_directory / 'out' unsigned_build(output_dir, extra='not signed') old_signature = output_dir / 'manifest.json.sig' old_signature.write_text('old') with mock.patch.object(build, 'sign_hash', return_value='SIGNATURE') as sign_hash, \ mock.patch.object(build, 'sign_manifest', side_effect=lambda path: assert_not_exists(old_signature)) \ as sign_manifest: build.sign_build(output_dir, CDN) sign_hash.assert_called_once_with('a' * 64) sign_manifest.assert_called_once_with(str(output_dir / 'manifest.json')) meta4 = (output_dir / '20261123' / 'inat-us-west-20261123.species.db.meta4').read_text() assert 'a' * 64 in meta4 and URL in meta4 and '1234' in meta4 and 'SIGNATURE' in meta4 # The manifest that is signed is written here, from what was checked: nothing else is carried over. manifest = json.loads((output_dir / 'manifest.json').read_text()) assert 'extra' not in manifest assert manifest['attribution'] == build.ATTRIBUTION assert manifest['regions'] == {'us-west': URL} and manifest['sha256'] == {URL: 'a' * 64} @pytest.mark.parametrize('changes', [ dict(version='../../etc'), dict(version=20261123), dict(regions={'atlantis': URL}), dict(regions={'us-west': 'https://elsewhere.example/inat-us-west-20261123.species.db'}), dict(regions={'us-west': f'{CDN}/20261123/../../evil.species.db'}), dict(regions={}), dict(sha256={URL: None}), dict(sha256={URL: 'not a hash'}), dict(sizes={'us-west': 0}), dict(sizes={'us-west': '1234'}), ]) def test_sign_build_refuses(test_directory, changes): """Only what a build writes is signed: a manifest from a compromised or broken build host is refused.""" output_dir = test_directory / 'out' unsigned_build(output_dir, **changes) with mock.patch.object(build, 'sign_hash') as sign_hash, \ mock.patch.object(build, 'sign_manifest') as sign_manifest, pytest.raises(ValueError): build.sign_build(output_dir, CDN) sign_hash.assert_not_called() sign_manifest.assert_not_called() assert not list(test_directory.rglob('*.meta4')) def test_main_sign(test_directory): """--sign signs an unsigned build; it needs no work directory.""" with mock.patch('sys.argv', ['build_inat_regions.py', '--sign', str(test_directory), '--cdn-base', CDN]), \ mock.patch.object(build, 'sign_build') as sign_build: build.main() sign_build.assert_called_once_with(test_directory, CDN) def test_main_needs_directories(): with mock.patch('sys.argv', ['build_inat_regions.py']), pytest.raises(SystemExit): build.main() def test_main(test_directory, dwca_path, taxa_path, taxonomy_path): """The whole build, offline: given sources, two regions, no signing.""" work_dir, output_dir = test_directory / 'work', test_directory / 'out' argv = ['build_inat_regions.py', str(work_dir), str(output_dir), '--dwca', str(dwca_path), '--taxa', str(taxa_path), '--taxonomy', str(taxonomy_path), '--regions', 'us-west,us-central', '--no-sign'] with mock.patch('sys.argv', argv), \ mock.patch.object(build, 'query_wikidata', return_value=[]), \ mock.patch.object(build, 'download') as download: build.main() download.assert_not_called() manifest = json.loads((output_dir / 'manifest.json').read_text()) assert set(manifest['regions']) == {'us-west', 'us-central'} assert (output_dir / '20261123' / 'inat-us-central-20261123.species.db').is_file() assert (output_dir / '20261123' / 'inat-us-west-20261123.species.db').is_file() assert json.loads((work_dir / 'wikidata.json').read_text()) == {'12727': {}, '54001': {}, '88': {}, '6000': {}} with sqlite3.connect(output_dir / '20261123' / 'inat-us-west-20261123.species.db') as db: assert db.execute('SELECT common_name FROM species WHERE taxon_id = 12727').fetchone() == ('American Robin',) # A rebuild of the same observations, with a new version, from the last build's region work files. with mock.patch('sys.argv', argv + ['--version', '20261128', '--reuse-split']), \ mock.patch.object(build, 'query_wikidata', return_value=[]), \ mock.patch.object(build, 'read_observations') as read_observations: build.main() read_observations.assert_not_called() manifest = json.loads((output_dir / 'manifest.json').read_text()) assert manifest['version'] == '20261128' assert manifest['regions']['us-west'].endswith('/20261128/inat-us-west-20261128.species.db') with sqlite3.connect(output_dir / '20261128' / 'inat-us-west-20261128.species.db') as db: assert dict(db.execute('SELECT key, value FROM meta'))['version'] == '20261128' assert db.execute('SELECT COUNT(*) FROM species').fetchone() == (4,) @pytest.mark.parametrize('newer_than,built', [('20261122', True), ('20261123', False), ('20261129', False)]) def test_main_newer_than(test_directory, dwca_path, taxa_path, taxonomy_path, newer_than, built): """--newer-than: observations no newer than those published build nothing, so nothing older is published.""" output_dir = test_directory / 'out' argv = ['build_inat_regions.py', str(test_directory / 'work'), str(output_dir), '--dwca', str(dwca_path), '--taxa', str(taxa_path), '--taxonomy', str(taxonomy_path), '--regions', 'us-west', '--no-sign', '--newer-than', newer_than] with mock.patch('sys.argv', argv), mock.patch.object(build, 'query_wikidata', return_value=[]): build.main() assert (output_dir / 'manifest.json').is_file() == built @pytest.mark.parametrize('extra', [['--version', '2026-11-28'], ['--reuse-split']]) def test_main_invalid(test_directory, dwca_path, taxa_path, taxonomy_path, extra): """A version must be YYYYMMDD; --reuse-split needs the work files of a last build.""" argv = ['build_inat_regions.py', str(test_directory / 'work'), str(test_directory / 'out'), '--dwca', str(dwca_path), '--taxa', str(taxa_path), '--taxonomy', str(taxonomy_path), '--no-sign', *extra] with mock.patch('sys.argv', argv), pytest.raises(SystemExit): build.main() def test_main_unknown_region(test_directory): argv = ['build_inat_regions.py', str(test_directory), str(test_directory), '--regions', 'atlantis'] with mock.patch('sys.argv', argv), pytest.raises(SystemExit): build.main() def test_planet(test_directory, dwca_path, taxa, taxonomy_path): """The planet is every observation once, though regions overlap, built from work files split by species.""" regions = build.bbox_regions(US_REGIONS) paths = build.split_by_region(build.read_observations(dwca_path), taxa, regions, test_directory, planet=True) buckets = paths['planet'] assert len(buckets) == build.PLANET_BUCKETS # Each species is in one bucket; every observation of a species (in a region or not) is in it once. species_of_bucket = [build.species_in(i) for i in buckets] assert sum(len(i) for i in species_of_bucket) == len(set().union(*species_of_bucket)) == 4 # Bend robin x2, Prineville subspecies, boundary robin, 2 maples, 2 ladybugs (one in no region), other. assert sum(len(i.read_text().splitlines()) for i in buckets) == 9 planet = test_directory / build.pack_name('planet', '20261123') stats = build.build_pack(buckets, 'planet', build.PLANET_BBOX, taxa, WIKIDATA, '20261123', planet, build.load_english_names(taxonomy_path)) assert (stats['species'], stats['observations']) == (4, 9) db = sqlite3.connect(planet) meta = dict(db.execute('SELECT key, value FROM meta')) assert (meta['region'], meta['bbox'], meta['observations']) == ('planet', '-180.0,-90.0,180.0,90.0', '9') # The boundary robin is in both us-west and us-central, but once here: Bend x2, Prineville, the boundary. robin = db.execute('SELECT common_name, obs_count, months FROM species WHERE taxon_id = 12727').fetchone() assert robin == ('American Robin', 4, '0,0,0,0,2,1,1,0,0,0,0,0') assert db.execute('SELECT SUM(obs_count) FROM cell_species').fetchone() == (9,) assert db.execute("SELECT rowid FROM species_fts WHERE species_fts MATCH '\"redbreast\"*'").fetchall() == [(12727,)] def test_main_planet_alone(test_directory, dwca_path, taxa_path, taxonomy_path): """`--regions planet` builds only the planet; the manifest also lists the regions already built for the version.""" work_dir, output_dir = test_directory / 'work', test_directory / 'out' argv = ['build_inat_regions.py', str(work_dir), str(output_dir), '--dwca', str(dwca_path), '--taxa', str(taxa_path), '--taxonomy', str(taxonomy_path), '--no-sign'] with mock.patch('sys.argv', argv + ['--regions', 'us-west,us-central']), \ mock.patch.object(build, 'query_wikidata', return_value=[]): build.main() assert not (output_dir / '20261123' / 'inat-planet-20261123.species.db').exists() with mock.patch('sys.argv', argv + ['--regions', 'planet']), \ mock.patch.object(build, 'query_wikidata', return_value=[]): build.main() manifest = json.loads((output_dir / 'manifest.json').read_text()) assert set(manifest['regions']) == {'us-west', 'us-central', 'planet'} assert not (work_dir / 'regions' / 'us-west.tsv').read_text() == '', 'the regions\' work was left alone'