diff --git a/src/uk_open_data/analyses/_need.py b/src/uk_open_data/analyses/_need.py index 0f81331..66a9c1f 100644 --- a/src/uk_open_data/analyses/_need.py +++ b/src/uk_open_data/analyses/_need.py @@ -1323,10 +1323,7 @@ def keep_need_figures( Raises: ValueError: If the need is not one the analysis has built in. """ - if need not in MEASURES: - msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}." - raise ValueError(msg) - measure = MEASURES[need] + measure = _built_in(need) content = { "need": need, "label": measure.label, @@ -1360,11 +1357,28 @@ def download_need_figures(need: str = "unemployed") -> Path: ValueError: If the need is not one the analysis has built in, or its source does not return a count for each local authority. """ - if need not in MEASURES: - msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}." - raise ValueError(msg) - measure = MEASURES[need] + _built_in(need) clear_need_cache() + return keep_fetched_need_figures(need) + + +def keep_fetched_need_figures(need: str) -> Path: + """Keep a need's figures, fetching them only if they are not held in memory. + + Needs from one source then share one fetch. Call :func:`clear_need_cache` + first for fresh figures. + + Args: + need: One of the needs the analysis has built in, such as ``unemployed``. + + Returns: + The path of the file written. + + Raises: + ValueError: If the need is not one the analysis has built in, or its + source does not return a count for each local authority. + """ + measure = _built_in(need) figures = _in_nations(measure.fetch(), measure) note = f"fetched from {measure.origin} on {date.today().isoformat()}." return keep_need_figures( @@ -1388,6 +1402,14 @@ def clear_need_cache() -> None: crime.clear_cache() +def _built_in(need: str) -> Measure: + """Return a built-in need by its name, or say which ones there are.""" + if need not in MEASURES: + msg = f"No need called '{need}'. Known needs: {', '.join(MEASURES)}." + raise ValueError(msg) + return MEASURES[need] + + # --- the area compared ----------------------------------------------------- diff --git a/src/uk_open_data/analyses/datasets.py b/src/uk_open_data/analyses/datasets.py index a2d6bbd..78afb1a 100644 --- a/src/uk_open_data/analyses/datasets.py +++ b/src/uk_open_data/analyses/datasets.py @@ -17,7 +17,12 @@ from uk_open_data._nations import NATIONS from uk_open_data.analyses._centres import _LEVELS, download_centres from uk_open_data.analyses._model import Source -from uk_open_data.analyses._need import MEASURES, download_need_figures +from uk_open_data.analyses._need import ( + MEASURES, + clear_need_cache, + download_need_figures, + keep_fetched_need_figures, +) from uk_open_data.analyses._steps import ENGLAND_AND_WALES from uk_open_data.analyses.sources import ( CENSUS_ETHNIC_GROUP, @@ -106,6 +111,9 @@ def download_datasets( The analyses then read the copies instead of the network, so a server or a demonstration works offline. Run this once when a server is built, and again when new figures are published. Only public figures are fetched. + When a need is kept, the need figures held in memory are forgotten first, + so they are fetched afresh, and a file that several needs come from is + fetched once. The copies live in the data folder (see :func:`uk_open_data.postcodes.offline.data_dir`). @@ -121,15 +129,19 @@ def download_datasets( ValueError: If no id is given in a list, or an id is not a dataset that can be kept. Nothing is fetched then. """ + to_keep = _to_keep(ids) + downloads = [download for dataset in to_keep for download in dataset.downloads] + if any(isinstance(download, _NeedDownload) for download in downloads): + clear_need_cache() # Two datasets kept in one file share its download, which runs once. written: dict[Callable[[], Path], Path] = {} kept: dict[str, list[Path]] = {} - for dataset in _to_keep(ids): + for dataset in to_keep: fresh = [download for download in dataset.downloads if download not in written] if fresh: logger.info("Fetching %s.", dataset.source.id) for download in fresh: - written[download] = download() + written[download] = _run_with_others(download) kept[dataset.source.id] = [written[download] for download in dataset.downloads] return kept @@ -158,6 +170,17 @@ def _to_keep(ids: str | Iterable[str] | None) -> list[Dataset]: return [keepable[id_] for id_ in dict.fromkeys(wanted)] +def _run_with_others(download: Callable[[], Path]) -> Path: + """Run a download as one of several, where needs share what is fetched. + + The need figures held in memory were forgotten when the run began, so a + need keeps what a need before it fetched, and does not fetch it again. + """ + if isinstance(download, _NeedDownload): + return keep_fetched_need_figures(download.need) + return download() + + def _keep_postcode_table() -> Path: """Keep the postcode table this version publishes, unless it is installed. @@ -178,7 +201,7 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]: """ return ( *( - partial(download_need_figures, need) + _NeedDownload(need) for need, measure in MEASURES.items() if measure.source.id == source.id ), @@ -195,6 +218,16 @@ def _kept_for_analyses(source: Source) -> tuple[Callable[[], Path], ...]: ) +@dataclass(frozen=True) +class _NeedDownload: + """Fetches a need's figures afresh and keeps them, when run on its own.""" + + need: str + + def __call__(self) -> Path: + return download_need_figures(self.need) + + _NEED = ("need-reach", "provision-gap", "access-distance") # The analyses that place people in neighbourhoods and read their residents # from the indices of deprivation. diff --git a/tests/test_analysis_need_reach.py b/tests/test_analysis_need_reach.py index 1ec9b15..405c9b0 100644 --- a/tests/test_analysis_need_reach.py +++ b/tests/test_analysis_need_reach.py @@ -447,6 +447,14 @@ def test_only_built_in_needs_can_be_kept(): assert need_figures_path("poverty") is None +def test_an_unknown_need_is_refused_before_figures_are_forgotten(nomis): + _run(_counts(Lewisham=60)) + with pytest.raises(ValueError, match="No need called 'poverty'"): + download_need_figures("poverty") + _run(_counts(Lewisham=60)) + assert len(nomis.asked) == 2 # the need, and the residents for the map + + def test_a_kept_file_that_cannot_be_read_is_an_input_error(nomis): path = keep_need_figures("unemployed", INVENTED, "invented.") path.write_text('{"format": "something else"}', encoding="utf-8") diff --git a/tests/test_datasets.py b/tests/test_datasets.py index ca71086..43c4fd0 100644 --- a/tests/test_datasets.py +++ b/tests/test_datasets.py @@ -229,6 +229,24 @@ def test_clearing_caches_fetches_the_figures_again(nomis) -> None: assert _tables_asked(nomis).count("NM_2124_1") == 2 +def test_keeping_a_dataset_with_no_need_forgets_no_need_figures( + nomis, tmp_path, empty_data_dir +) -> None: + """Need figures held in memory outlast a run that keeps no need.""" + source = tmp_path / "lookup.csv" + source.write_text(fakes.POSTCODE_LOOKUP_CSV, encoding="utf-8") + table = tmp_path / "postcodes.ktpc.gz" + build_postcode_table(source, table, PUBLISHED_TABLE["edition"]) + install_postcode_table(table) + options = {"need": "unemployed"} + run_analysis("need-reach", COUNCIL_COUNTS, options=options) + + download_datasets(["ons-postcode-lookup"]) + + run_analysis("need-reach", COUNCIL_COUNTS, options=options) + assert _tables_asked(nomis).count("NM_2124_1") == 1 + + def test_an_empty_list_of_datasets_is_refused(nomis, empty_data_dir) -> None: with pytest.raises(ValueError, match="No dataset was named"): download_datasets([]) diff --git a/tests/test_vaccination_needs.py b/tests/test_vaccination_needs.py index 5df182c..0aed9a3 100644 --- a/tests/test_vaccination_needs.py +++ b/tests/test_vaccination_needs.py @@ -6,12 +6,14 @@ """ from typing import Any +from unittest.mock import MagicMock import pytest from need_fakes import COUNCIL_COUNTS, RUNS, area, keep_places, serve_gov_uk from spreadsheets import ods from uk_open_data.analyses import AnalysisInputError, AnalysisResult, run_analysis +from uk_open_data.analyses.datasets import download_datasets, list_datasets from uk_open_data.vaccinations import api RELEASE_PATH = "/government/statistics/cover-programme-april-2025-to-march-2026" @@ -91,8 +93,12 @@ def _table(age: str, vaccines: list[str], figures: list[list[float]]) -> list[An return [[f"Children aged {age}"], header, *rows] -def _serve(monkeypatch: pytest.MonkeyPatch, at_24_months: str = "MMR1") -> None: - """Serve UKHSA's statistics, naming the vaccine at 24 months as given.""" +def _serve(monkeypatch: pytest.MonkeyPatch, at_24_months: str = "MMR1") -> MagicMock: + """Serve UKHSA's statistics, naming the vaccine at 24 months as given. + + Returns: + The stand-in for the web request, to see what was asked. + """ workbook = ods( { "T4b_UTLA12m": _table("12 months", ["MenB"], AT_24_MONTHS), @@ -100,17 +106,18 @@ def _serve(monkeypatch: pytest.MonkeyPatch, at_24_months: str = "MMR1") -> None: "T6b_UTLA5y": _table("5 years", ["MMR1", "MMR2"], AT_5_YEARS), } ) - serve_gov_uk(monkeypatch, PAGES, {RELEASE_FILE: workbook}) + return serve_gov_uk(monkeypatch, PAGES, {RELEASE_FILE: workbook}) @pytest.fixture(autouse=True) -def gov_uk(monkeypatch: pytest.MonkeyPatch) -> None: +def gov_uk(monkeypatch: pytest.MonkeyPatch) -> MagicMock: """Serve UKHSA's statistics, and keep the residents and centres runs need.""" - _serve(monkeypatch) + answer = _serve(monkeypatch) keep_places( tuple((code, code, 100000) for code in MORE_COUNCILS), tuple((code, 52.6 + i / 100, -1.1) for i, code in enumerate(MORE_COUNCILS)), ) + return answer def _compared(result: AnalysisResult) -> dict[str, int]: @@ -193,6 +200,35 @@ def test_a_result_counts_children_without_both_mmr_doses() -> None: assert "ons-local-authority-lookups" in cited +def test_keeping_both_needs_fetches_ukhsa_once(gov_uk: MagicMock) -> None: + """Both needs come from one file, so keeping them fetches it once (#238).""" + kept = download_datasets("ukhsa-childhood-vaccinations") + + assert [path.name for path in kept["ukhsa-childhood-vaccinations"]] == [ + "children_without_mmr1_by_2.json", + "children_without_mmr2_by_5.json", + ] + assert [call.args[0] for call in gov_uk.call_args_list] == [ + api.CONTENT_API_URL, + RELEASE, + RELEASE_FILE, + ] + + +def test_a_download_run_on_its_own_fetches_afresh(gov_uk: MagicMock) -> None: + """Outside a run that keeps several, each download asks UKHSA again.""" + dataset = next( + dataset + for dataset in list_datasets() + if dataset.source.id == "ukhsa-childhood-vaccinations" + ) + + for download in dataset.downloads: + download() + + assert [call.args[0] for call in gov_uk.call_args_list].count(RELEASE_FILE) == 2 + + def test_a_renamed_vaccine_says_ukhsa_changed(monkeypatch: pytest.MonkeyPatch) -> None: _serve(monkeypatch, at_24_months="MMR 1")