diff --git a/README.md b/README.md index 8c69200..9fabbc2 100644 --- a/README.md +++ b/README.md @@ -198,7 +198,7 @@ with Saturday(api_key="sk_test_...") as client: | Resource | Methods | |----------|---------| | `client.nutrition` | `calculate`, `batch_calculate`, `product_fit`, `compare_products`, `extract` | -| `client.athletes` | `create`, `get`, `list`, `update`, `delete`, `get_settings`, `update_settings`, `get_fueling_profile`, `batch_create`, `export`, `erase`, `list_consent`, `record_consent`, `revoke_consent` | +| `client.athletes` | `create`, `get`, `list`, `update`, `delete`, `get_settings`, `update_settings`, `get_fueling_profile`, `create_onboarding_link`, `batch_create`, `export`, `erase`, `list_consent`, `record_consent`, `revoke_consent` | | `client.activities` | `create`, `get`, `list`, `update`, `delete`, `calculate_prescription`, `get_prescription`, `prep`, `import_activities`, `submit_feedback` | | `client.onboarding` | `questions` | | `client.reference` | `activity_types`, `settings_schema` | diff --git a/saturday/client.py b/saturday/client.py index d8a35b1..3a0e12d 100644 --- a/saturday/client.py +++ b/saturday/client.py @@ -98,7 +98,7 @@ def _retry_safe_on_server_error(method: str, path: str) -> bool: def _seg(value: str) -> str: """Encode one path segment.""" text = str(value) - if text in (".", ".."): + if text in ("", ".", ".."): raise ValueError(f"Invalid path segment: {text!r}") return quote(text, safe="") @@ -225,7 +225,14 @@ def request( if response.is_success: if response.status_code == 204: return None - return response.content if raw else response.json() + if raw: + return response.content + try: + return response.json() + except ValueError: + raise SaturdayError( + message=f"Response was not valid JSON (HTTP {response.status_code})", + status=response.status_code, code="invalid_response") try: error_body = response.json() @@ -670,7 +677,7 @@ def delete_offer(self, org_id: str) -> None: def create_subscription(self, org_id: str, *, type: str, seats: int, start_date: int, end_date: int) -> OrganizationSubscription: """Create a seat subscription (dates in Unix seconds). Seat subscriptions are set up - with Saturday: without an allowance on your account this raises ``PermissionError`` + with Saturday: without an allowance on your account this raises ``PermissionDeniedError`` (``organization_subscription_restricted``).""" return self._client.request( "POST", f"/v1/organizations/{_seg(org_id)}/subscriptions", @@ -778,7 +785,7 @@ def health(self) -> HealthResponse: class _KnowledgeResource: - """Early access: a key without access gets ``PermissionError`` (``feature_alpha``).""" + """Early access: a key without access gets ``PermissionDeniedError`` (``feature_alpha``).""" def __init__(self, client: Saturday): self._client = client diff --git a/saturday/errors.py b/saturday/errors.py index af5b9ba..02a2951 100644 --- a/saturday/errors.py +++ b/saturday/errors.py @@ -102,15 +102,15 @@ def from_response(cls, status: int, error_body: Any, retry_after: Optional[str] if seconds is not None and float(seconds).is_integer(): seconds = int(seconds) if status in (400, 422): - return ValidationError(**kwargs) + return ValidationError(**kwargs, retry_after=seconds) if status == 401: - return AuthenticationError(**kwargs) + return AuthenticationError(**kwargs, retry_after=seconds) if status == 403: - return PermissionDeniedError(**kwargs) + return PermissionDeniedError(**kwargs, retry_after=seconds) if status == 404: - return NotFoundError(**kwargs) + return NotFoundError(**kwargs, retry_after=seconds) if status == 409: - return ConflictError(**kwargs) + return ConflictError(**kwargs, retry_after=seconds) if status == 429: return RateLimitError(**kwargs, retry_after=seconds) return cls(**kwargs, retry_after=seconds) diff --git a/tests/test_api_surface.py b/tests/test_api_surface.py new file mode 100644 index 0000000..1fd1a29 --- /dev/null +++ b/tests/test_api_surface.py @@ -0,0 +1,438 @@ +"""Every public resource method against a mocked HTTP layer (no network). + +Each case checks the request the method builds (method, path, query, body and +headers) and that a realistic response is returned untouched, as a plain dict +matching the TypedDict the method is annotated with. Response payloads come +from the recorded API responses in tests/fixtures/live.json and the backend +contract samples in tests/fixtures/contracts.json where one exists for the +method. Payloads marked CONSTRUCTED have no recorded or contract sample in +this repository: they are built from the field definitions in +saturday/types.py (or, for the untyped Dict returns, from the words of the +method's docstring), so for those the SDK-observable contract checked here is +the request shape plus dict passthrough. +""" + +import json +from pathlib import Path + +import httpx +import pytest + +import saturday.types as T +from saturday import Saturday, ValidationError +from saturday.client import SDK_VERSION +from test_contracts import matches + +FIXTURES = Path(__file__).with_name("fixtures") +LIVE = {name: entry["body"] for name, entry in json.loads(FIXTURES.joinpath("live.json").read_text()).items()} +CONTRACTS = json.loads(FIXTURES.joinpath("contracts.json").read_text()) + +# CONSTRUCTED from OrganizationSubscription in saturday/types.py (the live +# suite only records the 403 for create_subscription without an allowance). +ORG_SUBSCRIPTION = { + "id": "sub_1", "org_id": "org_1", "partner_id": "partner_example", "type": "team", + "seats": 10, "used_seats": 3, "status": "active", + "start_date": 1700000000, "end_date": 1730000000, "created_at": 1700000000, +} +# CONSTRUCTED from LicenseListResponse / License in saturday/types.py. +LICENSES = { + "licenses": [{"email": "sam@example.com", "added_at": 1700000000, "active": True, "athlete_id": "ath_1", "name": "Sam"}], + "total": 1, "request_id": "req_lic", +} +# CONSTRUCTED from IntegrationSyncResponse in saturday/types.py. +SYNCED = { + "result": {"provider": "intervals_icu", "status": "completed", "activities_found": 2, + "activities_synced": 2, "activities_skipped": 0, "prescription_tier": "full"}, + "request_id": "req_sync", +} +# CONSTRUCTED from IntegrationDisconnectResponse (its docstring gives the message). +DISCONNECTED = {"message": "Successfully disconnected intervals_icu", "provider": "intervals_icu", "request_id": "req_disc"} +# CONSTRUCTED: nutrition.extract, infer.* and knowledge.* return Dict and no +# response shape for them exists in this repository's docs, types or fixtures. +EXTRACTED = {"product_name": "Example Gel", "per_serving": {"carb_g": 25.0, "sodium_mg": 50.0, "fluid_ml": 0.0}} +INFERRED_TYPE = {"activity_type": "bike"} +INFERRED_BRICK = {"legs": [{"activity_type": "bike", "duration_min": 90}, {"activity_type": "run", "duration_min": 30}]} +KNOWLEDGE_SEARCH = {"results": [{"id": "art_1", "title": "Sodium basics"}]} +KNOWLEDGE_TOPICS = {"topics": [{"id": "hydration", "name": "Hydration"}]} +KNOWLEDGE_ARTICLE = {"id": "art_1", "title": "Sodium basics", "body": "Drink to thirst."} +# CONSTRUCTED coach payloads: the coach reads return Dict; shapes follow the +# keys and words of their docstrings in saturday/client.py. +COACH_ROSTER = {"athletes": [{"athlete_uid": "ath_1", "needs_attention": True}]} +COACH_DIGEST = {"athletes": [{"athlete_uid": "ath_1", "needs_attention": True}]} +COACH_ROLLUP = {"athlete_uid": "ath_1", "window": 7, "concerns": []} +COACH_REPORT = {"narrative": "Fueling is on plan.", "athlete_uid": "ath_1"} +COACH_SESSION = {"athlete_uid": "ath_1", "activity_id": "act_1"} +COACH_RULES = { + "notification_rules": {"under_fuel": {"enabled": True, "channels": ["email"], "cadence": "daily", "urgent_threshold": 0.8}}, + "hourly_cap": {"enabled": True, "per_hour": 1}, + "preset": "balanced", + "channel_config": {"email": "coach@example.com"}, +} +COACH_REPORT_SETTINGS = {"ai_report_window_days": 7, "ai_report_focus": "worst", "concern_carb_cutoff": 0.8} +COACH_WEBHOOKS = {"webhooks": [{"id": "cwh_1", "url": "https://example.com/hook", "events": ["concern.detected"], "active": True}]} +COACH_WEBHOOK_CREATED = {"id": "cwh_1", "url": "https://example.com/hook", "events": [], "secret": "cwhsec_example"} + +SESSION = {"intensity_level": 5, "thermal_stress_level": 5, "meal_before_min": 120, "is_race": False} +BRICK_LEGS = [ + {"activity_type": "bike", "duration_min": 90, "intensity_level": 6, "thermal_stress_level": 6}, + {"activity_type": "run", "duration_min": 30, "intensity_level": 7, "thermal_stress_level": 6}, +] + +# (id, call, method, path, query, json body, status, response, model name or None) +CASES = [ + # nutrition + ("calculate", lambda c: c.nutrition.calculate(athlete_id="ath_1", activity_type="run", duration_min=60, **SESSION), + "POST", "/v1/nutrition/calculate", {}, {"athlete_id": "ath_1", "activity_type": "run", "duration_min": 60, **SESSION}, + 200, LIVE["calculate_exact"], "NutritionCalculateResponse"), + ("calculate-brick", lambda c: c.nutrition.calculate(athlete_id="ath_1", activity_type="brick", legs=BRICK_LEGS, meal_before_min=120, is_race=False), + "POST", "/v1/nutrition/calculate", {}, {"athlete_id": "ath_1", "activity_type": "brick", "legs": BRICK_LEGS, "meal_before_min": 120, "is_race": False}, + 200, LIVE["calculate_brick"], "NutritionCalculateResponse"), + ("batch-calculate", lambda c: c.nutrition.batch_calculate([{"activity_type": "bike", "duration_min": 90}]), + "POST", "/v1/nutrition/calculate/batch", {}, {"scenarios": [{"activity_type": "bike", "duration_min": 90}]}, + 200, LIVE["calculate_batch"], "BatchCalculateResponse"), + ("batch-estimate", lambda c: c.nutrition.batch_calculate([{"activity_type": "bike", "duration_min": 90}], estimate_only=True), + "POST", "/v1/nutrition/calculate/batch", {}, {"scenarios": [{"activity_type": "bike", "duration_min": 90}], "estimate_only": True}, + 200, CONTRACTS["batch_estimate"], "BatchCalculateResponse"), + ("product-fit", lambda c: c.nutrition.product_fit(athlete_id="ath_1", product_query="maurten gel 100", activity_type="run", duration_min=90, **SESSION), + "POST", "/v1/nutrition/products/fit", {}, {"athlete_id": "ath_1", "product_query": "maurten gel 100", "activity_type": "run", "duration_min": 90, **SESSION}, + 200, LIVE["product_fit"], "ProductFitResponse"), + ("product-fit-brick", lambda c: c.nutrition.product_fit(athlete_id="ath_1", product_query="maurten gel 100", activity_type="brick", legs=BRICK_LEGS, meal_before_min=120, is_race=False), + "POST", "/v1/nutrition/products/fit", {}, {"athlete_id": "ath_1", "product_query": "maurten gel 100", "activity_type": "brick", "legs": BRICK_LEGS, "meal_before_min": 120, "is_race": False}, + 200, LIVE["product_fit_brick"], "ProductFitResponse"), + ("compare-products", lambda c: c.nutrition.compare_products(athlete_id="ath_1", product_a={"product_query": "maurten gel 100"}, product_b={"product_query": "tailwind endurance fuel"}, activity_type="bike", duration_min=180, **SESSION), + "POST", "/v1/nutrition/products/compare", {}, {"athlete_id": "ath_1", "product_a": {"product_query": "maurten gel 100"}, "product_b": {"product_query": "tailwind endurance fuel"}, "activity_type": "bike", "duration_min": 180, **SESSION}, + 200, LIVE["product_compare"], "ProductCompareResponse"), + ("extract", lambda c: c.nutrition.extract(image_base64="AA=="), + "POST", "/v1/nutrition/extract", {}, {"image_base64": "AA=="}, 200, EXTRACTED, None), + # athletes + ("athletes-create", lambda c: c.athletes.create(external_id="user-42", sex="female", year_of_birth=1990, weight_kg=62), + "POST", "/v1/athletes", {}, {"external_id": "user-42", "sex": "female", "year_of_birth": 1990, "weight_kg": 62}, + 201, LIVE["athlete"], "Athlete"), + ("athletes-get", lambda c: c.athletes.get("ath_1"), + "GET", "/v1/athletes/ath_1", {}, None, 200, CONTRACTS["athlete_sharing"], "Athlete"), + ("athletes-list", lambda c: c.athletes.list(), + "GET", "/v1/athletes", {"limit": "50"}, None, 200, LIVE["athlete_list"], "AthleteListResponse"), + ("athletes-update", lambda c: c.athletes.update("ath_1", name="Jo"), + "PATCH", "/v1/athletes/ath_1", {}, {"name": "Jo"}, 200, LIVE["athlete"], "Athlete"), + ("athletes-delete", lambda c: c.athletes.delete("ath_1"), + "DELETE", "/v1/athletes/ath_1", {}, None, 204, None, None), + ("athletes-get-settings", lambda c: c.athletes.get_settings("ath_1"), + "GET", "/v1/athletes/ath_1/settings", {}, None, 200, CONTRACTS["settings_full"], "AthleteSettings"), + ("athletes-update-settings", lambda c: c.athletes.update_settings("ath_1", sweat_level=7), + "PATCH", "/v1/athletes/ath_1/settings", {}, {"sweat_level": 7}, 200, CONTRACTS["settings_updated"], "AthleteSettings"), + ("athletes-get-fueling-profile", lambda c: c.athletes.get_fueling_profile("ath_1"), + "GET", "/v1/athletes/ath_1/fueling-profile", {}, None, 200, CONTRACTS["fueling_profile_on"], "FuelingProfile"), + ("athletes-create-onboarding-link", lambda c: c.athletes.create_onboarding_link("ath_1", locale="de"), + "POST", "/v1/athletes/ath_1/onboarding-link", {}, {"locale": "de"}, 200, CONTRACTS["onboarding_link"], "OnboardingLink"), + ("athletes-batch-create", lambda c: c.athletes.batch_create([{"external_id": "u-1"}]), + "POST", "/v1/athletes/batch", {}, {"athletes": [{"external_id": "u-1"}]}, 200, LIVE["athletes_batch"], "BatchAthleteResponse"), + ("athletes-export", lambda c: c.athletes.export("ath_1"), + "POST", "/v1/athletes/ath_1/export", {}, None, 200, LIVE["export"], "AthleteDataExport"), + ("athletes-erase", lambda c: c.athletes.erase("ath_1"), + "POST", "/v1/athletes/ath_1/delete", {}, None, 204, None, None), + ("athletes-list-consent", lambda c: c.athletes.list_consent("ath_1"), + "GET", "/v1/athletes/ath_1/consent", {}, None, 200, LIVE["consent_list"], "ConsentListResponse"), + ("athletes-record-consent", lambda c: c.athletes.record_consent("ath_1", consent_type="analytics", granted=True), + "POST", "/v1/athletes/ath_1/consent", {}, {"consent_type": "analytics", "granted": True}, 200, LIVE["consent"], "ConsentRecord"), + ("athletes-revoke-consent", lambda c: c.athletes.revoke_consent("ath_1", "con_1"), + "DELETE", "/v1/athletes/ath_1/consent/con_1", {}, None, 204, None, None), + # activities + ("activities-create", lambda c: c.activities.create("ath_1", type="bike", duration_min=150, intensity_level=6, thermal_stress_level=6, meal_before_min=120, is_race_event=False), + "POST", "/v1/athletes/ath_1/activities", {}, {"type": "bike", "duration_min": 150, "intensity_level": 6, "thermal_stress_level": 6, "meal_before_min": 120, "is_race_event": False}, + 201, LIVE["activity"], "Activity"), + ("activities-create-brick", lambda c: c.activities.create("ath_1", type="brick", legs=[{"type": "bike", "duration_min": 90, "intensity_level": 6, "thermal_stress_level": 6}, {"type": "run", "duration_min": 30, "intensity_level": 7, "thermal_stress_level": 6}], meal_before_min=120, is_race_event=False), + "POST", "/v1/athletes/ath_1/activities", {}, {"type": "brick", "legs": [{"type": "bike", "duration_min": 90, "intensity_level": 6, "thermal_stress_level": 6}, {"type": "run", "duration_min": 30, "intensity_level": 7, "thermal_stress_level": 6}], "meal_before_min": 120, "is_race_event": False}, + 201, LIVE["activity_brick"], "Activity"), + ("activities-get", lambda c: c.activities.get("ath_1", "act_1"), + "GET", "/v1/athletes/ath_1/activities/act_1", {}, None, 200, LIVE["activity"], "Activity"), + ("activities-list", lambda c: c.activities.list("ath_1"), + "GET", "/v1/athletes/ath_1/activities", {}, None, 200, LIVE["activity_list"], "ActivityListResponse"), + ("activities-update", lambda c: c.activities.update("ath_1", "act_1", duration_min=160), + "PATCH", "/v1/athletes/ath_1/activities/act_1", {}, {"duration_min": 160}, 200, LIVE["activity"], "Activity"), + ("activities-delete", lambda c: c.activities.delete("ath_1", "act_1"), + "DELETE", "/v1/athletes/ath_1/activities/act_1", {}, None, 204, None, None), + ("activities-calculate-prescription", lambda c: c.activities.calculate_prescription("ath_1", "act_1"), + "POST", "/v1/athletes/ath_1/activities/act_1/calculate", {}, None, 200, LIVE["activity_calculate"], "PrescriptionEnvelope"), + ("activities-get-prescription", lambda c: c.activities.get_prescription("ath_1", "act_1"), + "GET", "/v1/athletes/ath_1/activities/act_1/prescription", {}, None, 200, LIVE["activity_prescription"], "StoredPrescriptionResponse"), + ("activities-prep-products", lambda c: c.activities.prep("ath_1", "act_1", products=[{"product_query": "maurten gel 100", "servings": 2}]), + "POST", "/v1/athletes/ath_1/activities/act_1/prep", {}, {"products": [{"product_query": "maurten gel 100", "servings": 2}]}, + 200, LIVE["prep"], "PrepResponse"), + ("activities-prep-legs", lambda c: c.activities.prep("ath_1", "act_1", legs=[{"products": []}, {"products": [{"product_query": "maurten gel 100"}]}]), + "POST", "/v1/athletes/ath_1/activities/act_1/prep", {}, {"legs": [{"products": []}, {"products": [{"product_query": "maurten gel 100"}]}]}, + 200, LIVE["prep_brick_per_leg"], "PrepResponse"), + ("activities-prep-neither", lambda c: c.activities.prep("ath_1", "act_1"), + "POST", "/v1/athletes/ath_1/activities/act_1/prep", {}, {"products": []}, 200, LIVE["prep"], "PrepResponse"), + ("activities-import-activities", lambda c: c.activities.import_activities("ath_1", [{"type": "run", "duration_min": 45}], calculate=True), + "POST", "/v1/athletes/ath_1/activities/import", {}, {"activities": [{"type": "run", "duration_min": 45}], "calculate": True}, + 200, LIVE["activity_import"], "ActivityImportResponse"), + ("activities-submit-feedback-notes", lambda c: c.activities.submit_feedback("ath_1", "act_1", rating=4, notes="felt strong"), + "POST", "/v1/athletes/ath_1/activities/act_1/feedback", {}, {"rating": 4, "notes": "felt strong"}, + 200, LIVE["feedback"], "ActivityFeedback"), + # onboarding, reference, infer + ("onboarding-questions", lambda c: c.onboarding.questions(), + "GET", "/v1/onboarding/questions", {}, None, 200, LIVE["onboarding_questions"], "OnboardingQuestionsResponse"), + ("reference-activity-types", lambda c: c.reference.activity_types(), + "GET", "/v1/activity-types", {}, None, 200, LIVE["activity_types"], "ActivityTypesResponse"), + ("reference-activity-types-filtered", lambda c: c.reference.activity_types(activity_type="brick"), + "GET", "/v1/activity-types", {"activity_type": "brick"}, None, 200, LIVE["activity_types_filtered"], "ActivityTypesResponse"), + ("reference-settings-schema", lambda c: c.reference.settings_schema(), + "GET", "/v1/settings/schema", {}, None, 200, LIVE["settings_schema"], "SettingsSchemaResponse"), + ("infer-activity-type", lambda c: c.infer.activity_type(activity_name="Morning Ride", device="Garmin Edge 1040"), + "POST", "/v1/infer/activity-type", {}, {"activity_name": "Morning Ride", "device": "Garmin Edge 1040"}, 200, INFERRED_TYPE, None), + ("infer-brick-types", lambda c: c.infer.brick_types(activity_name="Brick session"), + "POST", "/v1/infer/brick-types", {}, {"activity_name": "Brick session"}, 200, INFERRED_BRICK, None), + # partner + ("partner-get", lambda c: c.partner.get(), + "GET", "/v1/partner", {}, None, 200, LIVE["partner"], "PartnerAccount"), + ("partner-usage", lambda c: c.partner.usage(from_date="2026-11-01", to_date="2026-11-07"), + "GET", "/v1/partner/usage", {"from": "2026-11-01", "to": "2026-11-07"}, None, 200, LIVE["usage"], "UsageResponse"), + ("partner-usage-daily", lambda c: c.partner.usage_daily(from_date="2026-11-01", to_date="2026-11-07"), + "GET", "/v1/partner/usage/daily", {"from": "2026-11-01", "to": "2026-11-07"}, None, 200, LIVE["usage_daily"], "DailyUsageResponse"), + ("partner-list-api-keys", lambda c: c.partner.list_api_keys(), + "GET", "/v1/partner/api-keys", {}, None, 200, LIVE["api_keys"], "ApiKeyListResponse"), + ("partner-create-api-key", lambda c: c.partner.create_api_key("ci"), + "POST", "/v1/partner/api-keys", {}, {"name": "ci"}, 201, LIVE["api_key_created"], "CreatedApiKey"), + ("partner-revoke-api-key", lambda c: c.partner.revoke_api_key("key_1"), + "DELETE", "/v1/partner/api-keys/key_1", {}, None, 204, None, None), + ("partner-rotate-api-key", lambda c: c.partner.rotate_api_key("key_1"), + "POST", "/v1/partner/api-keys/key_1/rotate", {}, None, 200, LIVE["api_key_rotated"], "RotatedApiKey"), + # webhooks + ("webhooks-create", lambda c: c.webhooks.create("https://example.com/saturday", ["athlete.created"]), + "POST", "/v1/webhooks", {}, {"url": "https://example.com/saturday", "events": ["athlete.created"]}, + 201, LIVE["webhook_created"], "WebhookCreateResponse"), + ("webhooks-list", lambda c: c.webhooks.list(), + "GET", "/v1/webhooks", {}, None, 200, LIVE["webhook_list"], "WebhookListResponse"), + ("webhooks-get", lambda c: c.webhooks.get("wh_1"), + "GET", "/v1/webhooks/wh_1", {}, None, 200, LIVE["webhook"], "Webhook"), + ("webhooks-update", lambda c: c.webhooks.update("wh_1", active=False), + "PATCH", "/v1/webhooks/wh_1", {}, {"active": False}, 200, LIVE["webhook"], "Webhook"), + ("webhooks-delete", lambda c: c.webhooks.delete("wh_1"), + "DELETE", "/v1/webhooks/wh_1", {}, None, 204, None, None), + ("webhooks-test", lambda c: c.webhooks.test("wh_1"), + "POST", "/v1/webhooks/wh_1/test", {}, None, 200, LIVE["webhook_test"], "WebhookTestResponse"), + ("webhooks-list-deliveries", lambda c: c.webhooks.list_deliveries("wh_1"), + "GET", "/v1/webhooks/wh_1/deliveries", {}, None, 200, LIVE["webhook_deliveries"], "WebhookDeliveryList"), + # organizations + ("organizations-create", lambda c: c.organizations.create("Riders", sport="triathlon"), + "POST", "/v1/organizations", {}, {"display_name": "Riders", "sport": "triathlon"}, 201, LIVE["organization"], "Organization"), + ("organizations-list", lambda c: c.organizations.list(), + "GET", "/v1/organizations", {}, None, 200, LIVE["organization_list"], "OrganizationListResponse"), + ("organizations-get", lambda c: c.organizations.get("org_1"), + "GET", "/v1/organizations/org_1", {}, None, 200, LIVE["organization"], "Organization"), + ("organizations-update", lambda c: c.organizations.update("org_1", description="Weekend riders"), + "PATCH", "/v1/organizations/org_1", {}, {"description": "Weekend riders"}, 200, LIVE["organization"], "Organization"), + ("organizations-add-member", lambda c: c.organizations.add_member("org_1", "sam@example.com", athlete_id="ath_1"), + "POST", "/v1/organizations/org_1/members", {}, {"email": "sam@example.com", "role": "member", "athlete_id": "ath_1"}, + 201, LIVE["organization_member"], "OrganizationMember"), + ("organizations-list-members", lambda c: c.organizations.list_members("org_1"), + "GET", "/v1/organizations/org_1/members", {}, None, 200, LIVE["organization_members"], "OrganizationMembersResponse"), + ("organizations-remove-member", lambda c: c.organizations.remove_member("org_1", "mem_1"), + "DELETE", "/v1/organizations/org_1/members/mem_1", {}, None, 204, None, None), + ("organizations-set-offer", lambda c: c.organizations.set_offer("org_1", discount_percent=10), + "PUT", "/v1/organizations/org_1/offer", {}, {"discount_percent": 10}, 200, LIVE["organization_offer"], "OrganizationOffer"), + ("organizations-get-offer", lambda c: c.organizations.get_offer("org_1"), + "GET", "/v1/organizations/org_1/offer", {}, None, 200, LIVE["organization_offer"], "OrganizationOffer"), + ("organizations-delete-offer", lambda c: c.organizations.delete_offer("org_1"), + "DELETE", "/v1/organizations/org_1/offer", {}, None, 204, None, None), + ("organizations-create-subscription", lambda c: c.organizations.create_subscription("org_1", type="team", seats=10, start_date=1700000000, end_date=1730000000), + "POST", "/v1/organizations/org_1/subscriptions", {}, {"type": "team", "seats": 10, "start_date": 1700000000, "end_date": 1730000000}, + 201, ORG_SUBSCRIPTION, "OrganizationSubscription"), + ("organizations-list-subscriptions", lambda c: c.organizations.list_subscriptions("org_1"), + "GET", "/v1/organizations/org_1/subscriptions", {}, None, 200, LIVE["organization_subscriptions"], "OrganizationSubscriptionListResponse"), + ("organizations-update-subscription", lambda c: c.organizations.update_subscription("org_1", "sub_1", seats=12), + "PATCH", "/v1/organizations/org_1/subscriptions/sub_1", {}, {"seats": 12}, 200, ORG_SUBSCRIPTION, "OrganizationSubscription"), + ("organizations-add-licenses", lambda c: c.organizations.add_licenses("org_1", "sub_1", [{"athlete_id": "ath_1", "email": "sam@example.com"}]), + "POST", "/v1/organizations/org_1/subscriptions/sub_1/licenses", {}, {"licenses": [{"athlete_id": "ath_1", "email": "sam@example.com"}]}, + 200, LICENSES, "LicenseListResponse"), + ("organizations-list-licenses", lambda c: c.organizations.list_licenses("org_1", "sub_1"), + "GET", "/v1/organizations/org_1/subscriptions/sub_1/licenses", {}, None, 200, LICENSES, "LicenseListResponse"), + ("organizations-remove-license", lambda c: c.organizations.remove_license("org_1", "sub_1", "ath_1"), + "DELETE", "/v1/organizations/org_1/subscriptions/sub_1/licenses/ath_1", {}, None, 204, None, None), + # integrations, testing, meta, knowledge + ("integrations-sync", lambda c: c.integrations.sync("intervals_icu", athlete_id="ath_1", access_token="tok"), + "POST", "/v1/integrations/intervals_icu/sync", {}, {"athlete_id": "ath_1", "access_token": "tok", "sync_types": ["activities"]}, + 200, SYNCED, "IntegrationSyncResponse"), + ("integrations-status", lambda c: c.integrations.status("intervals_icu", "ath_1"), + "GET", "/v1/integrations/intervals_icu/status", {"athlete_id": "ath_1"}, None, 200, LIVE["integration_status"], "IntegrationStatusResponse"), + ("integrations-disconnect", lambda c: c.integrations.disconnect("intervals_icu", "ath_1"), + "POST", "/v1/integrations/intervals_icu/disconnect", {}, {"athlete_id": "ath_1"}, 200, DISCONNECTED, "IntegrationDisconnectResponse"), + ("testing-simulate-subscription", lambda c: c.testing.simulate_subscription("ath_1"), + "POST", "/v1/test/athletes/ath_1/simulate-subscription", {}, {"active": True}, 200, LIVE["simulate_subscription"], "SimulateSubscriptionResponse"), + ("meta-discovery", lambda c: c.meta.discovery(), + "GET", "/v1/", {}, None, 200, LIVE["discovery"], "DiscoveryResponse"), + ("meta-errors", lambda c: c.meta.errors(), + "GET", "/v1/errors", {}, None, 200, LIVE["errors"], "ErrorCatalogResponse"), + ("meta-health", lambda c: c.meta.health(), + "GET", "/v1/health", {}, None, 200, LIVE["health"], "HealthResponse"), + ("knowledge-search", lambda c: c.knowledge.search("sodium", limit=5, category="hydration"), + "POST", "/v1/knowledge/search", {}, {"query": "sodium", "limit": 5, "category": "hydration"}, 200, KNOWLEDGE_SEARCH, None), + ("knowledge-list-topics", lambda c: c.knowledge.list_topics(), + "GET", "/v1/knowledge/topics", {}, None, 200, KNOWLEDGE_TOPICS, None), + ("knowledge-get-article", lambda c: c.knowledge.get_article("art_1"), + "GET", "/v1/knowledge/articles/art_1", {}, None, 200, KNOWLEDGE_ARTICLE, None), + # coach reads and config + ("coach-roster", lambda c: c.coach.roster(window=7), + "GET", "/v1/coach/roster", {"window": "7"}, None, 200, COACH_ROSTER, None), + ("coach-roster-digest", lambda c: c.coach.roster_digest(window=7), + "GET", "/v1/coach/roster/digest", {"window": "7"}, None, 200, COACH_DIGEST, None), + ("coach-fueling-rollup", lambda c: c.coach.fueling_rollup("ath_1", window=7, focus="worst"), + "GET", "/v1/coach/athletes/ath_1/fueling-rollup", {"window": "7", "focus": "worst"}, None, 200, COACH_ROLLUP, None), + ("coach-report", lambda c: c.coach.report("ath_1", window=14, focus="rolling", refresh=True), + "GET", "/v1/coach/athletes/ath_1/report", {"window": "14", "focus": "rolling", "refresh": "true"}, None, 200, COACH_REPORT, None), + ("coach-session-detail", lambda c: c.coach.session_detail("ath_1", "act_1"), + "GET", "/v1/coach/athletes/ath_1/sessions/act_1", {}, None, 200, COACH_SESSION, None), + ("coach-get-notification-rules", lambda c: c.coach.get_notification_rules(scope="overall"), + "GET", "/v1/coach/config/notification-rules", {"scope": "overall"}, None, 200, COACH_RULES, None), + ("coach-set-notification-rules", lambda c: c.coach.set_notification_rules("overall", COACH_RULES), + "PUT", "/v1/coach/config/notification-rules", {}, {"scope": "overall", "scope_id": None, "rules": COACH_RULES}, 200, COACH_RULES, None), + ("coach-apply-preset", lambda c: c.coach.apply_preset(scope="overall", preset="balanced"), + "POST", "/v1/coach/config/preset", {}, {"scope": "overall", "scope_id": None, "preset": "balanced"}, 200, COACH_RULES, None), + ("coach-get-report-settings", lambda c: c.coach.get_report_settings(scope="overall"), + "GET", "/v1/coach/config/report-settings", {"scope": "overall"}, None, 200, COACH_REPORT_SETTINGS, None), + ("coach-set-report-settings", lambda c: c.coach.set_report_settings("overall", COACH_REPORT_SETTINGS), + "PUT", "/v1/coach/config/report-settings", {}, {"scope": "overall", "scope_id": None, "settings": COACH_REPORT_SETTINGS}, 200, COACH_REPORT_SETTINGS, None), + ("coach-list-webhooks", lambda c: c.coach.list_webhooks(), + "GET", "/v1/coach/webhooks", {}, None, 200, COACH_WEBHOOKS, None), + ("coach-register-webhook", lambda c: c.coach.register_webhook("https://example.com/hook"), + "POST", "/v1/coach/webhooks", {}, {"url": "https://example.com/hook", "events": []}, 201, COACH_WEBHOOK_CREATED, None), + ("coach-delete-webhook", lambda c: c.coach.delete_webhook("cwh_1"), + "DELETE", "/v1/coach/webhooks/cwh_1", {}, None, 200, {"deleted": True}, None), + ("coach-disable-webhook", lambda c: c.coach.disable_webhook("cwh_1"), + "POST", "/v1/coach/webhooks/cwh_1/disable", {}, None, 200, {"id": "cwh_1", "active": False}, None), + ("coach-enable-webhook", lambda c: c.coach.enable_webhook("cwh_1"), + "POST", "/v1/coach/webhooks/cwh_1/enable", {}, None, 200, {"id": "cwh_1", "active": True}, None), + # coach billing (contract samples) + ("coach-seat-state", lambda c: c.coach.seat_state(), + "GET", "/v1/coach/billing/seat-state", {}, None, 200, CONTRACTS["billing_seat_state"], "CoachSeatState"), + ("coach-seat-state-pro", lambda c: c.coach.seat_state(org_id="org_1"), + "GET", "/v1/coach/billing/seat-state", {"org_id": "org_1"}, None, 200, CONTRACTS["billing_seat_state_pro"], "CoachSeatState"), + ("coach-ledger", lambda c: c.coach.ledger(view="inflows", limit=50, cursor="1749480000000"), + "GET", "/v1/coach/billing/ledger", {"view": "inflows", "limit": "50", "cursor": "1749480000000"}, None, 200, CONTRACTS["billing_ledger_page"], "CoachLedgerPage"), + ("coach-ledger-empty", lambda c: c.coach.ledger(), + "GET", "/v1/coach/billing/ledger", {}, None, 200, CONTRACTS["billing_ledger_empty"], "CoachLedgerPage"), + ("coach-tier-status", lambda c: c.coach.tier_status(), + "GET", "/v1/coach/billing/tier-status", {}, None, 200, CONTRACTS["billing_tier_status"], "CoachTierStatus"), + ("coach-tier-status-empty", lambda c: c.coach.tier_status(), + "GET", "/v1/coach/billing/tier-status", {}, None, 200, CONTRACTS["billing_tier_status_empty"], "CoachTierStatus"), + ("coach-connect-summary", lambda c: c.coach.connect_summary(), + "GET", "/v1/coach/billing/connect/summary", {}, None, 200, CONTRACTS["billing_connect_summary"], "CoachConnectSummary"), + ("coach-connect-summary-none", lambda c: c.coach.connect_summary(), + "GET", "/v1/coach/billing/connect/summary", {}, None, 200, CONTRACTS["billing_connect_summary_none"], "CoachConnectSummary"), + ("coach-connect-earnings", lambda c: c.coach.connect_earnings(), + "GET", "/v1/coach/billing/connect/earnings", {}, None, 200, CONTRACTS["billing_connect_earnings"], "CoachConnectEarnings"), + ("coach-connect-earnings-empty", lambda c: c.coach.connect_earnings(), + "GET", "/v1/coach/billing/connect/earnings", {}, None, 200, CONTRACTS["billing_connect_earnings_empty"], "CoachConnectEarnings"), + ("coach-connect-transactions", lambda c: c.coach.connect_transactions(limit=20, cursor="1749480000000"), + "GET", "/v1/coach/billing/connect/transactions", {"limit": "20", "cursor": "1749480000000"}, None, 200, CONTRACTS["billing_connect_transactions"], "CoachConnectChargesPage"), + ("coach-connect-transactions-end", lambda c: c.coach.connect_transactions(), + "GET", "/v1/coach/billing/connect/transactions", {}, None, 200, CONTRACTS["billing_connect_transactions_end"], "CoachConnectChargesPage"), + ("coach-connect-arrangements", lambda c: c.coach.connect_arrangements(), + "GET", "/v1/coach/billing/connect/arrangements", {}, None, 200, CONTRACTS["billing_connect_arrangements"], "CoachConnectArrangements"), +] + + +def _client(handler): + client = Saturday(api_key="sk_test_fake", max_retries=0) + headers = client._client.headers + client._client.close() + client._client = httpx.Client(base_url=client._base_url, headers=headers, transport=httpx.MockTransport(handler)) + return client + + +@pytest.mark.parametrize("case_id, call, method, path, query, body, status, response, model", + CASES, ids=[case[0] for case in CASES]) +def test_method_builds_request_and_parses_response(case_id, call, method, path, query, body, status, response, model): + seen = [] + + def handler(request): + seen.append(request) + if status == 204: + return httpx.Response(204) + return httpx.Response(status, json=response) + + with _client(handler) as client: + result = call(client) + + assert len(seen) == 1 + (request,) = seen + assert request.method == method + assert request.url.path == path + assert dict(request.url.params) == query + assert (json.loads(request.content) if request.content else None) == body + assert request.headers["Authorization"] == "Bearer " + "sk_test_fake" + assert request.headers["User-Agent"] == f"saturday-python/{SDK_VERSION}" + assert request.headers["X-SDK-Version"] == SDK_VERSION + assert request.headers["Content-Type"] == "application/json" + + if status == 204: + assert result is None + return + assert type(result) is dict + assert result == response + if model is not None: + assert matches(result, getattr(T, model)), f"{case_id} response does not match {model}" + + +def test_case_table_covers_every_resource_method(): + """The case ids name every public resource method: a method added to the + client without a case here fails this test.""" + import inspect + + client = Saturday(api_key="sk_test_fake") + try: + resources = { + "nutrition": client.nutrition, "athletes": client.athletes, "activities": client.activities, + "onboarding": client.onboarding, "reference": client.reference, "infer": client.infer, + "partner": client.partner, "webhooks": client.webhooks, "organizations": client.organizations, + "integrations": client.integrations, "testing": client.testing, "meta": client.meta, + "knowledge": client.knowledge, "coach": client.coach, + } + # coach.report_pdf returns bytes: its case is the separate test below. + covered = {case[0] for case in CASES} | {"coach-report-pdf"} + missing = [] + for resource_name, resource in resources.items(): + for name, member in inspect.getmembers(resource, predicate=inspect.ismethod): + if name.startswith("_"): + continue + # A method is covered when some case id ends with its name in + # kebab form (variants share the method's id as a prefix). + kebab = name.replace("_", "-") + if not any(cid == f"{resource_name}-{kebab}" or cid.startswith(f"{resource_name}-{kebab}-") + or cid == kebab or cid.startswith(f"{kebab}-") for cid in covered): + missing.append(f"{resource_name}.{name}") + assert missing == [], f"no surface case for: {missing}" + finally: + client.close() + + +def test_prep_with_both_products_and_legs_sends_both_and_surfaces_the_refusal(): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(400, json={"error": {"type": "invalid_request", "code": "invalid_value", + "param": "products", "message": "Send only one of products and legs."}}) + + with _client(handler) as client: + with pytest.raises(ValidationError) as raised: + client.activities.prep("ath_1", "act_1", products=[{"product_id": "p1"}], legs=[{"products": []}]) + assert (raised.value.code, raised.value.param) == ("invalid_value", "products") + assert json.loads(seen[0].content) == {"legs": [{"products": []}], "products": [{"product_id": "p1"}]} + + +def test_report_pdf_sends_format_and_returns_bytes(): + pdf = b"%PDF-1.7\nreport" + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(200, content=pdf, headers={"Content-Type": "application/pdf"}) + + with _client(handler) as client: + assert client.coach.report_pdf("ath_1", window=7, focus="worst") == pdf + assert seen[0].method == "GET" + assert seen[0].url.path == "/v1/coach/athletes/ath_1/report" + assert dict(seen[0].url.params) == {"window": "7", "focus": "worst", "format": "pdf"} + assert seen[0].headers["Authorization"] == "Bearer " + "sk_test_fake" + diff --git a/tests/test_bugfixes.py b/tests/test_bugfixes.py new file mode 100644 index 0000000..1e061ea --- /dev/null +++ b/tests/test_bugfixes.py @@ -0,0 +1,151 @@ +"""Regression tests for bugs found by auditing the client against its docs. + +Each test here failed against the code as found; the paired fix keeps the +public API unchanged. The bug each test pins is stated in its docstring. +""" + +import re +from pathlib import Path + +import httpx +import pytest + +from saturday import ( + AuthenticationError, ConflictError, NotFoundError, PermissionDeniedError, + RateLimitError, Saturday, SaturdayError, ValidationError, +) + + +def _client(handler, **options): + client = Saturday(api_key="sk_test_fake", **options) + headers = client._client.headers + client._client.close() + client._client = httpx.Client(base_url=client._base_url, headers=headers, + transport=httpx.MockTransport(handler)) + return client + + +@pytest.mark.parametrize("body", [b"not JSON", b""]) +def test_non_json_success_body_raises_saturday_error(body): + """Bug: a 200 whose body is not JSON (or is empty) raised + json.JSONDecodeError out of request(), not a SaturdayError, so callers + catching the SDK's documented error type missed it.""" + client = _client(lambda _: httpx.Response(200, content=body), max_retries=0) + with pytest.raises(SaturdayError) as raised: + client.onboarding.questions() + assert (raised.value.status, raised.value.code) == (200, "invalid_response") + + +def test_raw_success_body_is_returned_without_json_parsing(): + """The raw path (coach.report_pdf) keeps returning bytes untouched.""" + client = _client(lambda _: httpx.Response(200, content=b"not JSON"), max_retries=0) + assert client.request("GET", "/v1/health", raw=True) == b"not JSON" + + +@pytest.mark.parametrize("status, klass", [ + (400, ValidationError), (401, AuthenticationError), (403, PermissionDeniedError), + (404, NotFoundError), (409, ConflictError), (422, ValidationError), +]) +def test_retry_after_is_kept_on_typed_errors(status, klass): + """Bug: SaturdayError.from_response computed Retry-After for every status + but passed it only to RateLimitError and the untyped 5xx class, so a typed + 4xx that carried the header reported retry_after None. The changelog + promises retry_after "from Retry-After on any error that carries one".""" + client = _client(lambda _: httpx.Response(status, json={"error": {"message": "Refused"}}, + headers={"Retry-After": "9"}), max_retries=0) + with pytest.raises(klass) as raised: + client.onboarding.questions() + assert raised.value.retry_after == 9 + + +@pytest.mark.parametrize("call", [ + lambda c: c.athletes.get(""), + lambda c: c.activities.get("ath_1", ""), + lambda c: c.knowledge.get_article(""), + lambda c: c.coach.delete_webhook(""), + lambda c: c.integrations.status("", "ath_1"), +]) +def test_empty_path_segment_is_rejected_before_any_request(call): + """Bug: _seg rejected "." and ".." for reaching another route but encoded + "" to "", so athletes.get("") requested GET /v1/athletes/ (the collection + route) instead of failing locally like its dot-segment siblings.""" + client = _client(lambda _: pytest.fail("no request should be sent"), max_retries=0) + with pytest.raises(ValueError, match="Invalid path segment"): + call(client) + + +def test_permission_denial_on_subscription_and_knowledge(): + """The 403 class is PermissionDeniedError on these routes too (their + docstrings once named the builtin PermissionError instead).""" + forbidden = lambda _: httpx.Response( # noqa: E731 + 403, json={"error": {"type": "authorization_error", "code": "feature_alpha", "message": "Closed."}}) + client = _client(forbidden, max_retries=0) + with pytest.raises(PermissionDeniedError): + client.knowledge.list_topics() + restricted = lambda _: httpx.Response( # noqa: E731 + 403, json={"error": {"type": "authorization_error", "code": "organization_subscription_restricted", + "message": "Seat subscriptions are set up with Saturday."}}) + client = _client(restricted, max_retries=0) + with pytest.raises(PermissionDeniedError) as raised: + client.organizations.create_subscription("org_1", type="team", seats=5, start_date=1, end_date=2) + assert raised.value.code == "organization_subscription_restricted" + + +def test_docstrings_name_permission_denied_error(): + """Bug: organizations.create_subscription and the knowledge resource + docstrings said the refusal raises PermissionError. Nothing in the SDK + raises the builtin; a caller catching it would never see the 403.""" + for source in (Path(__file__).parent.parent / "saturday").glob("*.py"): + assert "PermissionError" not in source.read_text(), source.name + + +def test_readme_resource_table_lists_every_method(): + """Bug: the README's athlete row omitted create_onboarding_link, a public + method added in 0.9.0. Every non-coach row must name exactly the + resource's public methods (the coach row is a prose summary).""" + import inspect + + readme = (Path(__file__).parent.parent / "README.md").read_text() + rows = {} + for line in readme.splitlines(): + match = re.match(r"\| `client\.(\w+)` \| (.*) \|$", line) + if match: + rows[match.group(1)] = set(re.findall(r"`([a-z_]+)`", match.group(2))) + client = Saturday(api_key="sk_test_fake") + try: + for name in ("nutrition", "athletes", "activities", "onboarding", "reference", "infer", "partner", + "webhooks", "organizations", "integrations", "testing", "meta", "knowledge"): + actual = {m for m, _ in inspect.getmembers(getattr(client, name), predicate=inspect.ismethod) + if not m.startswith("_")} + assert rows[name] == actual, f"README row for {name}: table {sorted(rows[name])} != client {sorted(actual)}" + finally: + client.close() + + +@pytest.mark.parametrize("timeout", ["30", True]) +def test_timeout_must_be_a_number(timeout): + """A timeout of the wrong type raises the same ValueError as an + out-of-range one (the type branch of the constructor check).""" + with pytest.raises(ValueError, match="timeout"): + Saturday(api_key="sk_test_fake", timeout=timeout) + + +def test_retry_after_date_parser_returning_none_is_absent(monkeypatch): + """parsedate_to_datetime raises on unparseable dates since Python 3.10, + so from_response's None guard is unreachable with the stdlib parser on + supported interpreters. Patch the parser to return None and check the + guard still reports no wait rather than crashing.""" + monkeypatch.setattr("saturday.errors.parsedate_to_datetime", lambda _: None) + error = SaturdayError.from_response( + 429, {"error": {"code": "rate_limit_exceeded", "message": "Slow"}}, "whenever") + assert error.retry_after is None + + +def test_retry_after_http_date_without_timezone_is_read_as_utc(): + """An HTTP-date Retry-After with the -0000 zone parses to a naive + datetime; the parser reads it as UTC rather than dropping it.""" + client = _client(lambda _: httpx.Response(429, json={"error": {"code": "rate_limited", "message": "Wait"}}, + headers={"Retry-After": "Wed, 21 Oct 2099 07:28:00 -0000"}), max_retries=0) + with pytest.raises(RateLimitError) as raised: + client.onboarding.questions() + assert raised.value.retry_after is not None and raised.value.retry_after > 0 diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 0000000..315ccab --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,155 @@ +"""Every exported model in saturday.types has a realistic instance checked +against it. + +Top-level response models are already checked in test_contracts (backend +contract samples), test_live_types (recorded live responses) and +test_live_shapes. This file covers the rest: nested models are extracted from +those same recorded or contract payloads at the path where the API puts them, +and the handful with no instance anywhere in the fixtures are built from the +field definitions in saturday/types.py and marked CONSTRUCTED. Literal +aliases check that each documented value matches and a bogus one does not. +A model added to saturday.__all__ without an instance here or in those files +fails test_every_exported_model_is_covered. +""" + +import json +from pathlib import Path +from typing import Literal, get_args, get_origin + +import pytest + +import saturday +import saturday.types as T +from test_contracts import MODELS, matches +from test_live_shapes import SHAPES + +FIXTURES = Path(__file__).with_name("fixtures") +CONTRACTS = json.loads(FIXTURES.joinpath("contracts.json").read_text()) +LIVE = {name: entry["body"] for name, entry in json.loads(FIXTURES.joinpath("live.json").read_text()).items()} +LIVE_TYPES = {entry["type"] for entry in json.loads(FIXTURES.joinpath("live.json").read_text()).values()} + +PROFILE = CONTRACTS["fueling_profile_on"]["profile"] +TRIAL = {k: CONTRACTS["nutrition_trial"][k] for k in ("tier_source", "trial_ends_at", "trial_calls_remaining_today")} +BATCH_SUMMARY = {k: CONTRACTS["batch_partial"][k] for k in ("total", "succeeded", "failed", "request_id", "errors")} + +# model name -> a realistic instance, extracted from the fixtures above. +INSTANCES = { + "ActivityLeg": LIVE["activity_brick"]["legs"][0], + "ActivityTypeInfo": LIVE["activity_types"]["activity_types"][0], + "ApiKeyInfo": LIVE["api_keys"]["api_keys"][0], + "Attribution": CONTRACTS["activity_full"]["attribution"], + "BandImpact": CONTRACTS["activity_full_banded"]["precision"]["missing_fields"][0]["band_impact"], + "BatchError": CONTRACTS["batch_partial"]["errors"][0], + "BatchSummary": BATCH_SUMMARY, + "CoachBillingArrangement": CONTRACTS["billing_connect_arrangements"]["arrangements"][0], + "CoachChargeBreakdown": CONTRACTS["billing_connect_earnings"]["breakdowns"][0], + "CoachConnectAccount": CONTRACTS["billing_connect_summary"]["connect_account"], + "CoachConnectCharge": CONTRACTS["billing_connect_transactions"]["charges"][0], + "CoachEarningsSummary": CONTRACTS["billing_connect_earnings"]["summary"], + "CoachLedgerEntry": CONTRACTS["billing_ledger_page"]["entries"][0], + "CoachSubscriptionStatus": CONTRACTS["billing_tier_status"]["status"], + "CoachTierSubscription": CONTRACTS["billing_tier_status"]["subscriptions"][0], + "ComparisonWinner": LIVE["product_compare"]["winner"], + "CoveragePct": LIVE["prep"]["coverage_pct"], + "DailyUsage": LIVE["usage"]["daily"][0], + "DiscoveryKeyInfo": LIVE["discovery"]["get_a_key"], + "ErrorCatalogEntry": LIVE["errors"]["errors"][0], + "FuelingConcerns": PROFILE["concerns"]["value"], + "FuelingProfileAnswers": PROFILE, + "FuelingProfileCarbExperience": PROFILE["carb_experience"], + "FuelingProfileConcerns": PROFILE["concerns"], + "FuelingProfileInt": PROFILE["age"], + "FuelingProfileSex": PROFILE["sex"], + "FuelingProfileUpdatedData": CONTRACTS["webhook_fueling_profile_updated"]["data"], + "FuelingProfileUsualCarb": PROFILE["usual_carb_consumption"], + "FuelingProfileWeight": PROFILE["athlete_weight_kg"], + "GapAmounts": LIVE["product_fit"]["fit"]["remaining_gap"], + "ImportPrescriptionItem": CONTRACTS["import_calculated"]["prescriptions"][0], + "IntegrationStatusDetail": LIVE["integration_status"]["status"], + "LegPrescription": LIVE["calculate_brick"]["legs"][0], + "LinkedSessionTypeInfo": LIVE["activity_types"]["linked_session_types"][0], + "MissingField": CONTRACTS["activity_full_banded"]["precision"]["missing_fields"][0], + "NutrientAmounts": LIVE["prep"]["prescription"], + "OnboardingInvite": CONTRACTS["activity_full_banded"]["precision"]["onboarding"], + "OnboardingOption": LIVE["onboarding_questions"]["questions"][0]["options"][0], + "OnboardingQuestion": LIVE["onboarding_questions"]["questions"][0], + "PaginationMeta": CONTRACTS["list_athletes_next"]["pagination"], + "PartnerRateLimits": LIVE["partner"]["rate_limits"], + "PerServing": LIVE["product_fit"]["fit"]["per_serving"], + "PlanBasis": LIVE["product_fit_plan_basis"]["plan_basis"], + "Precision": CONTRACTS["activity_full_banded"]["precision"], + "PrepLeg": LIVE["prep_brick"]["legs"][0], + "PrepProduct": LIVE["prep"]["products"][0], + "ProductCompareLeg": LIVE["product_compare_triathlon"]["legs"][0], + "ProductFitDetail": LIVE["product_fit"]["fit"], + "ProductFitLeg": LIVE["product_fit_brick"]["legs"][0], + "SafetyMetadata": CONTRACTS["activity_full"]["safety"], + "SettingsFieldSchema": LIVE["settings_schema"]["settings"][0], + "SubscriptionCTA": CONTRACTS["nutrition_teaser"]["subscription_cta"], + "TrialMetadata": TRIAL, + "UsagePeriod": LIVE["usage"]["period"], + "WebhookDelivery": LIVE["webhook_test"]["delivery"], + "WebhookEvent": CONTRACTS["webhook_profile_sharing_changed"], + "WebhookWithSecret": LIVE["webhook_created"]["webhook"], + # Request-side models: the examples the README and live suite send. + "CalculateLeg": {"activity_type": "bike", "duration_min": 90, "intensity_level": 6, "thermal_stress_level": 6}, + "ImportActivityRequest": {"type": "run", "duration_min": 45, "intensity_level": 5, + "meal_before_min": 120, "is_race_event": False, "external_id": "partner-act"}, + # CONSTRUCTED from saturday/types.py: no fixture in this repository + # contains an instance (no recorded prep answer carries gear, no product + # teaser with categories was recorded, and no sync, seat subscription or + # license response was recorded). + "GearItem": {"id": "gear_1", "name": "Soft flask", "type": "flask", "capacity_ml": 500, + "is_default": True, "created_at": 1700000000, "updated_at": 1700000000}, + "ProductCategory": {"id": "gels", "name": "Gels", "description": "Energy gels"}, + "License": {"email": "sam@example.com", "added_at": 1700000000, "active": True, "athlete_id": "ath_1", "name": "Sam"}, + "LicenseListResponse": {"licenses": [{"email": "sam@example.com", "added_at": 1700000000, "active": True}], + "total": 1, "request_id": "req_lic"}, + "OrganizationSubscription": {"id": "sub_1", "org_id": "org_1", "partner_id": "partner_example", "type": "team", + "seats": 10, "used_seats": 3, "status": "active", "start_date": 1700000000, + "end_date": 1730000000, "created_at": 1700000000}, + "IntegrationSyncResult": {"provider": "intervals_icu", "status": "completed", "activities_found": 2, + "activities_synced": 2, "activities_skipped": 0, "prescription_tier": "full"}, + "IntegrationSyncResponse": {"result": {"provider": "intervals_icu", "status": "completed", "activities_found": 2, + "activities_synced": 2, "activities_skipped": 0}, "request_id": "req_sync"}, + "IntegrationDisconnectResponse": {"message": "Successfully disconnected intervals_icu", + "provider": "intervals_icu", "request_id": "req_disc"}, +} + +NON_MODELS = { + "Saturday", "SaturdayError", "AuthenticationError", "PermissionDeniedError", "RateLimitError", + "ValidationError", "NotFoundError", "ConflictError", "DAILY_LIMIT_CODES", "MAX_RETRY_WAIT_SECONDS", +} +EXPORTED_MODELS = [name for name in saturday.__all__ if name not in NON_MODELS] +LITERALS = [name for name in EXPORTED_MODELS if get_origin(getattr(T, name)) is Literal] +TYPED_DICTS = [name for name in EXPORTED_MODELS if name not in LITERALS] +ALREADY_CHECKED = set(MODELS.values()) | LIVE_TYPES | set(SHAPES) + + +def test_every_exported_model_is_covered(): + covered = ALREADY_CHECKED | set(INSTANCES) | set(LITERALS) + assert set(EXPORTED_MODELS) <= covered, f"no instance checked for: {sorted(set(EXPORTED_MODELS) - covered)}" + assert set(INSTANCES) <= set(EXPORTED_MODELS), f"instances for unexported names: {sorted(set(INSTANCES) - set(EXPORTED_MODELS))}" + + +@pytest.mark.parametrize("name", sorted(INSTANCES)) +def test_model_instance_matches_its_typed_dict(name): + model = getattr(T, name) + instance = INSTANCES[name] + assert isinstance(instance, dict) and instance, name + assert matches(instance, model), f"{name} instance does not match its TypedDict" + assert model(**instance) == instance + assert type(model(**instance)) is dict + + +@pytest.mark.parametrize("name", sorted(LITERALS)) +def test_literal_alias_takes_its_documented_values_only(name): + alias = getattr(T, name) + for value in get_args(alias): + assert matches(value, alias), f"{name} should take {value!r}" + assert not matches("__bogus__", alias), f"{name} should refuse a bogus value" + + +def test_exported_models_are_typed_dicts_or_literals(): + for name in TYPED_DICTS: + assert hasattr(getattr(T, name), "__required_keys__"), f"{name} is neither a TypedDict nor a Literal alias" diff --git a/tests/test_readme.py b/tests/test_readme.py index 8e67716..4edfbd6 100644 --- a/tests/test_readme.py +++ b/tests/test_readme.py @@ -1,10 +1,38 @@ from pathlib import Path +import inspect import json import re +import textwrap import httpx import pytest +import saturday + +FIXTURES = Path(__file__).with_name("fixtures") +LIVE = {name: entry["body"] for name, entry in json.loads(FIXTURES.joinpath("live.json").read_text()).items()} +CONTRACTS = json.loads(FIXTURES.joinpath("contracts.json").read_text()) +README = (Path(__file__).parents[1] / "README.md").read_text() +BLOCKS = re.findall(r"```python\n(.*?)```", README, re.S) + + +def _block(marker): + return next(code for code in BLOCKS if marker in code) + + +def _run(monkeypatch, code, route, filename, namespace=None): + """Execute an example with httpx.Client.send routed to ``route``.""" + seen = [] + + def send(client, request, **kwargs): + seen.append(request) + return route(request) + + monkeypatch.setattr(httpx.Client, "send", send) + namespace = {} if namespace is None else namespace + exec(compile(code, filename, "exec"), namespace) + return namespace, seen + ATHLETE = {"id": "ath_1", "partner_id": "partner_example", "settings": {}, "profile_complete": True, "created_at": 1, "updated_at": 1} @@ -63,3 +91,215 @@ def send(client, request, **kwargs): code = next(code for code in re.findall(r"```python\n(.*?)```", readme, re.S) if "get_fueling_profile" in code) exec(compile(code, "README.md fueling profile", "exec"), {}) assert capsys.readouterr().out.splitlines() == [expected] + + +def test_every_readme_block_has_an_executing_test(): + """Each python block in the README is run by a test in this file: the + markers below are the substrings those tests select their block by, plus + the quickstart (first block) and fueling profile tests above.""" + markers = ["Still needed:", "brick.get", "except ConflictError", "signing_secret", + "hourly_cap", "except RateLimitError", "delegated =", "get_fueling_profile"] + covered = {0} + for marker in markers: + covered |= {i for i, code in enumerate(BLOCKS) if marker in code} + assert covered == set(range(len(BLOCKS))), f"README blocks not executed by any test: {sorted(set(range(len(BLOCKS))) - covered)}" + + +def _json(request, payload, status=200): + return httpx.Response(status, json=payload, request=request) + + +def test_readme_prep_and_product_fit(monkeypatch, capsys): + def route(request): + path = request.url.path + if path == "/v1/nutrition/products/fit": + body = json.loads(request.content) + return _json(request, LIVE["product_fit_brick"] if body.get("activity_type") == "brick" else LIVE["product_fit"]) + if path.endswith("/calculate"): + return _json(request, LIVE["activity_calculate"]) + if path.endswith("/prep"): + return _json(request, LIVE["prep"]) + assert path == "/v1/athletes/ATHLETE_ID/activities", path + return _json(request, LIVE["activity"], 201) + + _, seen = _run(monkeypatch, _block("Still needed:"), route, "README.md prep and product fit") + + created = json.loads(seen[0].content) + assert created == {"type": "bike", "duration_min": 150, "intensity_level": 6, "thermal_stress_level": 6, + "meal_before_min": 120, "is_race_event": False} + prep = LIVE["prep"] + expected = [f"{p['servings']} x {p['product_name']}" for p in prep["products"]] + expected.append(f"Still needed: {prep['remaining_gap']}") + expected.append(LIVE["product_fit"]["fit"]["verdict"]) + expected += [f"{leg['activity_type']}: {leg['fit']['max_servings']} servings" + for leg in LIVE["product_fit_brick"]["legs"]] + assert capsys.readouterr().out.splitlines() == expected + + +def test_readme_bricks_and_triathlons(monkeypatch, capsys): + def route(request): + path = request.url.path + if path == "/v1/nutrition/calculate": + return _json(request, LIVE["calculate_brick"]) + if path.endswith("/calculate"): + return _json(request, LIVE["activity_calculate_brick"]) + if path.endswith("/prep"): + return _json(request, LIVE["prep_brick_per_leg"]) + assert path == "/v1/athletes/ATHLETE_ID/activities", path + return _json(request, LIVE["activity_brick"], 201) + + _run(monkeypatch, _block("brick.get"), route, "README.md bricks and triathlons") + + expected = [f"{leg['duration_min']} min: {leg['total_carb_g']} g carbs" for leg in LIVE["calculate_brick"]["legs"]] + expected.append(str(LIVE["activity_calculate_brick"]["prescription"]["legs"])) + expected += [f"{leg['activity_type']} {len(leg['products'])} {leg['remaining_gap']}" + for leg in LIVE["prep_brick_per_leg"]["legs"]] + assert capsys.readouterr().out.splitlines() == expected + + +def test_readme_external_id_conflict(monkeypatch, capsys): + athlete = LIVE["athlete"] + + def route(request): + if request.method == "POST": + return _json(request, {"error": {"type": "invalid_request", "code": "athlete_exists", + "athlete_id": athlete["id"], + "message": 'An athlete with external_id "user-42" already exists.'}}, 409) + assert request.url.path == f"/v1/athletes/{athlete['id']}" + return _json(request, athlete) + + namespace, _ = _run(monkeypatch, _block("except ConflictError"), route, "README.md external id") + assert namespace["athlete"] == athlete + assert capsys.readouterr().out.splitlines() == [athlete["id"]] + + +def test_readme_webhooks(monkeypatch, capsys): + def route(request): + if request.url.path.endswith("/test"): + return _json(request, LIVE["webhook_test"]) + assert request.url.path == "/v1/webhooks" + return _json(request, LIVE["webhook_created"], 201) + + namespace, _ = _run(monkeypatch, _block("signing_secret"), route, "README.md webhooks") + assert namespace["signing_secret"] == LIVE["webhook_created"]["webhook"]["secret"] + delivery = LIVE["webhook_test"]["delivery"] + assert capsys.readouterr().out.splitlines() == [f"{delivery['status']} {delivery['status_code']}"] + + +def test_readme_coach_alert_rules(monkeypatch): + from test_api_surface import COACH_RULES + + def route(request): + assert request.url.path == "/v1/coach/config/notification-rules" + if request.method == "GET": + assert dict(request.url.params) == {"scope": "overall"} + return _json(request, COACH_RULES) + return _json(request, COACH_RULES) + + _, seen = _run(monkeypatch, _block("hourly_cap"), route, "README.md coach alert rules") + assert json.loads(seen[1].content) == { + "scope": "overall", "scope_id": None, + "rules": {**COACH_RULES, "hourly_cap": {"enabled": True, "per_hour": 2}}, + } + + +@pytest.mark.parametrize("status, error_body, headers, check", [ + (429, {"type": "rate_limit_error", "code": "daily_call_limit_reached", "message": "Daily call limit reached."}, {}, + lambda line: re.fullmatch(r"daily_call_limit_reached: resets at \d{4}-\d{2}-\d{2}T00:00:00\+00:00", line)), + (429, {"type": "rate_limit_error", "code": "rate_limited", "message": "Blocked."}, {"Retry-After": "5"}, + lambda line: line == "rate_limited: try again in 5 s"), + (400, {"type": "invalid_request", "code": "unsupported_field", "param": "is_rac", + "message": '"is_rac" is not a field of this request. Did you mean "is_race"?'}, {}, + lambda line: line == "is_rac is not a field of this request; send is_race"), + (400, {"type": "invalid_request", "code": "invalid_value", "param": "duration_min", + "message": "duration_min is out of range"}, {}, + lambda line: line == "Fix duration_min: duration_min is out of range"), +], ids=["daily-limit", "blocked", "unsupported-field", "invalid-value"]) +def test_readme_errors(monkeypatch, capsys, status, error_body, headers, check): + def route(request): + return httpx.Response(status, json={"error": error_body}, headers=headers, request=request) + + _run(monkeypatch, _block("except RateLimitError"), route, "README.md errors") + (line,) = capsys.readouterr().out.splitlines() + assert check(line), line + + +def test_readme_configuration(monkeypatch): + def route(request): + pytest.fail("the configuration example makes no request") + + namespace, seen = _run(monkeypatch, _block("delegated ="), route, "README.md configuration") + try: + assert seen == [] + client = namespace["client"] + assert client._base_url == "https://api.saturday.fit" + assert client._timeout == 30.0 + assert client._max_retries == 3 + delegated = namespace["delegated"] + assert delegated._bearer_token == "eyJ..." + # The athlete's token is sent in place of the API key. + assert delegated._client.headers["Authorization"] == "Bearer " + delegated._bearer_token + finally: + namespace["client"].close() + namespace["delegated"].close() + + +def _docstring_code(obj): + lines = inspect.getdoc(obj).splitlines() + start = next(i for i, line in enumerate(lines) if line.rstrip().endswith("::")) + return textwrap.dedent("\n".join(lines[start + 1:])).strip() + + +def test_package_docstring_example(monkeypatch, capsys): + def route(request): + assert request.url.path == "/v1/nutrition/calculate" + assert json.loads(request.content) == {"activity_type": "bike", "duration_min": 120} + return _json(request, CONTRACTS["nutrition_exact"]) + + monkeypatch.setenv("SATURDAY_API_KEY", "sk_test_fake") + _run(monkeypatch, _docstring_code(saturday), route, "package docstring example") + plan = CONTRACTS["nutrition_exact"] + assert capsys.readouterr().out.splitlines() == [str(plan.get("carb_g_per_hr", plan.get("carb_range_g_per_hr")))] + + +def test_saturday_class_docstring_example(monkeypatch): + def route(request): + if request.url.path == "/v1/athletes": + return _json(request, LIVE["athlete"], 201) + assert request.url.path == "/v1/nutrition/calculate" + assert json.loads(request.content) == { + "athlete_id": LIVE["athlete"]["id"], "activity_type": "run", "duration_min": 90, + "intensity_level": 5, "thermal_stress_level": 6, "meal_before_min": 120, "is_race": False, + } + return _json(request, LIVE["calculate_exact"]) + + # The class docstring snippet is a fragment: it uses Saturday without + # importing it, so seed the name as the surrounding docs do. + namespace, _ = _run(monkeypatch, _docstring_code(saturday.Saturday), route, + "client docstring example", namespace={"Saturday": saturday.Saturday}) + try: + assert namespace["athlete"] == LIVE["athlete"] + assert namespace["plan"] == LIVE["calculate_exact"] + finally: + namespace["client"].close() + + +def test_coach_resource_docstring_example(monkeypatch): + from saturday.client import _CoachResource + from test_api_surface import COACH_DIGEST + + def route(request): + if request.method == "GET": + assert request.url.path == "/v1/coach/roster/digest" + assert dict(request.url.params) == {"window": "7"} + return _json(request, COACH_DIGEST) + assert request.url.path == "/v1/coach/config/preset" + return _json(request, {}) + + namespace, seen = _run(monkeypatch, _docstring_code(_CoachResource), route, + "coach resource docstring example", namespace={"Saturday": saturday.Saturday}) + try: + assert namespace["digest"] == COACH_DIGEST + assert json.loads(seen[1].content) == {"scope": "overall", "scope_id": None, "preset": "balanced"} + finally: + namespace["client"].close() diff --git a/tests/test_request.py b/tests/test_request.py index 3a6c192..8d42564 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -702,7 +702,6 @@ def test_non_json_404_body_still_maps_to_not_found(make_client): assert raised.value.message == "plain not found" -@pytest.mark.xfail(reason="200 with a non-JSON or empty body raises JSONDecodeError, not SaturdayError", strict=True) @pytest.mark.parametrize("body", [b"not JSON", b""]) def test_non_json_success_body_should_raise_saturday_error(make_client, body): client = make_client(lambda _: httpx.Response(200, content=body), max_retries=0)