:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Nager.Date import source (#84422)
Tom Owersfbe2a2f6f8cc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/nagerdate.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/nagerdate.pyindex 721e31d3e4a7..3ff109737d08 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/nagerdate.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/nagerdate.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass NagerDateSourceConfig(config.Config):- pass+ country_codes: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/canonical_descriptions.pynew file mode 100644index 000000000000..e23873786f79--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/canonical_descriptions.py@@ -0,0 +1,50 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://date.nager.at/scalar"++_HOLIDAY_COLUMNS = {+ "id": "Synthetic identifier this source adds from countryCode, date, name, subdivisionCodes, "+ "and holidayTypes, so a holiday split across subdivisions gets a unique row.",+ "date": "The date of the holiday.",+ "name": "English name of the holiday.",+ "countryCode": "ISO 3166-1 alpha-2 country code.",+ "nationalHoliday": "True if the holiday applies to the entire country.",+ "subdivisionCodes": "ISO 3166-2 codes of the subdivisions the holiday applies to, or null if it applies nationally.",+ "holidayTypes": "Holiday type classifications, for example Public, Bank, or School.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Countries": {+ "description": "Countries the Nager.Date API publishes public holiday data for.",+ "docs_url": _DOCS_URL,+ "columns": {+ "countryCode": "ISO 3166-1 alpha-2 country code, for example US or DE.",+ "name": "The common name of the country.",+ },+ },+ "CountryInfo": {+ "description": "Name and region information for each configured country, including neighboring countries.",+ "docs_url": _DOCS_URL,+ "columns": {+ "commonName": "The commonly used name of the country.",+ "nativeName": "The name of the country in its native language.",+ "officialName": "The official name of the country.",+ "countryCode": "ISO 3166-1 alpha-2 country code.",+ "region": "Geopolitical or continental region of the country.",+ "borders": "Neighboring countries based on geographical borders, or null if none.",+ },+ },+ "PublicHolidays": {+ "description": "Public holidays for each configured country, for the years the API currently supports "+ "(a rolling window around the current year).",+ "docs_url": _DOCS_URL,+ "columns": _HOLIDAY_COLUMNS,+ },+ "NextPublicHolidays": {+ "description": "The next public holidays occurring within 365 days for each configured country.",+ "docs_url": _DOCS_URL,+ "columns": _HOLIDAY_COLUMNS,+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/nager_date.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/nager_date.pynew file mode 100644index 000000000000..e002b2b61c23--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/nager_date.py@@ -0,0 +1,218 @@+import re+import datetime+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import quote++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.settings import (+ COUNTRIES,+ COUNTRY_INFO,+ NEXT_PUBLIC_HOLIDAYS,+ PUBLIC_HOLIDAYS,+)++BASE_URL = "https://date.nager.at/api/v4"++REQUEST_TIMEOUT_SECONDS = 30++# The community API only serves a rolling window of years around today for PublicHolidays;+# requesting outside it returns HTTP 400 rather than an empty list. Verified live (2026-08-18):+# the US, GB, DE, FR, JP, and BR all accepted 2025-2031 and rejected 2024 and 2032, i.e. the+# current year minus 1 through plus 5. This isn't documented in the OpenAPI spec, so `_get` also+# treats an out-of-window 400 as "no data" rather than an error, in case the window shifts.+BACKFILL_YEARS_BACK = 1+FORWARD_YEARS = 5++# Bounds fan-out: the API lists 200+ countries, and every configured country costs one request+# per synced year for PublicHolidays, plus one each for CountryInfo and NextPublicHolidays.+MAX_COUNTRY_CODES = 50++_CODE_SEPARATORS = re.compile(r"[,\s]+")+_COUNTRY_CODE_RE = re.compile(r"^[A-Za-z]{2}$")++[email protected](frozen=True)+class NagerDateResumeConfig:+ # Position in the endpoint's flattened work list (countries, or country/year pairs).+ index: int = 0+++def parse_country_codes(raw: Optional[str]) -> list[str]:+ """Parse the user's free-text `country_codes` field into a deduplicated, uppercased list.++ Accepts one code per line and/or comma-separated codes.+ """+ codes: list[str] = []+ seen: set[str] = set()+ for token in _CODE_SEPARATORS.split(raw or ""):+ code = token.strip().upper()+ if not code:+ continue+ if code not in seen:+ seen.add(code)+ codes.append(code)+ return codes+++def check_country_codes(country_codes: list[str]) -> Optional[str]:+ """User-facing error if the configured country code list is empty, oversized, or malformed."""+ if not country_codes:+ return "Enter at least one ISO 3166-1 alpha-2 country code, for example US."+ if len(country_codes) > MAX_COUNTRY_CODES:+ return f"Too many country codes ({len(country_codes)}); enter at most {MAX_COUNTRY_CODES}."+ invalid = [code for code in country_codes if not _COUNTRY_CODE_RE.match(code)]+ if invalid:+ return f"These aren't valid two-letter country codes: {', '.join(invalid)}."+ return None+++def _holiday_years() -> list[int]:+ current_year = datetime.date.today().year+ return list(range(current_year - BACKFILL_YEARS_BACK, current_year + FORWARD_YEARS + 1))+++def _holiday_id(row: dict[str, Any]) -> str:+ """Synthetic key for a holiday row: (countryCode, date, name) alone isn't unique — the same+ holiday can appear twice with different subdivisionCodes/holidayTypes (e.g. Good Friday is a+ public holiday in some US states and an optional holiday in Texas)."""+ subdivisions = ",".join(sorted(row.get("subdivisionCodes") or []))+ types = ",".join(sorted(row.get("holidayTypes") or []))+ return f"{row.get('countryCode')}|{row.get('date')}|{row.get('name')}|{subdivisions}|{types}"+++def _with_holiday_id(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return [{**row, "id": _holiday_id(row)} for row in rows]+++def _get(session: requests.Session, path: str) -> Any:+ """GET a Nager.Date v4 path, treating "no data for this request" as `None`.++ 204: the country has no holiday data at all. 400: the requested year is outside the community+ API's supported rolling window. 404: the country code isn't recognized (validate_credentials+ should already have caught this at source-create).+ """+ response = session.get(f"{BASE_URL}{path}", timeout=REQUEST_TIMEOUT_SECONDS)+ if response.status_code in (204, 400, 404):+ return None+ response.raise_for_status()+ if not response.content:+ return None+ return response.json()+++def _countries_rows(session: requests.Session) -> Iterator[list[dict[str, Any]]]:+ data = _get(session, "/Countries/Available")+ if data:+ yield data+++def _country_info_rows(+ session: requests.Session,+ country_codes: list[str],+ resumable_source_manager: ResumableSourceManager[NagerDateResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume.index if resume is not None else 0++ for index, country_code in enumerate(country_codes):+ if index < start_index:+ continue+ data = _get(session, f"/Countries/{quote(country_code, safe='')}")+ if data:+ yield [data]+ resumable_source_manager.save_state(NagerDateResumeConfig(index=index + 1))+++def _next_public_holidays_rows(+ session: requests.Session,+ country_codes: list[str],+ resumable_source_manager: ResumableSourceManager[NagerDateResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume.index if resume is not None else 0++ for index, country_code in enumerate(country_codes):+ if index < start_index:+ continue+ data = _get(session, f"/Holidays/{quote(country_code, safe='')}/Next")+ if data:+ yield _with_holiday_id(data)+ resumable_source_manager.save_state(NagerDateResumeConfig(index=index + 1))+++def _public_holidays_rows(+ session: requests.Session,+ country_codes: list[str],+ resumable_source_manager: ResumableSourceManager[NagerDateResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ work_items = [(country_code, year) for country_code in country_codes for year in _holiday_years()]++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume.index if resume is not None else 0++ for index, (country_code, year) in enumerate(work_items):+ if index < start_index:+ continue+ data = _get(session, f"/Holidays/{quote(country_code, safe='')}/{year}")+ if data:+ yield _with_holiday_id(data)+ resumable_source_manager.save_state(NagerDateResumeConfig(index=index + 1))+++def nager_date_source(+ endpoint: str,+ country_codes: list[str],+ resumable_source_manager: ResumableSourceManager[NagerDateResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session()++ if endpoint == COUNTRIES:+ yield from _countries_rows(session)+ return++ codes_error = check_country_codes(country_codes)+ if codes_error:+ raise ValueError(f"Nager.Date source misconfigured: {codes_error}")++ if endpoint == COUNTRY_INFO:+ yield from _country_info_rows(session, country_codes, resumable_source_manager)+ elif endpoint == NEXT_PUBLIC_HOLIDAYS:+ yield from _next_public_holidays_rows(session, country_codes, resumable_source_manager)+ elif endpoint == PUBLIC_HOLIDAYS:+ yield from _public_holidays_rows(session, country_codes, resumable_source_manager)+ else:+ raise ValueError(f"Unknown Nager.Date endpoint: {endpoint}")++ # Walked to completion: drop the checkpoint so a later attempt restarts cleanly instead of+ # resuming past the end and syncing nothing.+ resumable_source_manager.clear_state()+++def validate_credentials(country_codes: list[str]) -> tuple[bool, Optional[str]]:+ """Confirm the API is reachable and the first configured country code is recognized.++ The API is fully open, so there's no credential to check beyond that the configured codes are+ well-formed and real.+ """+ codes_error = check_country_codes(country_codes)+ if codes_error:+ return False, codes_error++ try:+ response = make_tracked_session().get(+ f"{BASE_URL}/Countries/{quote(country_codes[0], safe='')}", timeout=REQUEST_TIMEOUT_SECONDS+ )+ except Exception:+ return False, "Could not reach the Nager.Date API. Please try again."++ if response.status_code == 404:+ return False, f"'{country_codes[0]}' is not a recognized country code."+ if response.status_code != 200:+ return False, "The Nager.Date API returned an unexpected status code. Please try again."++ return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/settings.pynew file mode 100644index 000000000000..58261b455961--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/settings.py@@ -0,0 +1,29 @@+COUNTRIES = "Countries"+COUNTRY_INFO = "CountryInfo"+PUBLIC_HOLIDAYS = "PublicHolidays"+NEXT_PUBLIC_HOLIDAYS = "NextPublicHolidays"++ENDPOINTS: tuple[str, ...] = (+ COUNTRIES,+ COUNTRY_INFO,+ PUBLIC_HOLIDAYS,+ NEXT_PUBLIC_HOLIDAYS,+)++# PublicHolidays and NextPublicHolidays can return two rows with the same (countryCode, date,+# name) when a holiday applies to different subdivisions under different classifications (e.g.+# Good Friday is a public holiday in some US states and an optional holiday in Texas), so the+# table-wide key is a synthetic id built from the whole row — see `_holiday_id` in nager_date.py.+PRIMARY_KEYS: dict[str, list[str]] = {+ COUNTRIES: ["countryCode"],+ COUNTRY_INFO: ["countryCode"],+ PUBLIC_HOLIDAYS: ["id"],+ NEXT_PUBLIC_HOLIDAYS: ["id"],+}++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ COUNTRIES: "Countries the Nager.Date API publishes public holiday data for.",+ COUNTRY_INFO: "Country names and region for each configured country, with bordering countries.",+ PUBLIC_HOLIDAYS: "Public holidays for each configured country, for the years the API currently supports.",+ NEXT_PUBLIC_HOLIDAYS: "The next public holidays occurring within 365 days for each configured country.",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/source.pyindex 3a467a748e82..847a3e6a5c79 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/source.py@@ -1,21 +1,51 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.nagerdate import (NagerDateSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.nager_date import (+ NagerDateResumeConfig,+ nager_date_source,+ parse_country_codes,+ validate_credentials as validate_nager_date_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.settings import (+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ PRIMARY_KEYS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NagerDateSource(SimpleSource[NagerDateSourceConfig]):+class NagerDateSource(ResumableSource[NagerDateSourceConfig, NagerDateResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # The v3 API is deprecated (sunset 2027-01-31); v4 is the current generally available version+ # and is what every request in nager_date.py sends (the `/api/v4/` path segment).+ supported_versions = ("v4",)+ default_version = "v4"+ api_docs_url = "https://date.nager.at/scalar"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NAGERDATE@@ -26,7 +56,92 @@ class NagerDateSource(SimpleSource[NagerDateSourceConfig]):name=SchemaExternalDataSourceType.NAGER_DATE,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Nager.Date",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["holidays", "public holidays", "calendar"],+ caption="""Pull public holiday data from the free [Nager.Date](https://date.nager.at) API into the PostHog Data warehouse.++The API is open, so no credentials are required. Enter the ISO 3166-1 alpha-2 country codes you want to track, one per line or comma separated. For example:++```+US+GB+DE+```++A holidays table like this is commonly joined against event, order, or traffic timestamps by date and country to explain dips and seasonality.++The API only serves a rolling window of years around today, and it has no "changed since" filter, so every table syncs as a full refresh on each run. This also picks up holiday corrections the source publishes after the fact.""",iconPath="/static/services/nager_date.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/nager-date",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="country_codes",+ label="Country codes",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=True,+ placeholder="US\nGB\nDE",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # The API is unauthenticated, so there are no credential errors. What can permanently+ # fail a sync is a country code list that's empty, malformed, or over the per-source cap.+ return {+ "Nager.Date source misconfigured": "Check the country codes on this source: the list is empty, invalid, or has more codes than a single source can sync.",+ }++ def get_schemas(+ self,+ config: NagerDateSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # No endpoint exposes a server-side "changed since" filter, so every table is full+ # refresh only. That's also how retroactive holiday corrections get picked up.+ return build_endpoint_schemas(ENDPOINTS, {}, names, descriptions=ENDPOINT_DESCRIPTIONS)++ def validate_credentials(+ self,+ config: NagerDateSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_nager_date_credentials(parse_country_codes(config.country_codes))++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NagerDateResumeConfig]:+ return ResumableSourceManager[NagerDateResumeConfig](inputs, NagerDateResumeConfig)++ def source_for_pipeline(+ self,+ config: NagerDateSourceConfig,+ resumable_source_manager: ResumableSourceManager[NagerDateResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint = inputs.schema_name+ country_codes = parse_country_codes(config.country_codes)++ return SourceResponse(+ name=endpoint,+ items=lambda: nager_date_source(+ endpoint=endpoint,+ country_codes=country_codes,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=PRIMARY_KEYS[endpoint],)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date.pynew file mode 100644index 000000000000..87994144d3f1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date.py@@ -0,0 +1,331 @@+from typing import Any, Optional++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.nager_date import (+ BACKFILL_YEARS_BACK,+ BASE_URL,+ FORWARD_YEARS,+ MAX_COUNTRY_CODES,+ NagerDateResumeConfig,+ _get,+ _holiday_id,+ _holiday_years,+ check_country_codes,+ nager_date_source,+ parse_country_codes,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.settings import (+ COUNTRIES,+ COUNTRY_INFO,+ NEXT_PUBLIC_HOLIDAYS,+ PUBLIC_HOLIDAYS,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.nager_date"+++def _response(status: int = 200, body: Optional[Any] = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status+ resp.content = b"[]" if status not in (204,) else b""+ resp.json.return_value = body+ if status >= 500 or status not in (200, 204, 400, 404):+ resp.raise_for_status.side_effect = requests.HTTPError(f"{status} error", response=resp)+ return resp+++class TestParseCountryCodes:+ @parameterized.expand(+ [+ ("US", ["US"]),+ ("us", ["US"]),+ ("US,GB", ["US", "GB"]),+ ("US\nGB\nDE", ["US", "GB", "DE"]),+ (" US , GB \n DE ", ["US", "GB", "DE"]),+ ("US\nUS\nGB", ["US", "GB"]),+ ("US\n\n \nGB", ["US", "GB"]),+ (None, []),+ ("", []),+ ]+ )+ def test_parses_and_dedupes(self, raw: Optional[str], expected: list[str]) -> None:+ assert parse_country_codes(raw) == expected+++class TestCheckCountryCodes:+ def test_empty_is_invalid(self) -> None:+ assert check_country_codes([]) is not None++ def test_too_many_is_invalid(self) -> None:+ codes = [f"C{i}" for i in range(MAX_COUNTRY_CODES + 1)]+ message = check_country_codes(codes)+ assert message is not None+ assert "Too many" in message++ def test_at_the_cap_is_valid(self) -> None:+ codes = [chr(ord("A") + (i % 26)) * 2 for i in range(MAX_COUNTRY_CODES)]+ assert check_country_codes(codes) is None++ @parameterized.expand([(["USA"],), (["1G"],), (["U"],)])+ def test_malformed_code_is_invalid(self, codes: list[str]) -> None:+ message = check_country_codes(codes)+ assert message is not None+ assert "valid two-letter" in message++ def test_valid_codes_pass(self) -> None:+ assert check_country_codes(["US", "GB"]) is None+++class TestHolidayId:+ def test_stable_for_identical_rows(self) -> None:+ row = {"countryCode": "US", "date": "2026-04-03", "name": "Good Friday", "subdivisionCodes": ["US-TX"]}+ assert _holiday_id(row) == _holiday_id(dict(row))++ def test_differs_when_subdivisions_differ(self) -> None:+ # The same holiday can be split across multiple rows with different subdivisionCodes and+ # holidayTypes (e.g. Good Friday is Public in most states and Optional in Texas) — without+ # a synthetic key these would collide on (countryCode, date, name).+ row_a = {+ "countryCode": "US",+ "date": "2026-04-03",+ "name": "Good Friday",+ "subdivisionCodes": ["US-CT"],+ "holidayTypes": ["Public"],+ }+ row_b = {+ "countryCode": "US",+ "date": "2026-04-03",+ "name": "Good Friday",+ "subdivisionCodes": ["US-TX"],+ "holidayTypes": ["Optional"],+ }+ assert _holiday_id(row_a) != _holiday_id(row_b)++ def test_handles_null_subdivisions_and_types(self) -> None:+ row = {"countryCode": "US", "date": "2026-01-01", "name": "New Year's Day", "subdivisionCodes": None}+ assert _holiday_id(row) == "US|2026-01-01|New Year's Day||"+++class TestGet:+ @parameterized.expand([(204,), (400,), (404,)])+ def test_returns_none_for_no_data_statuses(self, status: int) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(status)++ assert _get(session, "/Holidays/US/2026") is None++ def test_returns_json_body_on_200(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(200, [{"countryCode": "US"}])++ assert _get(session, "/Countries/Available") == [{"countryCode": "US"}]++ def test_returns_none_for_empty_body_on_200(self) -> None:+ # A 200 with no body is distinct from the documented "no data" statuses, but should+ # still come back as None rather than raising on `.json()`.+ session = mock.MagicMock()+ response = _response(200)+ response.content = b""+ session.get.return_value = response++ assert _get(session, "/Countries/Available") is None++ def test_raises_for_server_error(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(500)++ with pytest.raises(requests.HTTPError):+ _get(session, "/Countries/Available")+++class TestHolidayYears:+ @freeze_time("2026-06-15")+ def test_spans_the_configured_backfill_and_forward_window(self) -> None:+ years = _holiday_years()++ assert years == list(range(2026 - BACKFILL_YEARS_BACK, 2026 + FORWARD_YEARS + 1))+ assert years[0] == 2025+ assert years[-1] == 2031+++def _make_manager(index: Optional[int] = None) -> mock.MagicMock:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = index is not None+ manager.load_state.return_value = NagerDateResumeConfig(index=index) if index is not None else None+ return manager+++class TestNagerDateSource:+ def test_countries_yields_the_full_list_in_one_batch(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, [{"countryCode": "US"}, {"countryCode": "GB"}])++ batches = list(nager_date_source(COUNTRIES, [], _make_manager()))++ assert batches == [[{"countryCode": "US"}, {"countryCode": "GB"}]]++ def test_country_info_yields_one_batch_per_country_and_saves_state(self) -> None:+ manager = _make_manager()+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [+ _response(200, {"countryCode": "US", "commonName": "United States"}),+ _response(200, {"countryCode": "GB", "commonName": "United Kingdom"}),+ ]++ batches = list(nager_date_source(COUNTRY_INFO, ["US", "GB"], manager))++ assert batches == [+ [{"countryCode": "US", "commonName": "United States"}],+ [{"countryCode": "GB", "commonName": "United Kingdom"}],+ ]+ assert [call.args[0].index for call in manager.save_state.call_args_list] == [1, 2]+ manager.clear_state.assert_called_once()++ def test_country_info_resumes_from_saved_index(self) -> None:+ manager = _make_manager(index=1)+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, {"countryCode": "GB"})++ batches = list(nager_date_source(COUNTRY_INFO, ["US", "GB"], manager))++ # Only the country at (and after) the saved index is fetched.+ assert batches == [[{"countryCode": "GB"}]]+ called_url = mock_session.return_value.get.call_args[0][0]+ assert called_url == f"{BASE_URL}/Countries/GB"++ def test_public_holidays_requests_every_configured_year_per_country(self) -> None:+ manager = _make_manager()+ with (+ mock.patch(f"{MODULE}.make_tracked_session") as mock_session,+ mock.patch(f"{MODULE}._holiday_years", return_value=[2025, 2026]),+ ):+ mock_session.return_value.get.return_value = _response(+ 200, [{"countryCode": "US", "date": "2026-01-01", "name": "New Year's Day"}]+ )++ list(nager_date_source(PUBLIC_HOLIDAYS, ["US"], manager))++ called_urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]++ assert called_urls == [f"{BASE_URL}/Holidays/US/2025", f"{BASE_URL}/Holidays/US/2026"]++ def test_public_holidays_skips_years_outside_the_supported_window(self) -> None:+ manager = _make_manager()+ with (+ mock.patch(f"{MODULE}.make_tracked_session") as mock_session,+ mock.patch(f"{MODULE}._holiday_years", return_value=[2020, 2026]),+ ):+ mock_session.return_value.get.side_effect = [+ _response(400), # 2020 is outside the community window+ _response(200, [{"countryCode": "US", "date": "2026-01-01", "name": "New Year's Day"}]),+ ]++ batches = list(nager_date_source(PUBLIC_HOLIDAYS, ["US"], manager))++ assert len(batches) == 1+ assert batches[0][0]["date"] == "2026-01-01"++ def test_public_holidays_rows_get_a_synthetic_id(self) -> None:+ manager = _make_manager()+ with (+ mock.patch(f"{MODULE}.make_tracked_session") as mock_session,+ mock.patch(f"{MODULE}._holiday_years", return_value=[2026]),+ ):+ mock_session.return_value.get.return_value = _response(+ 200, [{"countryCode": "US", "date": "2026-01-01", "name": "New Year's Day"}]+ )++ batches = list(nager_date_source(PUBLIC_HOLIDAYS, ["US"], manager))++ assert batches[0][0]["id"] == "US|2026-01-01|New Year's Day||"++ def test_next_public_holidays_requests_once_per_country(self) -> None:+ manager = _make_manager()+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(+ 200, [{"countryCode": "US", "date": "2026-09-07", "name": "Labour Day"}]+ )++ list(nager_date_source(NEXT_PUBLIC_HOLIDAYS, ["US"], manager))++ called_urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]++ assert called_urls == [f"{BASE_URL}/Holidays/US/Next"]++ def test_next_public_holidays_resumes_from_saved_index(self) -> None:+ manager = _make_manager(index=1)+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(+ 200, [{"countryCode": "GB", "date": "2026-12-25", "name": "Christmas Day"}]+ )++ batches = list(nager_date_source(NEXT_PUBLIC_HOLIDAYS, ["US", "GB"], manager))++ # The country before the saved index (US) is skipped entirely.+ assert len(batches) == 1+ called_urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert called_urls == [f"{BASE_URL}/Holidays/GB/Next"]++ def test_public_holidays_resumes_from_saved_index(self) -> None:+ manager = _make_manager(index=1)+ with (+ mock.patch(f"{MODULE}.make_tracked_session") as mock_session,+ mock.patch(f"{MODULE}._holiday_years", return_value=[2025, 2026]),+ ):+ mock_session.return_value.get.return_value = _response(+ 200, [{"countryCode": "US", "date": "2026-01-01", "name": "New Year's Day"}]+ )++ batches = list(nager_date_source(PUBLIC_HOLIDAYS, ["US"], manager))++ # The work item before the saved index (US/2025) is skipped entirely.+ assert len(batches) == 1+ called_urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]+ assert called_urls == [f"{BASE_URL}/Holidays/US/2026"]++ @parameterized.expand([(COUNTRY_INFO,), (NEXT_PUBLIC_HOLIDAYS,), (PUBLIC_HOLIDAYS,)])+ def test_raises_when_country_codes_are_misconfigured(self, endpoint: str) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session"):+ with pytest.raises(ValueError, match="Nager.Date source misconfigured"):+ list(nager_date_source(endpoint, [], _make_manager()))++ def test_unknown_endpoint_raises(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session"):+ with pytest.raises(ValueError, match="Unknown Nager.Date endpoint"):+ list(nager_date_source("NotARealEndpoint", ["US"], _make_manager()))+++class TestValidateCredentials:+ @parameterized.expand([(200, True), (404, False), (500, False)])+ def test_status_mapping(self, status: int, expected_valid: bool) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(status, {"countryCode": "US"})++ is_valid, _ = validate_credentials(["US"])++ assert is_valid is expected_valid++ def test_empty_codes_is_invalid_without_a_request(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ is_valid, message = validate_credentials([])++ assert is_valid is False+ assert message is not None+ mock_session.return_value.get.assert_not_called()++ def test_network_error_is_invalid(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = Exception("boom")++ is_valid, message = validate_credentials(["US"])++ assert is_valid is False+ assert message is not Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date_source.pynew file mode 100644index 000000000000..99365480bf5c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nager_date/tests/test_nager_date_source.py@@ -0,0 +1,158 @@+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++import structlog+from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.nagerdate import (+ NagerDateSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.nager_date import NagerDateResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.settings import ENDPOINTS, PRIMARY_KEYS+from products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.source import NagerDateSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(schema_name: str = "Countries") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=123,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestNagerDateSource:+ def setup_method(self) -> None:+ self.source = NagerDateSource()+ self.config = NagerDateSourceConfig(country_codes="US\nGB")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.NAGERDATE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "NagerDate"+ assert config.category == DataWarehouseSourceCategory.PRODUCTIVITY+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/nager-date"+ assert config.iconPath == "/static/services/nager_date.png"+ # A finished source ships visible; re-adding the flag would hide it from every user.+ assert not config.unreleasedSource++ def test_get_source_config_fields(self) -> None:+ fields = [field for field in self.source.get_source_config.fields if isinstance(field, SourceFieldInputConfig)]++ assert [field.name for field in fields] == ["country_codes"]+ assert fields[0].type == SourceFieldInputConfigType.TEXTAREA+ assert fields[0].required is True+ # The API is open, so nothing on this form is a credential.+ assert fields[0].secret is False++ def test_pinned_version_matches_the_path_the_code_calls(self) -> None:+ assert self.source.default_version == "v4"+ assert self.source.supported_versions == ("v4",)+ assert self.source.resolve_api_version(None) == "v4"++ def test_get_schemas(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=123)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ # No endpoint has a server-side "changed since" filter, so nothing may advertise+ # incremental or append sync.+ assert not any(schema.supports_incremental for schema in schemas)+ assert not any(schema.supports_append for schema in schemas)+ assert all(schema.description for schema in schemas)++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=123, names=["PublicHolidays"])++ assert [schema.name for schema in schemas] == ["PublicHolidays"]++ def test_documented_tables_render_without_credentials(self) -> None:+ # The public docs endpoint builds a blank config and calls get_schemas, so discovery must+ # do no I/O.+ tables = self.source.get_documented_tables()++ assert [table["name"] for table in tables] == list(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_every_endpoint_has_a_primary_key_and_canonical_descriptions(self, endpoint: str) -> None:+ assert PRIMARY_KEYS[endpoint]+ assert CANONICAL_DESCRIPTIONS[endpoint]["columns"]++ @parameterized.expand([("PublicHolidays",), ("NextPublicHolidays",)])+ def test_holiday_tables_key_on_the_synthetic_id(self, endpoint: str) -> None:+ # (countryCode, date, name) alone isn't unique: the same holiday can be split across+ # subdivisions with different classifications, so these tables key on the synthetic id+ # this source adds rather than the raw API fields.+ assert PRIMARY_KEYS[endpoint] == ["id"]++ def test_get_resumable_source_manager_is_bound_to_the_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is NagerDateResumeConfig++ def test_non_retryable_error_matches_a_misconfigured_country_list(self) -> None:+ raised = "Nager.Date source misconfigured: Enter at least one ISO 3166-1 alpha-2 country code, for example US."++ assert error_message_matches(raised, self.source.get_non_retryable_errors().keys())++ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_source_for_pipeline_plumbs_the_endpoint_through(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.source.nager_date_source"+ ) as mock_source:+ mock_source.return_value = iter([])+ response = self.source.source_for_pipeline(self.config, manager, _make_inputs(endpoint))+ list(cast(Iterable[Any], response.items()))++ assert response.name == endpoint+ assert response.primary_keys == PRIMARY_KEYS[endpoint]+ assert mock_source.call_args.kwargs["endpoint"] == endpoint+ assert mock_source.call_args.kwargs["country_codes"] == ["US", "GB"]++ @parameterized.expand(+ [+ ("US\nGB", ["US", "GB"]),+ ("", []),+ ]+ )+ def test_validate_credentials_parses_the_codes_before_probing(+ self, country_codes: str, expected_codes: list[str]+ ) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.nager_date.source.validate_nager_date_credentials"+ ) as mock_validate:+ mock_validate.return_value = (True, None)+ self.source.validate_credentials(NagerDateSourceConfig(country_codes=country_codes), team_id=123)++ assert mock_validate.call_args.args == (expected_codes,)