| 1 |
"""Unit tests for the .well-known/home endpoint discovery module.""" |
| 2 |
|
| 3 |
from aiohttp import ClientSession |
| 4 |
from aioresponses import aioresponses |
| 5 |
import pytest |
| 6 |
from yarl import URL |
| 7 |
|
| 8 |
from cookidoo_api.exceptions import CookidooParseException, CookidooRequestException |
| 9 |
from cookidoo_api.well_known import ( |
| 10 |
_TOKEN_RE, |
| 11 |
ENDPOINT_RELS, |
| 12 |
_fetch_service_links, |
| 13 |
_normalize_href, |
| 14 |
resolve_endpoint_paths, |
| 15 |
) |
| 16 |
|
| 17 |
API_ENDPOINT = URL("https://cookidoo.ch") |
| 18 |
|
| 19 |
|
| 20 |
@pytest.mark.parametrize( |
| 21 |
("href", "const_template", "expected"), |
| 22 |
[ |
| 23 |
# Absolute href, plain {var} tokens. |
| 24 |
( |
| 25 |
"https://de.web.production-eu.cookidoo.vorwerk-digital.com/planning/{lang}/api/my-week/{dayKey}", |
| 26 |
"planning/{language}/api/my-week/{day}", |
| 27 |
"planning/{language}/api/my-week/{day}", |
| 28 |
), |
| 29 |
# Relative href with a trailing RFC 6570 query template to strip. |
| 30 |
( |
| 31 |
"/profile/{lang}/login{?redirectAfterLogin}", |
| 32 |
"profile/{language}/login", |
| 33 |
"profile/{language}/login", |
| 34 |
), |
| 35 |
# RFC 6570 path-segment token ({/lang}) must keep its separating slash. |
| 36 |
( |
| 37 |
"https://de.web.production-eu.cookidoo.vorwerk-digital.com/recipes/recipe{/lang}/{id}", |
| 38 |
"recipes/recipe/{language}/{id}", |
| 39 |
"recipes/recipe/{language}/{id}", |
| 40 |
), |
| 41 |
# No placeholders on either side. |
| 42 |
( |
| 43 |
"https://de.web.production-eu.cookidoo.vorwerk-digital.com/ownership/subscriptions", |
| 44 |
"ownership/subscriptions", |
| 45 |
"ownership/subscriptions", |
| 46 |
), |
| 47 |
# Absolute href with a single {var} token plus a trailing RFC 6570 |
| 48 |
# query template to strip (search:home). |
| 49 |
( |
| 50 |
"https://de.web.production-eu.cookidoo.vorwerk-digital.com/search/{lang}{?query,context,filters*,focus,pagination,limit}", |
| 51 |
"search/{locale}", |
| 52 |
"search/{locale}", |
| 53 |
), |
| 54 |
], |
| 55 |
) |
| 56 |
def test_normalize_href_success(href: str, const_template: str, expected: str) -> None: |
| 57 |
"""Discovered hrefs are normalized into our const.py template shape.""" |
| 58 |
assert _normalize_href(href, const_template) == expected |
| 59 |
|
| 60 |
|
| 61 |
def test_normalize_href_shape_mismatch_returns_none() -> None: |
| 62 |
"""A different number of variables signals an incompatible shape change.""" |
| 63 |
assert ( |
| 64 |
_normalize_href( |
| 65 |
"https://de.web.production-eu.cookidoo.vorwerk-digital.com/community/profile/{lang}", |
| 66 |
"community/profile", |
| 67 |
) |
| 68 |
is None |
| 69 |
) |
| 70 |
|
| 71 |
|
| 72 |
def test_normalize_href_known_token_reorder_returns_none() -> None: |
| 73 |
"""A known-name token in the wrong position signals a silent reorder.""" |
| 74 |
# {dayKey}/{recipeId} swapped relative to our {recipe}/{day}: same count, |
| 75 |
# both names recognized, but lined up against the wrong our-name. |
| 76 |
assert ( |
| 77 |
_normalize_href( |
| 78 |
"https://de.web.production-eu.cookidoo.vorwerk-digital.com/planning/{lang}/api/my-day/{recipeId}/recipes/{dayKey}", |
| 79 |
"planning/{language}/api/my-day/{day}/recipes/{recipe}", |
| 80 |
) |
| 81 |
is None |
| 82 |
) |
| 83 |
|
| 84 |
|
| 85 |
def test_normalize_href_unknown_token_falls_back_to_positional() -> None: |
| 86 |
"""A token name we don't recognize still substitutes positionally.""" |
| 87 |
assert ( |
| 88 |
_normalize_href( |
| 89 |
"https://de.web.production-eu.cookidoo.vorwerk-digital.com/ownership/{someNewToken}", |
| 90 |
"ownership/{language}", |
| 91 |
) |
| 92 |
== "ownership/{language}" |
| 93 |
) |
| 94 |
|
| 95 |
|
| 96 |
async def test_fetch_service_links_sends_discovery_headers( |
| 97 |
session: ClientSession, mocked: aioresponses |
| 98 |
) -> None: |
| 99 |
"""Discovery GETs carry a browser User-Agent to avoid Cloudflare bot-filtering.""" |
| 100 |
service_url = API_ENDPOINT / "shopping/.well-known/home" |
| 101 |
mocked.get(service_url, payload={"_links": {}}) |
| 102 |
|
| 103 |
await _fetch_service_links(session, service_url) |
| 104 |
|
| 105 |
request = next(iter(mocked.requests.values()))[0] |
| 106 |
sent_headers = request.kwargs["headers"] |
| 107 |
assert sent_headers["ACCEPT"] == "application/json" |
| 108 |
assert "Mozilla" in sent_headers["User-Agent"] |
| 109 |
|
| 110 |
|
| 111 |
async def test_fetch_service_links_success( |
| 112 |
session: ClientSession, mocked: aioresponses |
| 113 |
) -> None: |
| 114 |
"""A well-formed HAL document is parsed into a rel -> href mapping.""" |
| 115 |
service_url = API_ENDPOINT / "shopping/.well-known/home" |
| 116 |
mocked.get( |
| 117 |
service_url, |
| 118 |
payload={ |
| 119 |
"_links": { |
| 120 |
"pantry:home": {"href": "/shopping/{lang}"}, |
| 121 |
"pantry:list-variant": [ |
| 122 |
{"href": "/shopping/{lang}/a"}, |
| 123 |
{"href": "/shopping/{lang}/b"}, |
| 124 |
], |
| 125 |
"pantry:broken": {"notAnHref": True}, |
| 126 |
"pantry:empty-list": [], |
| 127 |
"pantry:weird": 123, |
| 128 |
} |
| 129 |
}, |
| 130 |
) |
| 131 |
links = await _fetch_service_links(session, service_url) |
| 132 |
assert links == { |
| 133 |
"pantry:home": "/shopping/{lang}", |
| 134 |
"pantry:list-variant": "/shopping/{lang}/a", |
| 135 |
} |
| 136 |
|
| 137 |
|
| 138 |
async def test_fetch_service_links_non_200( |
| 139 |
session: ClientSession, mocked: aioresponses |
| 140 |
) -> None: |
| 141 |
"""A non-200 response is treated as unavailable, not an error.""" |
| 142 |
service_url = API_ENDPOINT / "shopping/.well-known/home" |
| 143 |
mocked.get(service_url, status=404) |
| 144 |
assert await _fetch_service_links(session, service_url) is None |
| 145 |
|
| 146 |
|
| 147 |
async def test_fetch_service_links_connection_error( |
| 148 |
session: ClientSession, mocked: aioresponses |
| 149 |
) -> None: |
| 150 |
"""A connection failure is swallowed and treated as unavailable.""" |
| 151 |
service_url = API_ENDPOINT / "shopping/.well-known/home" |
| 152 |
# No mock registered for this URL: aioresponses raises a ClientConnectionError. |
| 153 |
assert await _fetch_service_links(session, service_url) is None |
| 154 |
|
| 155 |
|
| 156 |
async def test_fetch_service_links_invalid_json( |
| 157 |
session: ClientSession, mocked: aioresponses |
| 158 |
) -> None: |
| 159 |
"""A response that isn't a JSON object is treated as unavailable.""" |
| 160 |
service_url = API_ENDPOINT / "shopping/.well-known/home" |
| 161 |
mocked.get(service_url, body="not json", content_type="application/json") |
| 162 |
assert await _fetch_service_links(session, service_url) is None |
| 163 |
|
| 164 |
|
| 165 |
async def test_fetch_service_links_no_links_key( |
| 166 |
session: ClientSession, mocked: aioresponses |
| 167 |
) -> None: |
| 168 |
"""A JSON object without a `_links` mapping is treated as unavailable.""" |
| 169 |
service_url = API_ENDPOINT / "shopping/.well-known/home" |
| 170 |
mocked.get(service_url, payload={"meta": {}}) |
| 171 |
assert await _fetch_service_links(session, service_url) is None |
| 172 |
|
| 173 |
|
| 174 |
def _mock_all_services( |
| 175 |
mocked: aioresponses, overrides: dict[str, dict[str, object]] | None = None |
| 176 |
) -> None: |
| 177 |
"""Mock every service's .well-known/home with a valid response for every rel. |
| 178 |
|
| 179 |
``overrides`` can replace individual service mocks (e.g. with a 404, or a |
| 180 |
payload missing/mismatching a specific rel) by service name. |
| 181 |
""" |
| 182 |
overrides = overrides or {} |
| 183 |
rels_by_service: dict[str, list[str]] = {} |
| 184 |
for rel, (service, _template) in ENDPOINT_RELS.items(): |
| 185 |
rels_by_service.setdefault(service, []).append(rel) |
| 186 |
|
| 187 |
for service, rels in rels_by_service.items(): |
| 188 |
service_url = API_ENDPOINT / service / ".well-known/home" |
| 189 |
if service in overrides: |
| 190 |
mocked.get(service_url, **overrides[service]) |
| 191 |
continue |
| 192 |
links = {} |
| 193 |
for rel in rels: |
| 194 |
_, template = ENDPOINT_RELS[rel] |
| 195 |
placeholder_count = len(_TOKEN_RE.findall(template)) |
| 196 |
tokens = "".join(f"/{{var{i}}}" for i in range(placeholder_count)) |
| 197 |
links[rel] = {"href": f"/{service}{tokens}"} |
| 198 |
mocked.get(service_url, payload={"_links": links}) |
| 199 |
|
| 200 |
|
| 201 |
async def test_resolve_endpoint_paths_success( |
| 202 |
session: ClientSession, mocked: aioresponses |
| 203 |
) -> None: |
| 204 |
"""Every rel resolves successfully, returning a full overrides mapping.""" |
| 205 |
_mock_all_services(mocked) |
| 206 |
|
| 207 |
overrides = await resolve_endpoint_paths(session, API_ENDPOINT) |
| 208 |
|
| 209 |
assert set(overrides) == set(ENDPOINT_RELS) |
| 210 |
assert overrides["recipe:details"] == "recipes/recipe/{language}/{id}" |
| 211 |
|
| 212 |
|
| 213 |
async def test_resolve_endpoint_paths_unreachable_service_raises( |
| 214 |
session: ClientSession, mocked: aioresponses |
| 215 |
) -> None: |
| 216 |
"""An unreachable service raises CookidooRequestException.""" |
| 217 |
_mock_all_services(mocked, {"ownership": {"status": 404}}) |
| 218 |
|
| 219 |
with pytest.raises(CookidooRequestException): |
| 220 |
await resolve_endpoint_paths(session, API_ENDPOINT) |
| 221 |
|
| 222 |
|
| 223 |
async def test_resolve_endpoint_paths_reachable_but_no_usable_links_raises_parse_error( |
| 224 |
session: ClientSession, mocked: aioresponses |
| 225 |
) -> None: |
| 226 |
"""A reachable service with no usable hrefs is a parse error, not a request one. |
| 227 |
|
| 228 |
``_fetch_service_links`` returns an empty (not ``None``) dict when the |
| 229 |
document parsed fine but no link had a usable string href -- that's a |
| 230 |
shape problem, and mustn't be misreported as "could not reach the |
| 231 |
service" (which callers, incl. the retry-once logic, may treat as more |
| 232 |
likely to be transient). |
| 233 |
""" |
| 234 |
_mock_all_services( |
| 235 |
mocked, {"ownership": {"payload": {"_links": {"broken": {"notAnHref": True}}}}} |
| 236 |
) |
| 237 |
|
| 238 |
with pytest.raises(CookidooParseException): |
| 239 |
await resolve_endpoint_paths(session, API_ENDPOINT) |
| 240 |
|
| 241 |
|
| 242 |
async def test_resolve_endpoint_paths_missing_rel_raises( |
| 243 |
session: ClientSession, mocked: aioresponses |
| 244 |
) -> None: |
| 245 |
"""A service reachable but no longer exposing our rel raises a parse error.""" |
| 246 |
_mock_all_services( |
| 247 |
mocked, |
| 248 |
{"ownership": {"payload": {"_links": {"other:rel": {"href": "/x"}}}}}, |
| 249 |
) |
| 250 |
|
| 251 |
with pytest.raises(CookidooParseException): |
| 252 |
await resolve_endpoint_paths(session, API_ENDPOINT) |
| 253 |
|
| 254 |
|
| 255 |
async def test_resolve_endpoint_paths_shape_mismatch_raises( |
| 256 |
session: ClientSession, mocked: aioresponses |
| 257 |
) -> None: |
| 258 |
"""A discovered href with an incompatible shape raises a parse error.""" |
| 259 |
_mock_all_services( |
| 260 |
mocked, |
| 261 |
{ |
| 262 |
"community/profile": { |
| 263 |
"payload": { |
| 264 |
"_links": { |
| 265 |
"community-profile:user-private-profile": { |
| 266 |
"href": "https://de.web.production-eu.cookidoo.vorwerk-digital.com/community/profile" |
| 267 |
} |
| 268 |
} |
| 269 |
} |
| 270 |
} |
| 271 |
}, |
| 272 |
) |
| 273 |
|
| 274 |
with pytest.raises(CookidooParseException): |
| 275 |
await resolve_endpoint_paths(session, API_ENDPOINT) |