From 1ab687919c7d1c17f3ee6eb8bb0e230ff5c05018 Mon Sep 17 00:00:00 2001 From: Alex Harrison Date: Thu, 19 Nov 2026 10:51:28 -0700 Subject: [PATCH] Run the tests on every pull request; contract samples now come from fuel-backend .github/workflows/test.yml runs the suite on pull requests (GitHub-hosted ubuntu-latest, free for public repos). generate.go moved into fuel-backend (pkg/sdkcontracts), which fails a test when its samples go stale; its scripts/sdk-contracts-sync.sh --pr opens a pull request here with new samples. RateLimitError passes retry_after through kwargs, which clears the one error the mypy check reported, so the workflow can run it. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 28 ++++ CONTRIBUTING.md | 2 + saturday/errors.py | 3 +- tests/fixtures/README.md | 13 +- tests/fixtures/generate.go | 279 ------------------------------------- 5 files changed, 35 insertions(+), 290 deletions(-) create mode 100644 .github/workflows/test.yml delete mode 100644 tests/fixtures/generate.go diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..0523f80 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,28 @@ +name: Test + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: test-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-python@v7 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: pyproject.toml + + - run: python -m pip install -e '.[test]' + - run: python -m pytest + - run: python -m mypy saturday tests/typecheck --check-untyped-defs --warn-unused-ignores diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 94f90a6..24ee2a1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,6 +19,8 @@ python -m pip install -e '.[test]' python -m pytest ``` +Every pull request runs the tests and the mypy check in `tests/fixtures/README.md` (`.github/workflows/test.yml`). + Update `saturday/` against the current [API documentation](https://docs.saturday.fit/introduction) and add coverage in `tests/` for behavior changes. `python -m pytest` uses mocked responses and recorded API responses and needs no API key. The live suite runs every method against a real API with a test key: see [tests/LIVE.md](tests/LIVE.md). After a change to the API, run it with `SATURDAY_LIVE_CAPTURE=tests/fixtures/live.json` and commit the new recording with the type changes. ## Code of conduct diff --git a/saturday/errors.py b/saturday/errors.py index eed0b86..1b0a0f6 100644 --- a/saturday/errors.py +++ b/saturday/errors.py @@ -98,7 +98,8 @@ class RateLimitError(SaturdayError): """ def __init__(self, *args: Any, retry_after: Optional[float] = None, now: Optional[datetime] = None, **kwargs: Any): - super().__init__(*args, retry_after=retry_after, **kwargs) + kwargs["retry_after"] = retry_after + super().__init__(*args, **kwargs) # An API that predates the daily codes marks a daily ceiling by sending no Retry-After. self.daily_limit = self.code in DAILY_LIMIT_CODES or retry_after is None self.resets_at: Optional[datetime] = None diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index 975ab53..6db3707 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -1,14 +1,7 @@ # Contract fixtures -`contracts.json` is generated from fuel-backend's Go JSON types and its real stored-prescription, list and settings handlers, using synthetic data and in-memory services. It makes no API, Firestore, inference, auth, or trial calls. The backend commit is recorded in `_meta`. +`contracts.json` holds sample API responses that fuel-backend builds (`pkg/sdkcontracts`) from its Go response types and its real stored-prescription, list and settings handlers, with synthetic data and in-memory services. It makes no API, Firestore, inference, auth, or trial calls. `_meta.backend_sha` is the backend commit that last changed the samples. -Regenerate from a checked-out backend module, with Go 1.26+: +The backend fails a test when its copy of the samples no longer matches what its types and handlers produce. Once the regenerated samples are on the backend's main, `scripts/sdk-contracts-sync.sh --pr` in fuel-backend opens a pull request here carrying them, and the test run on that pull request shows whether the SDK types still match. Fix the types on that branch when it fails. -```bash -cd /path/to/fuel-backend -go run /path/to/saturday-python/tests/fixtures/generate.go \ - -backend-sha "$(git rev-parse HEAD)" \ - -out /path/to/saturday-python/tests/fixtures/contracts.json -``` - -Review generated differences before accepting them. `tests/test_contracts.py` checks payloads against TypedDict required/optional keys and value types, then exercises methods using mocked HTTP. Static examples are checked with `python -m mypy saturday tests/typecheck --check-untyped-defs --warn-unused-ignores`. This is local source-contract evidence, not a live deployed-API smoke test. +`tests/test_contracts.py` checks payloads against TypedDict required/optional keys and value types, then exercises methods using mocked HTTP. Static examples are checked with `python -m mypy saturday tests/typecheck --check-untyped-defs --warn-unused-ignores`. This is local source-contract evidence, not a live deployed-API smoke test. diff --git a/tests/fixtures/generate.go b/tests/fixtures/generate.go deleted file mode 100644 index 4944791..0000000 --- a/tests/fixtures/generate.go +++ /dev/null @@ -1,279 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "flag" - "fmt" - "net/http/httptest" - "os" - "strings" - - "saturdaymorning.fit/appsbackend/pkg/api" - "saturdaymorning.fit/appsbackend/pkg/coachbilling" - "saturdaymorning.fit/appsbackend/pkg/connect" - "saturdaymorning.fit/appsbackend/pkg/partner" - "saturdaymorning.fit/appsbackend/pkg/purchase" - "saturdaymorning.fit/appsbackend/pkg/webhook" -) - -type activityReader struct { - api.ActivityManager - prescription *api.ActivityPrescription - activities []api.Activity - pagination *api.PaginationMeta -} - -func (a activityReader) GetPrescription(context.Context, string, string, string) (*api.ActivityPrescription, *api.ServiceError) { - return a.prescription, nil -} - -func (a activityReader) List(context.Context, string, string, string, int) ([]api.Activity, *api.PaginationMeta, *api.ServiceError) { - return a.activities, a.pagination, nil -} - -type athleteReader struct { - api.AthleteManager - athletes []api.Athlete - pagination *api.PaginationMeta - settings *api.AthleteSettings -} - -func (a athleteReader) List(context.Context, string, string, int, ...*bool) ([]api.Athlete, *api.PaginationMeta, *api.ServiceError) { - return a.athletes, a.pagination, nil -} - -func (a athleteReader) GetSettings(context.Context, string, string) (*api.AthleteSettings, *api.ServiceError) { - return a.settings, nil -} - -func (a athleteReader) UpdateSettings(_ context.Context, _, _ string, settings *api.AthleteSettings) (*api.AthleteSettings, *api.ServiceError) { - return settings, nil -} - -func settingsResponse(settings *api.AthleteSettings, body string) json.RawMessage { - h := &api.Handler{AthleteSvc: athleteReader{settings: settings}} - w := httptest.NewRecorder() - if body == "" { - h.HandleGetAthleteSettings(w, httptest.NewRequest("GET", "/settings", nil)) - } else { - h.HandleUpdateAthleteSettings(w, httptest.NewRequest("PATCH", "/settings", strings.NewReader(body))) - } - if w.Code != 200 { - panic(fmt.Sprintf("settings returned %d", w.Code)) - } - return json.RawMessage(w.Body.Bytes()) -} - -func listedActivities(activities []api.Activity, pagination *api.PaginationMeta) json.RawMessage { - h := &api.Handler{ActivitySvc: activityReader{activities: activities, pagination: pagination}} - w := httptest.NewRecorder() - r := httptest.NewRequest("GET", "/activities", nil) - r.SetPathValue("athlete_id", "ath_1") - h.HandleListActivities(w, r) - if w.Code != 200 { - panic(fmt.Sprintf("list activities returned %d", w.Code)) - } - return json.RawMessage(w.Body.Bytes()) -} - -func listedAthletes(athletes []api.Athlete, pagination *api.PaginationMeta) json.RawMessage { - h := &api.Handler{AthleteSvc: athleteReader{athletes: athletes, pagination: pagination}} - w := httptest.NewRecorder() - h.HandleListAthletes(w, httptest.NewRequest("GET", "/athletes", nil)) - if w.Code != 200 { - panic(fmt.Sprintf("list athletes returned %d", w.Code)) - } - return json.RawMessage(w.Body.Bytes()) -} - -func stored(prescription *api.ActivityPrescription) json.RawMessage { - h := &api.Handler{ActivitySvc: activityReader{prescription: prescription}} - w := httptest.NewRecorder() - h.HandleGetActivityPrescription(w, httptest.NewRequest("GET", "/prescription", nil)) - if w.Code != 200 { - panic(fmt.Sprintf("stored prescription returned %d", w.Code)) - } - return json.RawMessage(w.Body.Bytes()) -} - -func main() { - out := flag.String("out", "", "output JSON path") - sha := flag.String("backend-sha", "", "backend commit used to generate fixtures") - flag.Parse() - if *out == "" || *sha == "" { - panic("-out and -backend-sha are required") - } - safety := api.NewSafetyMetadata() - safety.MaxSafeFluidMLPerHr, safety.MaxSafeSodiumMGPerHr = 1500, 3000 - attribution := api.Attribution{Text: "Powered by Saturday", LogoURL: "https://saturday.fit/logo.png", Link: "https://saturday.fit"} - cta := &api.SubscriptionCTA{Message: "Subscribe", SubscribeURL: "https://saturday.fit/", Features: []string{"Exact targets"}} - incomplete := false - zero := 0 - precision := &api.Precision{ - ProfileComplete: false, - MissingFields: []api.MissingField{{Field: "sweat_level", Required: true, DisplayLabel: "how much you sweat", BandImpact: &api.BandImpact{FluidMLPerHr: 100}}}, - Onboarding: &api.OnboardingInvite{Message: "Complete your profile"}, - } - exact := &api.ActivityPrescription{TotalCarbG: 120, TotalSodiumMG: 1200, TotalFluidML: 1400, CarbGPerHr: 60, SodiumMGPerHr: 600, FluidMLPerHr: 700, CalculatedAt: 1700000000} - band := &api.ActivityPrescription{ProfileComplete: &incomplete, CarbRangeGPerHr: "50-70", SodiumRangeMGPerHr: "500-700", FluidRangeMLPerHr: "600-800", CalculatedAt: 1700000000} - full := api.PrescriptionEnvelope{Tier: "full", Prescription: exact, Safety: safety, Attribution: attribution} - banded := api.PrescriptionEnvelope{Tier: "full", Prescription: band, Precision: precision, Safety: safety, Attribution: attribution} - teaser := api.PrescriptionEnvelope{Tier: "teaser", CarbRangeGPerHr: "40-80", SodiumRangeMGPerHr: "400-800", FluidRangeMLPerHr: "500-900", Safety: safety, Attribution: attribution, CTA: cta, Precision: precision, TrialCapReached: true, TrialCapNote: "Daily cap reached", TrialEndsAt: 1700000500000} - trial := full - trial.TierSource, trial.TrialEndsAt, trial.TrialCallsRemainingToday = "trial", 1700000500000, &zero - nutrition := api.NutritionCalculateResponse{Tier: "full", CarbGPerHr: 60, SodiumMGPerHr: 600, FluidMLPerHr: 700, TotalCarbG: 120, TotalSodiumMG: 1200, TotalFluidML: 1400, Safety: safety, Attribution: attribution} - nutritionBand := api.NutritionCalculateResponse{Tier: "full", CarbRangeGPerHr: "50-70", SodiumRangeMGPerHr: "500-700", FluidRangeMLPerHr: "600-800", Safety: safety, Attribution: attribution, Precision: precision} - nutritionTeaser := nutritionBand - nutritionTeaser.Tier, nutritionTeaser.CTA, nutritionTeaser.TrialCapReached, nutritionTeaser.TrialCapNote = "teaser", cta, true, "Daily cap reached" - nutritionTrial := nutrition - nutritionTrial.TierSource, nutritionTrial.TrialEndsAt, nutritionTrial.TrialCallsRemainingToday = "trial", 1700000500000, &zero - activity := api.Activity{ID: "act_1", AthleteID: "ath_1", PartnerID: "partner_1", Type: "bike", DurationMin: 120, ExternalID: "partner-act", Prescription: exact, CreatedAt: 1700000000, UpdatedAt: 1700000000} - athlete := api.Athlete{ID: "ath_1", PartnerID: "partner_1", Name: "Fixture Athlete", CreatedAt: 1700000000, UpdatedAt: 1700000000} - batchError := api.BatchError{Index: 1, Code: "invalid_value", Message: "Invalid input"} - nextPage := &api.PaginationMeta{Total: 1, HasMore: true, NextCursor: "1700000000"} - lastPage := &api.PaginationMeta{Total: 0, HasMore: false} - settings := &api.AthleteSettings{ - SweatLevel: 5, Saltiness: 5, SatietyLevel: 5, FitnessLevel: 5, - CarbExperience: "range_40_60", UsualCarbConsumption: "range_60_80", CarbUpperLimitOverride: 90, - MuscleCramps: true, GutDistress: true, Performance: true, Hunger: true, - HeatTolerance: true, Faintness: true, DrinkingResistance: true, Thirst: true, ConcernsAnswered: true, - } - fixtures := map[string]any{ - "_meta": map[string]string{"backend_sha": *sha, "source": "pkg/api Go JSON types, stored-prescription/list/settings HTTP handlers, the coach billing structs in pkg/purchase, pkg/connect and pkg/coachbilling, and the profile-sharing types in pkg/api, pkg/partner and pkg/webhook; synthetic values, no API calls"}, - "activity_exact": exact, - "activity_banded": band, - "nutrition_exact": nutrition, - "nutrition_banded": nutritionBand, - "nutrition_teaser": nutritionTeaser, - "nutrition_trial": nutritionTrial, - "nutrition_zero": api.NutritionCalculateResponse{Tier: "full", Safety: safety, Attribution: attribution}, - "activity_full": full, - "activity_full_banded": banded, - "activity_teaser": teaser, - "activity_trial": trial, - "stored_exact": stored(exact), - "stored_banded": stored(band), - "activity": activity, - "athlete": athlete, - "list_athletes_next": listedAthletes([]api.Athlete{athlete}, nextPage), - "list_athletes_empty": listedAthletes([]api.Athlete{}, lastPage), - "list_activities_next": listedActivities([]api.Activity{activity}, nextPage), - "list_activities_empty": listedActivities([]api.Activity{}, lastPage), - "feedback": api.ActivityFeedback{Rating: 4, Notes: "Fixture feedback", CreatedAt: 1700000000}, - "settings_full": settingsResponse(settings, ""), - "settings_empty": settingsResponse(&api.AthleteSettings{}, ""), - "settings_updated": settingsResponse(nil, "{\"sweat_level\":5,\"gut_distress\":false}"), - "batch_partial": api.BatchCalculateResponse{Results: []api.NutritionCalculateResponse{nutrition, nutritionBand}, Errors: []api.BatchError{batchError}, Total: 3, Succeeded: 2, Failed: 1, EstimatedMS: 100, ElapsedMS: 100, RequestID: "req_1"}, - "batch_all_failed": api.BatchCalculateResponse{Results: []api.NutritionCalculateResponse{}, Errors: []api.BatchError{{Index: 0, Code: "invalid_value", Message: "Invalid input"}}, Total: 1, Failed: 1, RequestID: "req_2"}, - "batch_estimate": api.BatchCalculateResponse{Results: []api.NutritionCalculateResponse{}, Total: 2, EstimatedMS: 100, RequestID: "req_3"}, - "athletes_partial": api.BatchAthleteResponse{Created: []api.Athlete{athlete}, Errors: []api.BatchError{batchError}, Total: 2, Succeeded: 1, Failed: 1, RequestID: "req_4"}, - "athletes_all_failed": api.BatchAthleteResponse{Created: []api.Athlete{}, Errors: []api.BatchError{{Index: 0, Code: "invalid_value", Message: "Invalid input"}}, Total: 1, Failed: 1, RequestID: "req_5"}, - "import_plain": api.ActivityImportResponse{Imported: []api.Activity{activity}, Total: 1, Succeeded: 1, RequestID: "req_6"}, - "import_calculated": api.ActivityImportResponse{Imported: []api.Activity{activity}, Total: 1, Succeeded: 1, RequestID: "req_7", Prescriptions: []api.ImportPrescriptionItem{{Index: 0, ActivityID: "act_1", Result: &banded}}}, - "import_calc_failed": api.ActivityImportResponse{Imported: []api.Activity{activity}, Total: 1, Succeeded: 1, RequestID: "req_8", Prescriptions: []api.ImportPrescriptionItem{{Index: 0, ActivityID: "act_1", Code: "storage_error", Message: "Unable to calculate"}}}, - "import_all_failed": api.ActivityImportResponse{Imported: []api.Activity{}, Errors: []api.BatchError{{Index: 0, Code: "invalid_value", Message: "Invalid input"}}, Total: 1, Failed: 1, RequestID: "req_9"}, - } - // An app signed in on the athlete's behalf gets missing_fields without band_impact. - signedIn := *precision - signedIn.MissingFields = []api.MissingField{{Field: "sweat_level", Required: true, DisplayLabel: "how much you sweat"}} - nutritionSignedIn := nutritionBand - nutritionSignedIn.Precision = &signedIn - fixtures["nutrition_banded_signed_in"] = nutritionSignedIn - for name, fixture := range billingFixtures() { - fixtures[name] = fixture - } - for name, fixture := range sharingFixtures(athlete) { - fixtures[name] = fixture - } - file, err := os.Create(*out) - if err != nil { - panic(err) - } - defer file.Close() - encoder := json.NewEncoder(file) - encoder.SetIndent("", " ") - if err := encoder.Encode(fixtures); err != nil { - panic(err) - } - fmt.Printf("Wrote %d contract fixtures to %s\n", len(fixtures)-1, *out) -} - -// billingFixtures marshals the coach billing reads from the structs the Coach API -// serves (pkg/purchase, pkg/connect, pkg/coachbilling), one populated and one empty -// shape per endpoint, so the SDK types are checked against real serialization. -func billingFixtures() map[string]any { - acct := &connect.ConnectAccount{CoachUID: "coach_abc", StripeAccountID: "acct_1", ChargesEnabled: true, PayoutsEnabled: true, DetailsSubmitted: true, CardPaymentsStatus: "active", TransfersStatus: "active", Country: "US", DefaultCurrency: "usd", Capabilities: map[string]string{"card_payments": "active"}, OnboardedAt: 1749500000000, UpdatedAt: 1749500000000} - charge := connect.ConnectCharge{ChargeID: "ch_1", ArrangementID: "arr_1", CoachUID: "coach_abc", AthleteUID: "ath_123", AmountCents: 5000, PlatformFeeCents: 500, StripeFeesCents: 175, NetToCoachCents: 4325, Currency: "usd", Status: "succeeded", CapturedAt: 1749480000000, StripeWebhookEventID: "evt_1", StripeFeePaidBy: "coach"} - refunded := connect.ConnectCharge{ChargeID: "ch_2", ArrangementID: "arr_1", CoachUID: "coach_abc", AthleteUID: "ath_123", AmountCents: 10000, PlatformFeeCents: 1000, StripeFeesCents: 320, NetToCoachCents: 6880, Currency: "usd", Status: "refunded", RefundAmountCents: 2000, CapturedAt: 1749390000000, StripeWebhookEventID: "evt_2", StripeFeePaidBy: "coach", PlatformFeeReturnedCents: 200} - arr := connect.BillingArrangement{ArrangementID: "arr_1", CoachUID: "coach_abc", AthleteUID: "ath_123", StripeConnectAcctID: "acct_1", StripeCustomerID: "cus_1", StripeSubscriptionID: "sub_1", BillingMode: "recurring", AmountCents: 5000, Currency: "usd", Interval: "month", TrialDays: 7, RefundPolicy: "prorated", Status: "active", PlatformFeeBPS: 1000, CreatedAt: 1749400000000, ActivatedAt: 1749400000000} - sub := purchase.TierSubscription{SubscriptionID: "ts_1", SubscriberType: "user", SubscriberID: "coach_abc", Tier: "business", Channel: "web_stripe", SourceSKU: "price_1", StripeSubscriptionID: "sub_biz", Status: "active", CurrentPeriodStart: 1748000000000, CurrentPeriodEnd: 1750600000000, AmountCents: 9900, AutoRenew: true, CreatedAt: 1748000000000, UpdatedAt: 1748000000000} - return map[string]any{ - "billing_seat_state": &purchase.SeatState{Tier: "business", IncludedTotal: 50, IncludedUsed: 12, IsFairUse: true}, - "billing_seat_state_pro": &purchase.SeatState{Tier: "pro_coach", IncludedTotal: 2, IncludedUsed: 2, CoachPaidCount: 3, NextAthletePriceCents: 1299, VolumeTier: 1, TotalMonthlyCents: 3897}, - "billing_ledger_page": &coachbilling.LedgerPage{Entries: []map[string]any{{"id": "e_1", "entry_id": "e_1", "user_uid": "coach_abc", "direction": "receipt", "amount_cents": 5000, "currency": "usd", "category": "coaching_fee_received", "counterparty_type": "athlete", "counterparty_id": "ath_123", "counterparty_display_name": "A. Rider", "source_type": "stripe_charge", "source_reference_id": "ch_1", "description": "Coaching fee from A. Rider", "occurred_at": 1749480000000, "created_at": 1749480000000, "charge_group_id": "ch_1", "settlement_status": "settled"}}, NextCursor: "1749480000000|e_1"}, - "billing_ledger_empty": &coachbilling.LedgerPage{Entries: []map[string]any{}}, - "billing_tier_status": &coachbilling.TierStatus{Subscriptions: []purchase.TierSubscription{sub}, Count: 1, Status: &purchase.SubscriptionStatus{HasTierSub: true, IsActive: true, Source: "tier_subscription", TierID: "business"}}, - "billing_tier_status_empty": &coachbilling.TierStatus{Subscriptions: []purchase.TierSubscription{}, Status: &purchase.SubscriptionStatus{}}, - "billing_connect_summary": &connect.DashboardSummary{ConnectAccount: acct, IsOnboarded: true, ActiveArrangements: 3, MonthCharges: 15000, MonthFees: 2025, MonthNet: 12975, LifetimeCharges: 240000, LifetimeFees: 32400, LifetimeNet: 207600, PlatformFeeBPS: 1000}, - "billing_connect_summary_none": &connect.DashboardSummary{PlatformFeeBPS: 1000}, - "billing_connect_earnings": &coachbilling.ConnectEarnings{Summary: &connect.CoachEarningsSummary{CoachUID: "coach_abc", TotalGrossCents: 240000, TotalStripeFeeCents: 8400, TotalPlatformFeeCents: 24000, TotalRefundedCents: 2000, TotalPlatformFeeReturnedCents: 200, TotalDisputesCents: 1500, TotalDisputeRecoveryCents: 0, TotalNetCents: 204300, ChargeCount: 48, SettledCount: 46, SettlingCount: 2, Currency: "usd"}, Breakdowns: []connect.ChargeBreakdown{{ChargeGroupID: "ch_1", GrossAmountCents: 5000, StripeFeesCents: 175, StripeFeePaidBy: "coach", PlatformFeeCents: 500, NetToCoachCents: 4325, Currency: "usd", SettlementStatus: "settled", OccurredAt: 1749480000000, AthleteUID: "ath_123", AthleteDisplayName: "A. Rider"}, {ChargeGroupID: "ch_2", GrossAmountCents: 10000, StripeFeesCents: 320, StripeFeePaidBy: "coach", PlatformFeeCents: 1000, RefundedCents: 2000, PlatformFeeReturnedCents: 200, NetToCoachCents: 6880, Currency: "usd", SettlementStatus: "settled", OccurredAt: 1749390000000, AthleteUID: "ath_123", AthleteDisplayName: "A. Rider"}}}, - "billing_connect_earnings_empty": &coachbilling.ConnectEarnings{Summary: &connect.CoachEarningsSummary{CoachUID: "coach_abc", Currency: "usd"}, Breakdowns: []connect.ChargeBreakdown{}}, - "billing_connect_transactions": &coachbilling.ChargesPage{Charges: []connect.ConnectCharge{charge, refunded}, Total: 2, NextCursor: "1749390000000|ch_2"}, - "billing_connect_transactions_end": &coachbilling.ChargesPage{Charges: []connect.ConnectCharge{}}, - "billing_connect_arrangements": &connect.DashboardArrangements{Arrangements: []connect.BillingArrangement{arr}, Total: 1}, - } -} - -// sharingFixtures marshals the profile-sharing reads and webhooks from the backend's types: -// GET /v1/athletes/{id} with profile_sharing, the fueling-profile response in its three states -// (answers parsed by partner.ParseAppProfile from a synthetic users document, one entry per -// partner.SharedProfileFields), and the two sharing webhook envelopes, whose data is the athlete -// record as GET returns it (fueling_profile_updated adds changed_fields). -func sharingFixtures(athlete api.Athlete) map[string]any { - shared := athlete - shared.SubscriptionStatus, shared.ProfileSharing = "full", partner.SharingOn - unlinked := athlete - unlinked.SubscriptionStatus, unlinked.ProfileSharing = "teaser", partner.SharingNotLinked - app := partner.ParseAppProfile(map[string]interface{}{ - "sex": "female", "year_of_birth": int64(1992), "weight_in_lb": int64(135), - "sweat_level": int64(7), "saltiness": int64(9), "fitness_level": int64(5), - "max_carb_exp": "range_40_60", "usual_carb_consumption": "range_60_80", - "fueling_concerns": map[string]interface{}{"performance": true}, - }) - uses := map[string]string{"age": api.CalculationsUsePartner, "saltiness": api.CalculationsUsePartner, "satiety_level": api.CalculationsUseDefault} - profile := map[string]api.FuelingProfileField{} - for _, f := range partner.SharedProfileFields { - value, _ := app.Value(f, 2026) - use := uses[f] - if use == "" { - use = api.CalculationsUseSaturdayApp - } - profile[f] = api.FuelingProfileField{Value: value, CalculationsUse: use} - } - offMessage := "This athlete has not chosen to share their Saturday app answers with you." - notLinkedMessage := "This athlete has not connected a Saturday account, so there are no Saturday app answers to share." - updated := record(shared) - updated["changed_fields"] = []string{"sweat_level", "concerns"} - return map[string]any{ - "athlete_sharing": shared, - "fueling_profile_on": api.FuelingProfile{Object: "fueling_profile", AthleteID: "ath_1", Sharing: partner.SharingOn, Profile: profile, UpdatedAt: 1760000000000}, - "fueling_profile_off": api.FuelingProfile{Object: "fueling_profile", AthleteID: "ath_1", Sharing: partner.SharingOff, Message: &offMessage}, - "fueling_profile_not_linked": api.FuelingProfile{Object: "fueling_profile", AthleteID: "ath_1", Sharing: partner.SharingNotLinked, Message: ¬LinkedMessage}, - "webhook_profile_sharing_changed": webhook.WebhookEvent{ID: "evt_4f9a2c7e1b8d3a6f0c5e9b2d7a1f4c8e", Type: webhook.EventProfileSharingChanged, CreatedAt: 1765467600000, Data: record(unlinked)}, - "webhook_fueling_profile_updated": webhook.WebhookEvent{ID: "evt_0b7e3d9a5c1f8e2a6d4b0c9f3e7a1d5b", Type: webhook.EventFuelingProfileUpdated, CreatedAt: 1765467600000, Data: updated}, - } -} - -// record is an athlete as a JSON object, the shape the sharing webhooks build their data from. -func record(athlete api.Athlete) map[string]any { - raw, err := json.Marshal(athlete) - if err != nil { - panic(err) - } - var out map[string]any - if err := json.Unmarshal(raw, &out); err != nil { - panic(err) - } - return out -}