fix: address final review findings for service clients plan

Fixes 9 numbered findings + 7 minor fixes from the whole-plan review of
the MyWhoosh/Garmin service clients (Plan 3):

Garmin uploader (app/garmin/uploader.py):
- Detect Garmin-rejected imports (failures without successes) and raise
  new GarminImportRejected instead of reporting them as successful.
- Reclassify 429/rate-limit/500 login failures as transient instead of
  falling through to permanent auth errors; unrecognized login failures
  are now treated as transient (retryable) rather than GarminAuthError.
- Mirror the auth-token check from the login branch into the import
  branch so 401-at-import-time raises GarminAuthError instead of
  propagating raw.
- Add common GarminError base class, hoist transient-token tuple to a
  shared module constant, check response.status_code==409 before the
  duplicate substring fallback, and create the tokenstore dir 0o700.

MyWhoosh client (app/mywhoosh/client.py):
- Add optional max_pages bound to list_activities pagination.
- Add aclose()/__aenter__/__aexit__ so the client's own httpx.AsyncClient
  gets closed, while never closing an injected client.
- Guard the two remaining unguarded JSON-decode paths (login body,
  download-fit metadata) so malformed bodies raise
  MyWhooshIntegrationError instead of raw ValueError/AttributeError.
- Row-level malformation (missing id/activityFileId, unparseable
  startDatetime) is now skipped rather than aborting the whole page;
  envelope-shape failures still raise. id/activityFileId checks use
  explicit None/"" comparisons instead of Python falsiness.
- Replace asserts in _authenticated_post with explicit exceptions;
  restrict the reauth retry to 401 only, treat 403 as immediately
  terminal; naive startDatetime values are now treated as already-UTC
  instead of host-local.

MyWhoosh tokenstore (app/mywhoosh/tokenstore.py):
- load() now treats any corrupt/malformed token file (bad JSON, missing
  keys, OS errors) as "absent" instead of raising, so a bad cache no
  longer permanently wedges a user.

pyproject.toml:
- Tighten garminconnect pin to >=0.3.10,<1 (import_activity requires
  0.3.10+).

Adds/updates tests across tests/mywhoosh/ and tests/garmin/ covering
all of the above, including a fake client that wraps GarminUploadBlocked
in a plain RuntimeError to mirror the real garminconnect library's MFA
error wrapping.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Bastian Wagner
2026-08-15 15:23:14 +02:00
parent b48008c16e
commit 2f65c0178c
8 changed files with 426 additions and 33 deletions

View File

@@ -134,7 +134,7 @@ async def test_download_fit_fetches_signed_url_bytes(tmp_path) -> None:
@pytest.mark.asyncio
async def test_list_activities_raises_integration_error_on_missing_stable_id(tmp_path) -> None:
async def test_list_activities_skips_row_missing_stable_id(tmp_path) -> None:
async def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/activities"):
return httpx.Response(
@@ -147,7 +147,13 @@ async def test_list_activities_raises_integration_error_on_missing_stable_id(tmp
"title": "Ride without id",
"activityFileId": "f-1",
"startDatetime": "2026-08-15T06:00:00.000Z",
}
},
{
"id": "a-2",
"title": "Ride with id",
"activityFileId": "f-2",
"startDatetime": "2026-08-15T06:00:00.000Z",
},
],
}
},
@@ -158,5 +164,108 @@ async def test_list_activities_raises_integration_error_on_missing_stable_id(tmp
store.save(MyWhooshToken(access_token="cached", refresh_token=None, whoosh_id=None))
client = MyWhooshClient(store, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
activities = await client.list_activities("rider@example.com", "secret")
assert [a.id for a in activities] == ["a-2"]
@pytest.mark.asyncio
async def test_list_activities_skips_row_with_unparseable_start_datetime(tmp_path) -> None:
async def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/activities"):
return httpx.Response(
200,
json={
"data": {
"totalPages": 1,
"results": [
{
"id": "a-1",
"title": "Ride with bad date",
"activityFileId": "f-1",
"startDatetime": "not-a-date",
},
{
"id": "a-2",
"title": "Ride with good date",
"activityFileId": "f-2",
"startDatetime": "2026-08-15T06:00:00.000Z",
},
],
}
},
)
raise AssertionError(request.url)
store = MyWhooshTokenStore(tmp_path / "mywhoosh.json")
store.save(MyWhooshToken(access_token="cached", refresh_token=None, whoosh_id=None))
client = MyWhooshClient(store, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
activities = await client.list_activities("rider@example.com", "secret")
assert [a.id for a in activities] == ["a-2"]
@pytest.mark.asyncio
async def test_list_activities_raises_integration_error_on_envelope_shape_failure(tmp_path) -> None:
async def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/activities"):
return httpx.Response(200, json={"data": {"totalPages": 1}})
raise AssertionError(request.url)
store = MyWhooshTokenStore(tmp_path / "mywhoosh.json")
store.save(MyWhooshToken(access_token="cached", refresh_token=None, whoosh_id=None))
client = MyWhooshClient(store, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
with pytest.raises(MyWhooshIntegrationError):
await client.list_activities("rider@example.com", "secret")
@pytest.mark.asyncio
async def test_list_activities_respects_max_pages(tmp_path) -> None:
calls = []
async def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/activities"):
payload = json.loads(request.content)
page = payload["page"]
calls.append(page)
result = {
"data": {
"totalPages": 5,
"results": [
{
"id": f"a-{page}",
"title": f"Ride {page}",
"activityFileId": f"f-{page}",
"startDatetime": "2026-08-15T06:00:00.000Z",
}
],
}
}
return httpx.Response(200, json=result)
raise AssertionError(request.url)
store = MyWhooshTokenStore(tmp_path / "mywhoosh.json")
store.save(MyWhooshToken(access_token="cached", refresh_token=None, whoosh_id=None))
client = MyWhooshClient(store, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
activities = await client.list_activities("rider@example.com", "secret", max_pages=1)
assert calls == [1]
assert [a.id for a in activities] == ["a-1"]
@pytest.mark.asyncio
async def test_download_fit_raises_integration_error_on_invalid_json(tmp_path) -> None:
async def handler(request: httpx.Request) -> httpx.Response:
if request.url.path.endswith("/download-activity-file"):
return httpx.Response(200, content=b"not json", headers={"content-type": "application/json"})
raise AssertionError(request.url)
store = MyWhooshTokenStore(tmp_path / "mywhoosh.json")
store.save(MyWhooshToken(access_token="cached", refresh_token=None, whoosh_id=None))
client = MyWhooshClient(store, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
with pytest.raises(MyWhooshIntegrationError):
await client.download_fit("f-1", "rider@example.com", "secret")

View File

@@ -1,7 +1,12 @@
import httpx
import pytest
from app.mywhoosh.client import MyWhooshClient, MyWhooshAuthError
from app.mywhoosh.client import (
MyWhooshAuthError,
MyWhooshClient,
MyWhooshIntegrationError,
MyWhooshTransientError,
)
from app.mywhoosh.models import MyWhooshToken
from app.mywhoosh.tokenstore import MyWhooshTokenStore
@@ -37,3 +42,93 @@ async def test_invalid_credentials_raise_auth_error(tmp_path) -> None:
)
with pytest.raises(MyWhooshAuthError):
await client.login("rider@example.com", "bad")
@pytest.mark.asyncio
async def test_login_returns_json_array_raises_integration_error(tmp_path) -> None:
async def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json=["not", "an", "object"])
client = MyWhooshClient(
MyWhooshTokenStore(tmp_path / "mywhoosh.json"),
http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
)
with pytest.raises(MyWhooshIntegrationError):
await client.login("rider@example.com", "bad")
@pytest.mark.asyncio
async def test_login_5xx_raises_transient_error(tmp_path) -> None:
async def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(503, text="Service Unavailable")
client = MyWhooshClient(
MyWhooshTokenStore(tmp_path / "mywhoosh.json"),
http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
)
with pytest.raises(MyWhooshTransientError):
await client.login("rider@example.com", "secret")
@pytest.mark.asyncio
async def test_second_401_after_reauth_raises_auth_error(tmp_path) -> None:
login_call_count = 0
async def handler(request: httpx.Request) -> httpx.Response:
nonlocal login_call_count
if request.url.path.endswith("/activities"):
return httpx.Response(401, json={"message": "expired"})
if request.url.path.endswith("/login"):
login_call_count += 1
return httpx.Response(
200,
json={
"Success": True,
"AccessToken": "fresh-access",
"RefreshToken": "fresh-refresh",
"WhooshId": "w-1",
},
)
raise AssertionError(request.url)
store = MyWhooshTokenStore(tmp_path / "mywhoosh.json")
store.save(MyWhooshToken(access_token="stale", refresh_token=None, whoosh_id=None))
client = MyWhooshClient(store, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
with pytest.raises(MyWhooshAuthError):
await client.list_activities("rider@example.com", "secret")
assert login_call_count == 1
@pytest.mark.asyncio
async def test_aclose_closes_self_owned_http_client(tmp_path) -> None:
store = MyWhooshTokenStore(tmp_path / "mywhoosh.json")
client = MyWhooshClient(store)
await client.aclose()
assert client.http.is_closed is True
@pytest.mark.asyncio
async def test_aclose_does_not_close_injected_http_client(tmp_path) -> None:
store = MyWhooshTokenStore(tmp_path / "mywhoosh.json")
injected = httpx.AsyncClient()
client = MyWhooshClient(store, http_client=injected)
await client.aclose()
assert injected.is_closed is False
await injected.aclose()
@pytest.mark.asyncio
async def test_client_usable_as_async_context_manager(tmp_path) -> None:
store = MyWhooshTokenStore(tmp_path / "mywhoosh.json")
async with MyWhooshClient(store) as client:
http_client = client.http
assert http_client.is_closed is False
assert http_client.is_closed is True

View File

@@ -16,3 +16,28 @@ def test_tokenstore_round_trip_and_permissions(tmp_path: Path) -> None:
def test_missing_token_returns_none(tmp_path: Path) -> None:
store = MyWhooshTokenStore(tmp_path / "missing.json")
assert store.load() is None
def test_corrupt_token_file_returns_none(tmp_path: Path) -> None:
path = tmp_path / "mywhoosh.json"
path.write_bytes(b"not valid json {{{")
store = MyWhooshTokenStore(path)
assert store.load() is None
def test_token_file_missing_access_token_returns_none(tmp_path: Path) -> None:
path = tmp_path / "mywhoosh.json"
path.write_text('{"refresh_token": "r", "whoosh_id": "w"}', encoding="utf-8")
store = MyWhooshTokenStore(path)
assert store.load() is None
def test_clear_removes_token_and_load_returns_none(tmp_path: Path) -> None:
store = MyWhooshTokenStore(tmp_path / "tokens" / "mywhoosh.json")
token = MyWhooshToken(access_token="access", refresh_token="refresh", whoosh_id="whoosh-1")
store.save(token)
store.clear()
assert store.load() is None
assert not store.path.exists()