Debian Codegraph @

tests/test_cookidoo.py

raw
1 """Unit tests for cookidoo-api."""
2
3 import asyncio
4 from collections.abc import Callable
5 from datetime import datetime
6 from http import HTTPStatus
7 import pathlib
8 import re
9 from typing import Any
10
11 from aiohttp import ClientError, ClientSession
12 from aioresponses import CallbackResult, aioresponses
13 from dotenv import load_dotenv
14 import pytest
15 from yarl import URL
16
17 from cookidoo_api import cooking_activity_from_push
18 from cookidoo_api.const import (
19 CIAM_LOGIN_SRV_URL,
20 OAUTH_CLIENT_ID,
21 OAUTH_REDIRECT_URI,
22 OIDC_DISCOVERY_URL,
23 )
24 from cookidoo_api.cookidoo import Cookidoo
25 from cookidoo_api.exceptions import (
26 CookidooAuthException,
27 CookidooConfigException,
28 CookidooException,
29 CookidooParseException,
30 CookidooRequestException,
31 )
32 from cookidoo_api.helpers import get_localization_options
33 from cookidoo_api.types import (
34 CookidooAdditionalItem,
35 CookidooAuthData,
36 CookidooConfig,
37 CookidooCookState,
38 CookidooIngredientItem,
39 CookidooSearchResult,
40 ThermomixMachineType,
41 )
42 from tests.conftest import TEST_CLIENT_ID, TEST_REDIRECT_URI
43 from tests.responses import (
44 COOKIDOO_TEST_LOGIN_PAGE_HTML,
45 COOKIDOO_TEST_OIDC_DISCOVERY,
46 COOKIDOO_TEST_PUSH_COOKING_ACTIVITY,
47 COOKIDOO_TEST_REFRESHED_TOKEN_RESPONSE,
48 COOKIDOO_TEST_RESPONSE_ACTIVE_SUBSCRIPTION,
49 COOKIDOO_TEST_RESPONSE_ADD_ADDITIONAL_ITEMS,
50 COOKIDOO_TEST_RESPONSE_ADD_CUSTOM_COLLECTION,
51 COOKIDOO_TEST_RESPONSE_ADD_CUSTOM_RECIPE,
52 COOKIDOO_TEST_RESPONSE_ADD_CUSTOM_RECIPES_TO_CALENDAR,
53 COOKIDOO_TEST_RESPONSE_ADD_INGREDIENTS_FOR_CUSTOM_RECIPES,
54 COOKIDOO_TEST_RESPONSE_ADD_INGREDIENTS_FOR_RECIPES,
55 COOKIDOO_TEST_RESPONSE_ADD_MANAGED_COLLECTION,
56 COOKIDOO_TEST_RESPONSE_ADD_RECIPES_TO_CALENDAR,
57 COOKIDOO_TEST_RESPONSE_ADD_RECIPES_TO_CUSTOM_COLLECTION,
58 COOKIDOO_TEST_RESPONSE_CALENDAR_WEEK,
59 COOKIDOO_TEST_RESPONSE_DEVICES,
60 COOKIDOO_TEST_RESPONSE_DEVICES_EMPTY,
61 COOKIDOO_TEST_RESPONSE_DEVICES_MULTIPLE,
62 COOKIDOO_TEST_RESPONSE_EDIT_ADDITIONAL_ITEMS,
63 COOKIDOO_TEST_RESPONSE_EDIT_ADDITIONAL_ITEMS_OWNERSHIP,
64 COOKIDOO_TEST_RESPONSE_EDIT_INGREDIENTS_OWNERSHIP,
65 COOKIDOO_TEST_RESPONSE_GET_ADDITIONAL_ITEMS,
66 COOKIDOO_TEST_RESPONSE_GET_CUSTOM_COLLECTIONS,
67 COOKIDOO_TEST_RESPONSE_GET_CUSTOM_RECIPE,
68 COOKIDOO_TEST_RESPONSE_GET_INGREDIENTS_FOR_CUSTOM_RECIPES,
69 COOKIDOO_TEST_RESPONSE_GET_INGREDIENTS_FOR_RECIPES,
70 COOKIDOO_TEST_RESPONSE_GET_MANAGED_COLLECTIONS,
71 COOKIDOO_TEST_RESPONSE_GET_RECIPE_DETAILS,
72 COOKIDOO_TEST_RESPONSE_GET_SHOPPING_LIST_RECIPES,
73 COOKIDOO_TEST_RESPONSE_INACTIVE_SUBSCRIPTION,
74 COOKIDOO_TEST_RESPONSE_LIST_CUSTOM_RECIPES,
75 COOKIDOO_TEST_RESPONSE_MOBILE_HOME,
76 COOKIDOO_TEST_RESPONSE_MONITORED_DEVICES,
77 COOKIDOO_TEST_RESPONSE_REMOVE_CUSTOM_RECIPE_FROM_CALENDAR,
78 COOKIDOO_TEST_RESPONSE_REMOVE_RECIPE_FROM_CALENDAR,
79 COOKIDOO_TEST_RESPONSE_REMOVE_RECIPE_FROM_CUSTOM_COLLECTION,
80 COOKIDOO_TEST_RESPONSE_RMI_CONFIG,
81 COOKIDOO_TEST_RESPONSE_SEARCH_RECIPES,
82 COOKIDOO_TEST_RESPONSE_USER_INFO,
83 COOKIDOO_TEST_TOKEN_RESPONSE,
84 )
85
86 load_dotenv()
87
88
89 class TestGetterSetter:
90 """Tests for getter and setter."""
91
92 @pytest.mark.parametrize(
93 ("country", "language", "expected_domain"),
94 [
95 ("ch", "de-CH", "https://cookidoo.ch"),
96 ("de", "de-DE", "https://cookidoo.de"),
97 ("ma", "en", "https://cookidoo.international"),
98 ("ie", "en-GB", "https://cookidoo.co.uk"),
99 ("gb", "en-GB", "https://cookidoo.co.uk"),
100 ],
101 )
102 async def test_api_endpoint(
103 self,
104 mocked: aioresponses,
105 session: ClientSession,
106 country: str,
107 language: str,
108 expected_domain: str,
109 ) -> None:
110 """Test api endpoint for different localizations."""
111 cookidoo = Cookidoo(
112 session,
113 cfg=CookidooConfig(
114 localization=(
115 await get_localization_options(country=country, language=language)
116 )[0],
117 ),
118 )
119
120 assert str(cookidoo.api_endpoint) == expected_domain
121
122 async def test_localization(self, cookidoo: Cookidoo) -> None:
123 """Test localization property."""
124 loc = cookidoo.localization
125 assert loc.language == "de-CH"
126 assert loc.country_code == "ch"
127
128
129 TOKEN_ENDPOINT = "https://ciam.prod.cookidoo.vorwerk-digital.com/token-srv/token"
130 AUTHZ_RE = re.compile(r".*/authz-srv/authz.*")
131
132
133 class TestLogin:
134 """Tests for the OAuth2 authorization-code login flow."""
135
136 @staticmethod
137 def _mock_authorize(
138 mocked: aioresponses, *, body: str = COOKIDOO_TEST_LOGIN_PAGE_HTML
139 ) -> dict[str, str]:
140 """Serve the login page and capture the ``state`` the client sent."""
141 captured: dict[str, str] = {}
142
143 def _serve(url: URL, **kwargs: Any) -> CallbackResult:
144 captured["state"] = url.query["state"]
145 return CallbackResult(status=HTTPStatus.OK, body=body)
146
147 mocked.get(AUTHZ_RE, callback=_serve, repeat=True)
148 return captured
149
150 @staticmethod
151 def _app_redirect(
152 captured: dict[str, str], *, code: str | None = "test-code"
153 ) -> Callable[..., CallbackResult]:
154 """Redirect to the app scheme, echoing the state like CIAM does."""
155
156 def _redirect(url: URL, **kwargs: Any) -> CallbackResult:
157 query = [f"code={code}"] if code else []
158 query.append(f"state={captured['state']}")
159 return CallbackResult(
160 status=HTTPStatus.FOUND,
161 headers={"Location": f"{TEST_REDIRECT_URI}?{'&'.join(query)}"},
162 )
163
164 return _redirect
165
166 @classmethod
167 def _mock_login_flow(
168 cls,
169 mocked: aioresponses,
170 *,
171 page_body: str = COOKIDOO_TEST_LOGIN_PAGE_HTML,
172 code: str | None = "test-code",
173 ) -> dict[str, str]:
174 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
175 captured = cls._mock_authorize(mocked, body=page_body)
176 mocked.post(CIAM_LOGIN_SRV_URL, callback=cls._app_redirect(captured, code=code))
177 mocked.post(TOKEN_ENDPOINT, payload=COOKIDOO_TEST_TOKEN_RESPONSE)
178 return captured
179
180 async def test_login_success(
181 self, mocked: aioresponses, cookidoo: Cookidoo
182 ) -> None:
183 """Test a successful OAuth2 login."""
184 self._mock_login_flow(mocked)
185
186 await cookidoo.login()
187
188 assert cookidoo._logged_in
189 assert cookidoo.auth_data is not None
190 assert cookidoo.auth_data.access_token == "test-access-token"
191 assert cookidoo.auth_data.refresh_token == "test-refresh-token"
192 assert cookidoo._api_headers["Authorization"] == "Bearer test-access-token"
193
194 async def test_token_request_is_a_public_client_request(
195 self, mocked: aioresponses, cookidoo: Cookidoo
196 ) -> None:
197 """The code exchange identifies the client without authenticating it.
198
199 CIAM accepts the exchange on the strength of the PKCE ``code_verifier``,
200 so no client secret is sent (and none is configurable).
201 """
202 self._mock_login_flow(mocked)
203
204 await cookidoo.login()
205
206 (_, kwargs) = mocked.requests[("POST", URL(TOKEN_ENDPOINT))][0]
207 assert kwargs["data"]["client_id"] == TEST_CLIENT_ID
208 assert kwargs["data"]["code_verifier"]
209 assert "client_secret" not in kwargs["data"]
210 assert "Authorization" not in kwargs["headers"]
211
212 async def test_refresh_is_a_public_client_request(
213 self, mocked: aioresponses, cookidoo: Cookidoo
214 ) -> None:
215 """The refresh grant identifies the client the same way."""
216 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
217 mocked.post(TOKEN_ENDPOINT, payload=COOKIDOO_TEST_TOKEN_RESPONSE)
218 cookidoo.apply_auth_data(CookidooAuthData("old", "test-refresh-token", 0.0))
219
220 await cookidoo.refresh()
221
222 (_, kwargs) = mocked.requests[("POST", URL(TOKEN_ENDPOINT))][0]
223 assert kwargs["data"]["client_id"] == TEST_CLIENT_ID
224 assert "client_secret" not in kwargs["data"]
225 assert "Authorization" not in kwargs["headers"]
226
227 async def test_login_page_unreachable(
228 self, mocked: aioresponses, cookidoo: Cookidoo
229 ) -> None:
230 """Test login when the authorize/login page returns an error."""
231 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
232 mocked.get(AUTHZ_RE, status=HTTPStatus.SERVICE_UNAVAILABLE)
233
234 with pytest.raises(CookidooAuthException, match="could not reach login page"):
235 await cookidoo.login()
236
237 async def test_login_page_parse_error(
238 self, mocked: aioresponses, cookidoo: Cookidoo
239 ) -> None:
240 """Test login when requestId cannot be extracted."""
241 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
242 mocked.get(
243 AUTHZ_RE,
244 status=HTTPStatus.OK,
245 body="<html><body>No form here</body></html>",
246 )
247
248 with pytest.raises(CookidooParseException, match="could not extract requestId"):
249 await cookidoo.login()
250
251 async def test_login_invalid_credentials(
252 self, mocked: aioresponses, cookidoo: Cookidoo
253 ) -> None:
254 """Invalid credentials yield no authorization code."""
255 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
256 mocked.get(AUTHZ_RE, status=HTTPStatus.OK, body=COOKIDOO_TEST_LOGIN_PAGE_HTML)
257 # The login service replies 200 (re-renders the form) instead of redirecting.
258 mocked.post(CIAM_LOGIN_SRV_URL, status=HTTPStatus.OK)
259
260 with pytest.raises(CookidooAuthException, match="invalid credentials"):
261 await cookidoo.login()
262
263 async def test_login_follows_intermediate_redirects(
264 self, mocked: aioresponses, cookidoo: Cookidoo
265 ) -> None:
266 """Redirects before the app scheme are followed to capture the code."""
267 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
268 captured = self._mock_authorize(mocked)
269 interstitial = (
270 "https://ciam.prod.cookidoo.vorwerk-digital.com/login-srv/continue"
271 )
272 mocked.post(
273 CIAM_LOGIN_SRV_URL,
274 status=HTTPStatus.FOUND,
275 headers={"Location": interstitial},
276 )
277 mocked.get(interstitial, callback=self._app_redirect(captured))
278 mocked.post(TOKEN_ENDPOINT, payload=COOKIDOO_TEST_TOKEN_RESPONSE)
279
280 await cookidoo.login()
281
282 assert cookidoo._logged_in
283
284 async def test_login_refuses_redirect_off_the_auth_host(
285 self, mocked: aioresponses, cookidoo: Cookidoo
286 ) -> None:
287 """A redirect leaving the CIAM origin is refused instead of followed."""
288 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
289 self._mock_authorize(mocked)
290 mocked.post(
291 CIAM_LOGIN_SRV_URL,
292 status=HTTPStatus.FOUND,
293 headers={"Location": "https://evil.example/login-srv/continue"},
294 )
295
296 with pytest.raises(
297 CookidooAuthException, match="redirected off the authentication host"
298 ):
299 await cookidoo.login()
300
301 async def test_login_state_mismatch(
302 self, mocked: aioresponses, cookidoo: Cookidoo
303 ) -> None:
304 """A state that does not match the one sent aborts the login."""
305 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
306 self._mock_authorize(mocked)
307 mocked.post(
308 CIAM_LOGIN_SRV_URL,
309 status=HTTPStatus.FOUND,
310 headers={"Location": f"{TEST_REDIRECT_URI}?code=test-code&state=tampered"},
311 )
312
313 with pytest.raises(CookidooAuthException, match="state mismatch"):
314 await cookidoo.login()
315
316 async def test_login_state_missing(
317 self, mocked: aioresponses, cookidoo: Cookidoo
318 ) -> None:
319 """A callback that omits the state entirely counts as a mismatch."""
320 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
321 self._mock_authorize(mocked)
322 mocked.post(
323 CIAM_LOGIN_SRV_URL,
324 status=HTTPStatus.FOUND,
325 headers={"Location": f"{TEST_REDIRECT_URI}?code=test-code"},
326 )
327
328 with pytest.raises(CookidooAuthException, match="state mismatch"):
329 await cookidoo.login()
330
331 async def test_login_sends_the_state_it_verifies(
332 self, mocked: aioresponses, cookidoo: Cookidoo
333 ) -> None:
334 """The state accepted on the callback is the one the client sent."""
335 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
336 captured = self._mock_authorize(mocked)
337 mocked.post(CIAM_LOGIN_SRV_URL, callback=self._app_redirect(captured))
338 mocked.post(TOKEN_ENDPOINT, payload=COOKIDOO_TEST_TOKEN_RESPONSE)
339
340 await cookidoo.login()
341
342 assert captured["state"]
343 assert cookidoo._logged_in
344
345 async def test_login_redirect_loop(
346 self, mocked: aioresponses, cookidoo: Cookidoo
347 ) -> None:
348 """An endless redirect chain gives up instead of looping forever."""
349 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
350 mocked.get(AUTHZ_RE, status=HTTPStatus.OK, body=COOKIDOO_TEST_LOGIN_PAGE_HTML)
351 loop_url = "https://ciam.prod.cookidoo.vorwerk-digital.com/login-srv/loop"
352 mocked.post(
353 CIAM_LOGIN_SRV_URL,
354 status=HTTPStatus.FOUND,
355 headers={"Location": loop_url},
356 )
357 mocked.get(
358 re.compile(r".*/login-srv/loop.*"),
359 status=HTTPStatus.FOUND,
360 headers={"Location": loop_url},
361 repeat=True,
362 )
363
364 with pytest.raises(CookidooAuthException, match="invalid credentials"):
365 await cookidoo.login()
366
367 async def test_login_token_exchange_failure(
368 self, mocked: aioresponses, cookidoo: Cookidoo
369 ) -> None:
370 """A rejected code exchange surfaces as an auth exception."""
371 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
372 captured = self._mock_authorize(mocked)
373 mocked.post(CIAM_LOGIN_SRV_URL, callback=self._app_redirect(captured))
374 mocked.post(TOKEN_ENDPOINT, status=HTTPStatus.BAD_REQUEST)
375
376 with pytest.raises(CookidooAuthException, match="Token exchange failed"):
377 await cookidoo.login()
378
379 async def test_login_unexpected_token_response(
380 self, mocked: aioresponses, cookidoo: Cookidoo
381 ) -> None:
382 """A token response without an access token surfaces as an auth exception."""
383 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
384 captured = self._mock_authorize(mocked)
385 mocked.post(CIAM_LOGIN_SRV_URL, callback=self._app_redirect(captured))
386 mocked.post(TOKEN_ENDPOINT, payload={"token_type": "Bearer"})
387
388 with pytest.raises(CookidooAuthException, match="Unexpected token response"):
389 await cookidoo.login()
390
391 async def test_discovery_is_cached(
392 self, mocked: aioresponses, cookidoo: Cookidoo
393 ) -> None:
394 """The OIDC discovery document is only fetched once."""
395 captured = self._mock_login_flow(mocked)
396
397 await cookidoo.login()
398 # A second login must not hit the discovery endpoint again, it is only
399 # mocked once and a second request would fail.
400 mocked.post(CIAM_LOGIN_SRV_URL, callback=self._app_redirect(captured))
401 mocked.post(TOKEN_ENDPOINT, payload=COOKIDOO_TEST_TOKEN_RESPONSE)
402
403 await cookidoo.login()
404
405 assert cookidoo._logged_in
406
407 def test_default_oauth_client_is_the_public_mobile_client(self) -> None:
408 """The client identifiers default to the app's public ones."""
409 cfg = CookidooConfig()
410
411 assert cfg.client_id == OAUTH_CLIENT_ID
412 assert cfg.redirect_uri == OAUTH_REDIRECT_URI
413 assert not hasattr(cfg, "client_secret")
414
415 @pytest.mark.parametrize(
416 ("client_id", "redirect_uri", "expected"),
417 [
418 ("", TEST_REDIRECT_URI, "client_id"),
419 (TEST_CLIENT_ID, "", "redirect_uri"),
420 ("", "", "client_id, redirect_uri"),
421 ],
422 )
423 async def test_login_with_blanked_client_config(
424 self,
425 session: ClientSession,
426 client_id: str,
427 redirect_uri: str,
428 expected: str,
429 ) -> None:
430 """Overriding an identifier with an empty value is rejected early."""
431 cookidoo = Cookidoo(
432 session,
433 cfg=CookidooConfig(client_id=client_id, redirect_uri=redirect_uri),
434 )
435
436 with pytest.raises(CookidooConfigException, match=expected):
437 await cookidoo.login()
438
439 async def test_refresh_with_blanked_client_config(
440 self, session: ClientSession
441 ) -> None:
442 """Refreshing a restored token validates the client config too."""
443 cookidoo = Cookidoo(session, cfg=CookidooConfig(client_id=""))
444 cookidoo.apply_auth_data(CookidooAuthData("old", "ref", 9999999999.0))
445
446 with pytest.raises(
447 CookidooConfigException, match="Missing OAuth2 client configuration"
448 ):
449 await cookidoo.refresh()
450
451 @pytest.mark.parametrize(
452 "exception",
453 [
454 TimeoutError,
455 ClientError,
456 ],
457 )
458 async def test_request_exceptions(
459 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
460 ) -> None:
461 """Test that transport exceptions surface as request exceptions."""
462 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
463 mocked.get(AUTHZ_RE, exception=exception)
464
465 with pytest.raises(CookidooRequestException):
466 await cookidoo.login()
467
468
469 class TestTokenPersistenceAndRefresh:
470 """Tests for token persistence and refresh."""
471
472 async def test_save_and_load_token(
473 self, cookidoo: Cookidoo, tmp_path: pathlib.Path
474 ) -> None:
475 """Test saving and restoring tokens across instances."""
476 cookidoo.apply_auth_data(CookidooAuthData("acc", "ref", 9999999999.0))
477 token_file = tmp_path / "token.json"
478 cookidoo.save_token(token_file)
479 assert token_file.exists()
480
481 fresh = Cookidoo(cookidoo._session)
482 fresh.load_token(token_file)
483 assert fresh._logged_in
484 assert fresh.auth_data is not None
485 assert fresh.auth_data.access_token == "acc"
486 assert fresh.auth_data.refresh_token == "ref"
487
488 async def test_save_token_not_logged_in(
489 self, cookidoo: Cookidoo, tmp_path: pathlib.Path
490 ) -> None:
491 """Saving without a login raises."""
492 with pytest.raises(CookidooConfigException, match="not logged in"):
493 cookidoo.save_token(tmp_path / "token.json")
494
495 async def test_load_token_missing_file(self, cookidoo: Cookidoo) -> None:
496 """Loading a missing token file raises."""
497 with pytest.raises(CookidooConfigException, match="Cannot load token"):
498 cookidoo.load_token("/nonexistent/path/token.json")
499
500 async def test_refresh(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
501 """Test refreshing the access token."""
502 cookidoo.apply_auth_data(CookidooAuthData("old", "ref", 9999999999.0))
503 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
504 mocked.post(TOKEN_ENDPOINT, payload=COOKIDOO_TEST_REFRESHED_TOKEN_RESPONSE)
505
506 await cookidoo.refresh()
507
508 assert cookidoo.auth_data is not None
509 assert cookidoo.auth_data.access_token == "refreshed-access-token"
510 assert cookidoo.auth_data.refresh_token == "refreshed-refresh-token"
511
512 async def test_refresh_without_login(self, cookidoo: Cookidoo) -> None:
513 """Refreshing without a refresh token raises."""
514 with pytest.raises(CookidooAuthException, match="no refresh token available"):
515 await cookidoo.refresh()
516
517 async def test_refresh_rejected(
518 self, mocked: aioresponses, cookidoo: Cookidoo
519 ) -> None:
520 """A rejected refresh surfaces as an auth exception."""
521 cookidoo.apply_auth_data(CookidooAuthData("old", "ref", 9999999999.0))
522 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
523 mocked.post(TOKEN_ENDPOINT, status=HTTPStatus.UNAUTHORIZED)
524
525 with pytest.raises(CookidooAuthException, match="Token refresh failed"):
526 await cookidoo.refresh()
527
528 async def test_refresh_request_exception(
529 self, mocked: aioresponses, cookidoo: Cookidoo
530 ) -> None:
531 """A transport error during refresh surfaces as a request exception."""
532 cookidoo.apply_auth_data(CookidooAuthData("old", "ref", 9999999999.0))
533 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
534 mocked.post(TOKEN_ENDPOINT, exception=ClientError())
535
536 with pytest.raises(CookidooRequestException, match="Token refresh failed"):
537 await cookidoo.refresh()
538
539 async def test_refresh_timeout(
540 self, mocked: aioresponses, cookidoo: Cookidoo
541 ) -> None:
542 """A timeout during refresh surfaces as a request exception."""
543 cookidoo.apply_auth_data(CookidooAuthData("old", "ref", 9999999999.0))
544 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
545 mocked.post(TOKEN_ENDPOINT, exception=TimeoutError())
546
547 with pytest.raises(CookidooRequestException, match="connection timeout"):
548 await cookidoo.refresh()
549
550 async def test_refresh_discovery_request_exception(
551 self, mocked: aioresponses, cookidoo: Cookidoo
552 ) -> None:
553 """A transport error while discovering the token endpoint is normalized."""
554 cookidoo.apply_auth_data(CookidooAuthData("old", "ref", 9999999999.0))
555 mocked.get(OIDC_DISCOVERY_URL, exception=ClientError())
556
557 with pytest.raises(CookidooRequestException, match="Token refresh failed"):
558 await cookidoo.refresh()
559
560 async def test_refresh_discovery_timeout(
561 self, mocked: aioresponses, cookidoo: Cookidoo
562 ) -> None:
563 """A timeout while discovering the token endpoint is normalized."""
564 cookidoo.apply_auth_data(CookidooAuthData("old", "ref", 9999999999.0))
565 mocked.get(OIDC_DISCOVERY_URL, exception=TimeoutError())
566
567 with pytest.raises(CookidooRequestException, match="connection timeout"):
568 await cookidoo.refresh()
569
570 async def test_auto_refresh_failure_is_normalized(
571 self, mocked: aioresponses, cookidoo: Cookidoo
572 ) -> None:
573 """A failed implicit refresh raises a Cookidoo exception, not a raw one.
574
575 ``_ensure_token()`` runs before the request helper's own try block, so
576 anything it raises reaches the caller unchanged.
577 """
578 cookidoo.apply_auth_data(CookidooAuthData("expired", "ref", 0.0))
579 mocked.get(OIDC_DISCOVERY_URL, exception=TimeoutError())
580
581 with pytest.raises(CookidooRequestException, match="connection timeout"):
582 await cookidoo.get_user_info()
583
584 async def test_no_refresh_on_valid_token(
585 self, mocked: aioresponses, cookidoo: Cookidoo
586 ) -> None:
587 """A still valid access token is used as is, without a refresh."""
588 cookidoo.apply_auth_data(CookidooAuthData("valid", "ref", 9999999999.0))
589 mocked.get(
590 "https://cookidoo.ch/community/profile/de-CH",
591 payload=COOKIDOO_TEST_RESPONSE_USER_INFO,
592 status=HTTPStatus.OK,
593 )
594
595 await cookidoo.get_user_info()
596
597 # No token endpoint was mocked, so a refresh would have failed.
598 assert cookidoo.auth_data is not None
599 assert cookidoo.auth_data.access_token == "valid"
600
601 async def test_auto_refresh_on_expired_token(
602 self, mocked: aioresponses, cookidoo: Cookidoo
603 ) -> None:
604 """An expired access token is refreshed automatically before a request."""
605 cookidoo.apply_auth_data(CookidooAuthData("expired", "ref", 0.0))
606 mocked.get(OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY)
607 mocked.post(TOKEN_ENDPOINT, payload=COOKIDOO_TEST_REFRESHED_TOKEN_RESPONSE)
608 mocked.get(
609 "https://cookidoo.ch/community/profile/de-CH",
610 payload=COOKIDOO_TEST_RESPONSE_USER_INFO,
611 status=HTTPStatus.OK,
612 )
613
614 await cookidoo.get_user_info()
615
616 assert cookidoo.auth_data is not None
617 assert cookidoo.auth_data.access_token == "refreshed-access-token"
618
619 async def test_concurrent_requests_refresh_once(
620 self, mocked: aioresponses, cookidoo: Cookidoo
621 ) -> None:
622 """Concurrent requests across an expiry share a single refresh.
623
624 The server may rotate the refresh token, retiring the one a second
625 concurrent refresh would spend, so only one may be in flight.
626 """
627 refreshes = 0
628
629 async def _token_callback(url: Any, **kwargs: Any) -> CallbackResult:
630 nonlocal refreshes
631 refreshes += 1
632 # Suspend so the other callers reach _ensure_token meanwhile
633 await asyncio.sleep(0)
634 return CallbackResult(payload=COOKIDOO_TEST_REFRESHED_TOKEN_RESPONSE)
635
636 cookidoo.apply_auth_data(CookidooAuthData("expired", "ref", 0.0))
637 mocked.get(
638 OIDC_DISCOVERY_URL, payload=COOKIDOO_TEST_OIDC_DISCOVERY, repeat=True
639 )
640 mocked.post(TOKEN_ENDPOINT, callback=_token_callback, repeat=True)
641 mocked.get(
642 "https://cookidoo.ch/community/profile/de-CH",
643 payload=COOKIDOO_TEST_RESPONSE_USER_INFO,
644 status=HTTPStatus.OK,
645 repeat=True,
646 )
647
648 await asyncio.gather(*(cookidoo.get_user_info() for _ in range(3)))
649
650 assert refreshes == 1
651
652 assert cookidoo.auth_data is not None
653 assert cookidoo.auth_data.access_token == "refreshed-access-token"
654 assert cookidoo.auth_data.refresh_token == "refreshed-refresh-token"
655
656
657 class TestGetUserInfo:
658 """Tests for get_user_info method."""
659
660 async def test_get_user_info(
661 self, mocked: aioresponses, cookidoo: Cookidoo
662 ) -> None:
663 """Test for get_user_info."""
664
665 mocked.get(
666 "https://cookidoo.ch/community/profile/de-CH",
667 payload=COOKIDOO_TEST_RESPONSE_USER_INFO,
668 status=HTTPStatus.OK,
669 )
670
671 data = await cookidoo.get_user_info()
672 assert data.id == COOKIDOO_TEST_RESPONSE_USER_INFO["id"]
673 assert (
674 data.username == COOKIDOO_TEST_RESPONSE_USER_INFO["userInfo"]["username"] # type: ignore[index]
675 )
676 assert (
677 data.description
678 == COOKIDOO_TEST_RESPONSE_USER_INFO["userInfo"]["description"] # type: ignore[index]
679 )
680 assert (
681 data.picture == COOKIDOO_TEST_RESPONSE_USER_INFO["userInfo"]["picture"] # type: ignore[index]
682 )
683
684 @pytest.mark.parametrize(
685 "exception",
686 [
687 TimeoutError,
688 ClientError,
689 ],
690 )
691 async def test_request_exception(
692 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
693 ) -> None:
694 """Test request exceptions."""
695
696 mocked.get(
697 "https://cookidoo.ch/community/profile/de-CH",
698 exception=exception,
699 )
700
701 with pytest.raises(CookidooRequestException):
702 await cookidoo.get_user_info()
703
704 async def test_endpoint_discovery_retries_once_and_succeeds(
705 self,
706 mocked: aioresponses,
707 cookidoo: Cookidoo,
708 monkeypatch: pytest.MonkeyPatch,
709 ) -> None:
710 """A transient discovery failure is retried once and can still succeed."""
711 calls = 0
712
713 async def _flaky(*_args: object, **_kwargs: object) -> dict[str, str]:
714 nonlocal calls
715 calls += 1
716 if calls == 1:
717 raise CookidooRequestException("boom")
718 return {
719 "community-profile:user-private-profile": "community/profile/{language}"
720 }
721
722 monkeypatch.setattr(
723 "cookidoo_api.cookidoo.resolve_endpoint_paths",
724 _flaky,
725 )
726 mocked.get(
727 "https://cookidoo.ch/community/profile/de-CH",
728 payload=COOKIDOO_TEST_RESPONSE_USER_INFO,
729 status=HTTPStatus.OK,
730 )
731
732 await cookidoo.get_user_info()
733
734 assert calls == 2
735 assert cookidoo._endpoints_resolved
736 assert (
737 cookidoo._endpoint_overrides["community-profile:user-private-profile"]
738 == "community/profile/{language}"
739 )
740
741 async def test_endpoint_discovery_failure_raises_after_retry(
742 self,
743 cookidoo: Cookidoo,
744 monkeypatch: pytest.MonkeyPatch,
745 ) -> None:
746 """A discovery failure that persists through the retry propagates."""
747
748 async def _raise(*_args: object, **_kwargs: object) -> dict[str, str]:
749 raise CookidooParseException("boom")
750
751 monkeypatch.setattr(
752 "cookidoo_api.cookidoo.resolve_endpoint_paths",
753 _raise,
754 )
755
756 with pytest.raises(CookidooParseException):
757 await cookidoo.get_user_info()
758
759 assert not cookidoo._endpoints_resolved
760
761 async def test_endpoint_discovery_runs_only_once_per_instance(
762 self,
763 mocked: aioresponses,
764 cookidoo: Cookidoo,
765 monkeypatch: pytest.MonkeyPatch,
766 ) -> None:
767 """Once resolved, discovery is not repeated on subsequent calls."""
768 calls = 0
769
770 async def _resolve(*_args: object, **_kwargs: object) -> dict[str, str]:
771 nonlocal calls
772 calls += 1
773 return {
774 "community-profile:user-private-profile": "community/profile/{language}",
775 "ownership:subscriptions": "ownership/subscriptions",
776 }
777
778 monkeypatch.setattr(
779 "cookidoo_api.cookidoo.resolve_endpoint_paths",
780 _resolve,
781 )
782 mocked.get(
783 "https://cookidoo.ch/community/profile/de-CH",
784 payload=COOKIDOO_TEST_RESPONSE_USER_INFO,
785 status=HTTPStatus.OK,
786 repeat=True,
787 )
788
789 await cookidoo.get_user_info()
790 await cookidoo.get_user_info()
791
792 assert calls == 1
793
794 async def test_endpoint_discovery_is_concurrency_safe(
795 self,
796 mocked: aioresponses,
797 cookidoo: Cookidoo,
798 monkeypatch: pytest.MonkeyPatch,
799 ) -> None:
800 """Concurrent callers on a fresh instance share a single discovery run."""
801 calls = 0
802
803 async def _resolve(*_args: object, **_kwargs: object) -> dict[str, str]:
804 nonlocal calls
805 calls += 1
806 await asyncio.sleep(0) # yield, so concurrent callers can interleave
807 return {
808 "community-profile:user-private-profile": "community/profile/{language}",
809 "ownership:subscriptions": "ownership/subscriptions",
810 }
811
812 monkeypatch.setattr(
813 "cookidoo_api.cookidoo.resolve_endpoint_paths",
814 _resolve,
815 )
816 mocked.get(
817 "https://cookidoo.ch/community/profile/de-CH",
818 payload=COOKIDOO_TEST_RESPONSE_USER_INFO,
819 status=HTTPStatus.OK,
820 repeat=True,
821 )
822
823 await asyncio.gather(
824 cookidoo.get_user_info(),
825 cookidoo.get_user_info(),
826 cookidoo.get_user_info(),
827 )
828
829 assert calls == 1
830
831 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
832 """Test unauthorized exception."""
833 mocked.get(
834 "https://cookidoo.ch/community/profile/de-CH",
835 status=HTTPStatus.UNAUTHORIZED,
836 payload={"error_description": ""},
837 )
838 with pytest.raises(CookidooAuthException):
839 await cookidoo.get_user_info()
840
841 async def test_non_mapping_response(
842 self, mocked: aioresponses, cookidoo: Cookidoo
843 ) -> None:
844 """Test response shape validation."""
845 mocked.get(
846 "https://cookidoo.ch/community/profile/de-CH",
847 status=HTTPStatus.OK,
848 payload=[],
849 )
850
851 with pytest.raises(CookidooParseException):
852 await cookidoo.get_user_info()
853
854 async def test_invalid_mapping_response(
855 self, mocked: aioresponses, cookidoo: Cookidoo
856 ) -> None:
857 """Test converter parse exception for missing keys."""
858 mocked.get(
859 "https://cookidoo.ch/community/profile/de-CH",
860 status=HTTPStatus.OK,
861 payload={},
862 )
863
864 with pytest.raises(CookidooParseException):
865 await cookidoo.get_user_info()
866
867 @pytest.mark.parametrize(
868 ("status", "exception"),
869 [
870 (HTTPStatus.OK, CookidooParseException),
871 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
872 ],
873 )
874 async def test_parse_exception(
875 self,
876 mocked: aioresponses,
877 cookidoo: Cookidoo,
878 status: HTTPStatus,
879 exception: type[CookidooException],
880 ) -> None:
881 """Test parse exceptions."""
882 mocked.get(
883 "https://cookidoo.ch/community/profile/de-CH",
884 status=status,
885 body="not json",
886 content_type="application/json",
887 )
888
889 with pytest.raises(exception):
890 await cookidoo.get_user_info()
891
892
893 class TestGetActiveSubscription:
894 """Tests for get_active_subscription method."""
895
896 async def test_get_active_subscription(
897 self, mocked: aioresponses, cookidoo: Cookidoo
898 ) -> None:
899 """Test for get_active_subscription."""
900
901 mocked.get(
902 "https://cookidoo.ch/ownership/subscriptions",
903 payload=COOKIDOO_TEST_RESPONSE_ACTIVE_SUBSCRIPTION,
904 status=HTTPStatus.OK,
905 )
906
907 data = await cookidoo.get_active_subscription()
908 assert data
909 assert data.active
910 assert data.status == "RUNNING"
911
912 async def test_get_inactive_subscription(
913 self, mocked: aioresponses, cookidoo: Cookidoo
914 ) -> None:
915 """Test for get_active_subscription."""
916
917 mocked.get(
918 "https://cookidoo.ch/ownership/subscriptions",
919 payload=COOKIDOO_TEST_RESPONSE_INACTIVE_SUBSCRIPTION,
920 status=HTTPStatus.OK,
921 )
922
923 data = await cookidoo.get_active_subscription()
924 assert data is None
925
926 async def test_get_devices(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
927 """Test for get_devices with a single appliance."""
928 mocked.get(
929 "https://cookidoo.ch/customer-devices/api/my-devices/versions",
930 payload=COOKIDOO_TEST_RESPONSE_DEVICES,
931 status=HTTPStatus.OK,
932 )
933
934 devices = await cookidoo.get_devices()
935 assert len(devices) == 1
936 assert devices[0].type == ThermomixMachineType.TM7
937
938 async def test_get_devices_multiple(
939 self, mocked: aioresponses, cookidoo: Cookidoo
940 ) -> None:
941 """Test for get_devices with several appliances."""
942 mocked.get(
943 "https://cookidoo.ch/customer-devices/api/my-devices/versions",
944 payload=COOKIDOO_TEST_RESPONSE_DEVICES_MULTIPLE,
945 status=HTTPStatus.OK,
946 )
947
948 devices = await cookidoo.get_devices()
949 assert [d.type for d in devices] == [
950 ThermomixMachineType.TM7,
951 ThermomixMachineType.TM6,
952 ]
953
954 async def test_get_devices_empty(
955 self, mocked: aioresponses, cookidoo: Cookidoo
956 ) -> None:
957 """Test for get_devices with no paired appliance."""
958 mocked.get(
959 "https://cookidoo.ch/customer-devices/api/my-devices/versions",
960 payload=COOKIDOO_TEST_RESPONSE_DEVICES_EMPTY,
961 status=HTTPStatus.OK,
962 )
963
964 assert await cookidoo.get_devices() == []
965
966 async def test_get_devices_no_content(
967 self, mocked: aioresponses, cookidoo: Cookidoo
968 ) -> None:
969 """An account without a paired appliance gets a 204 with an empty body."""
970 mocked.get(
971 "https://cookidoo.ch/customer-devices/api/my-devices/versions",
972 status=HTTPStatus.NO_CONTENT,
973 )
974
975 assert await cookidoo.get_devices() == []
976
977 async def test_get_devices_unknown_type(
978 self, mocked: aioresponses, cookidoo: Cookidoo
979 ) -> None:
980 """An unrecognized machine type raises a parse exception."""
981 mocked.get(
982 "https://cookidoo.ch/customer-devices/api/my-devices/versions",
983 payload=["TM99"],
984 status=HTTPStatus.OK,
985 )
986
987 with pytest.raises(CookidooParseException):
988 await cookidoo.get_devices()
989
990 async def test_non_sequence_response(
991 self, mocked: aioresponses, cookidoo: Cookidoo
992 ) -> None:
993 """Test response shape validation."""
994 mocked.get(
995 "https://cookidoo.ch/ownership/subscriptions",
996 payload={},
997 status=HTTPStatus.OK,
998 )
999
1000 with pytest.raises(CookidooParseException):
1001 await cookidoo.get_active_subscription()
1002
1003 async def test_subscription_missing_active(
1004 self, mocked: aioresponses, cookidoo: Cookidoo
1005 ) -> None:
1006 """Test malformed subscription items."""
1007 mocked.get(
1008 "https://cookidoo.ch/ownership/subscriptions",
1009 payload=[{"status": "RUNNING"}],
1010 status=HTTPStatus.OK,
1011 )
1012
1013 with pytest.raises(CookidooParseException):
1014 await cookidoo.get_active_subscription()
1015
1016 @pytest.mark.parametrize(
1017 "exception",
1018 [
1019 TimeoutError,
1020 ClientError,
1021 ],
1022 )
1023 async def test_request_exception(
1024 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1025 ) -> None:
1026 """Test request exceptions."""
1027
1028 mocked.get(
1029 "https://cookidoo.ch/ownership/subscriptions",
1030 exception=exception,
1031 )
1032
1033 with pytest.raises(CookidooRequestException):
1034 await cookidoo.get_active_subscription()
1035
1036 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
1037 """Test unauthorized exception."""
1038 mocked.get(
1039 "https://cookidoo.ch/ownership/subscriptions",
1040 status=HTTPStatus.UNAUTHORIZED,
1041 payload={"error_description": ""},
1042 )
1043 with pytest.raises(CookidooAuthException):
1044 await cookidoo.get_active_subscription()
1045
1046 @pytest.mark.parametrize(
1047 ("status", "exception"),
1048 [
1049 (HTTPStatus.OK, CookidooParseException),
1050 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
1051 ],
1052 )
1053 async def test_parse_exception(
1054 self,
1055 mocked: aioresponses,
1056 cookidoo: Cookidoo,
1057 status: HTTPStatus,
1058 exception: type[CookidooException],
1059 ) -> None:
1060 """Test parse exceptions."""
1061 mocked.get(
1062 "https://cookidoo.ch/ownership/subscriptions",
1063 status=status,
1064 body="not json",
1065 content_type="application/json",
1066 )
1067
1068 with pytest.raises(exception):
1069 await cookidoo.get_active_subscription()
1070
1071
1072 class TestGetRecipeDetails:
1073 """Tests for get_recipe_details method."""
1074
1075 async def test_get_recipe_details(
1076 self, mocked: aioresponses, cookidoo: Cookidoo
1077 ) -> None:
1078 """Test for get_recipe_details."""
1079
1080 mocked.get(
1081 "https://cookidoo.ch/recipes/recipe/de-CH/r907015",
1082 payload=COOKIDOO_TEST_RESPONSE_GET_RECIPE_DETAILS,
1083 status=HTTPStatus.OK,
1084 )
1085
1086 data = await cookidoo.get_recipe_details("r907015")
1087 assert data
1088 assert isinstance(data, object)
1089 assert data.id == "r907015"
1090 assert data.name == "Kokos Pralinen"
1091 assert isinstance(data.categories, list)
1092 assert isinstance(data.collections, list)
1093 assert isinstance(data.ingredients, list)
1094 assert isinstance(data.notes, list)
1095 assert isinstance(data.utensils, list)
1096 assert isinstance(data.active_time, int)
1097 assert isinstance(data.total_time, int)
1098 assert isinstance(data.serving_size, int)
1099 assert len(data.step_groups) == 1
1100 assert data.step_groups[0].title == ""
1101 assert len(data.step_groups[0].recipe_steps) == 4
1102 assert data.step_groups[0].recipe_steps[0].title == "1"
1103 assert (
1104 data.step_groups[0]
1105 .recipe_steps[0]
1106 .formatted_text.startswith("<NOBR>200 g Kokosraspeln</NOBR>")
1107 )
1108
1109 @pytest.mark.parametrize(
1110 "exception",
1111 [
1112 TimeoutError,
1113 ClientError,
1114 ],
1115 )
1116 async def test_request_exception(
1117 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1118 ) -> None:
1119 """Test request exceptions."""
1120
1121 mocked.get(
1122 "https://cookidoo.ch/recipes/recipe/de-CH/r907015",
1123 exception=exception,
1124 )
1125
1126 with pytest.raises(CookidooRequestException):
1127 await cookidoo.get_recipe_details("r907015")
1128
1129 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
1130 """Test unauthorized exception."""
1131 mocked.get(
1132 "https://cookidoo.ch/recipes/recipe/de-CH/r907015",
1133 status=HTTPStatus.UNAUTHORIZED,
1134 payload={"error_description": ""},
1135 )
1136 with pytest.raises(CookidooAuthException):
1137 await cookidoo.get_recipe_details("r907015")
1138
1139 @pytest.mark.parametrize(
1140 ("status", "exception"),
1141 [
1142 (HTTPStatus.OK, CookidooParseException),
1143 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
1144 ],
1145 )
1146 async def test_parse_exception(
1147 self,
1148 mocked: aioresponses,
1149 cookidoo: Cookidoo,
1150 status: HTTPStatus,
1151 exception: type[CookidooException],
1152 ) -> None:
1153 """Test parse exceptions."""
1154 mocked.get(
1155 "https://cookidoo.ch/recipes/recipe/de-CH/r907015",
1156 status=status,
1157 body="not json",
1158 content_type="application/json",
1159 )
1160
1161 with pytest.raises(exception):
1162 await cookidoo.get_recipe_details("r907015")
1163
1164 async def test_missing_times_raises_parse_exception(
1165 self, mocked: aioresponses, cookidoo: Cookidoo
1166 ) -> None:
1167 """A recipe missing a non-null activeTime/totalTime raises CookidooParseException.
1168
1169 Previously this raised a bare StopIteration, which is not a documented
1170 exception of this method and is not even guaranteed to propagate as
1171 StopIteration out of an async function (PEP 479).
1172 """
1173 payload = COOKIDOO_TEST_RESPONSE_GET_RECIPE_DETAILS.copy()
1174 payload["times"] = []
1175 mocked.get(
1176 "https://cookidoo.ch/recipes/recipe/de-CH/r907015",
1177 payload=payload,
1178 status=HTTPStatus.OK,
1179 )
1180
1181 with pytest.raises(CookidooParseException):
1182 await cookidoo.get_recipe_details("r907015")
1183
1184
1185 class TestSearchRecipes:
1186 """Tests for search_recipes method."""
1187
1188 async def test_search_recipes(
1189 self, mocked: aioresponses, cookidoo: Cookidoo
1190 ) -> None:
1191 """Test for search_recipes."""
1192 mocked.get(
1193 "https://cookidoo.ch/search/de?query=chicken",
1194 payload=COOKIDOO_TEST_RESPONSE_SEARCH_RECIPES,
1195 status=HTTPStatus.OK,
1196 )
1197
1198 data = await cookidoo.search_recipes("chicken")
1199 assert isinstance(data, CookidooSearchResult)
1200 assert data.total == 2
1201 assert len(data.recipes) == 2
1202 assert data.recipes[0].id == "r123456"
1203 assert data.recipes[0].name == "Chicken Soup"
1204 assert data.recipes[0].thumbnail == (
1205 "https://assets.tmecosys.com/image/upload/"
1206 "t_web_shared_recipe_221x240/img/recipe/ras/Assets/"
1207 "a1b2c3d4-1111-2222-3333-444455556666/Derivates/"
1208 "abcdef01-2345-6789-abcd-ef0123456789.jpg"
1209 )
1210 assert data.recipes[0].image == (
1211 "https://assets.tmecosys.com/image/upload/"
1212 "t_web_rdp_recipe_584x480_1_5x/img/recipe/ras/Assets/"
1213 "a1b2c3d4-1111-2222-3333-444455556666/Derivates/"
1214 "abcdef01-2345-6789-abcd-ef0123456789.jpg"
1215 )
1216 assert data.recipes[0].url == (
1217 "https://cookidoo.ch/recipes/recipe/de-CH/r123456"
1218 )
1219 assert data.recipes[1].id == "r654321"
1220 assert data.recipes[1].name == "Chicken Salad"
1221 assert data.recipes[1].thumbnail == (
1222 "https://assets.tmecosys.com/image/upload/"
1223 "t_web_shared_recipe_221x240/img/recipe/ras/Assets/"
1224 "f1e2d3c4-9999-8888-7777-666655554444/Derivates/"
1225 "98765432-10fe-dcba-9876-543210fedcba.jpg"
1226 )
1227 assert data.recipes[1].image == (
1228 "https://assets.tmecosys.com/image/upload/"
1229 "t_web_rdp_recipe_584x480_1_5x/img/recipe/ras/Assets/"
1230 "f1e2d3c4-9999-8888-7777-666655554444/Derivates/"
1231 "98765432-10fe-dcba-9876-543210fedcba.jpg"
1232 )
1233 assert data.recipes[1].url == (
1234 "https://cookidoo.ch/recipes/recipe/de-CH/r654321"
1235 )
1236
1237 async def test_search_recipes_with_options(
1238 self, mocked: aioresponses, cookidoo: Cookidoo
1239 ) -> None:
1240 """Test search_recipes with filters and list parameters."""
1241 accessories = [
1242 "includingFriend",
1243 "includingBladeCover",
1244 "includingBladeCoverWithPeeler",
1245 "includingCutter",
1246 "includingSensor",
1247 ]
1248 categories = [
1249 "VrkNavCategory-RPF-001",
1250 "VrkNavCategory-RPF-002",
1251 "VrkNavCategory-RPF-003",
1252 ]
1253 url = (
1254 "https://cookidoo.ch/search/es?"
1255 "query=chicken"
1256 "&accessories=includingFriend,includingBladeCover,includingBladeCoverWithPeeler,includingCutter,includingSensor"
1257 "&languages=en,es"
1258 "&categories=VrkNavCategory-RPF-001,VrkNavCategory-RPF-002,VrkNavCategory-RPF-003"
1259 "&countries=ar,es"
1260 "&ingredients=sal,aceite%20de%20oliva"
1261 "&excludeIngredients=polvo%20de%20hornear"
1262 "&tags=De%20diario"
1263 "&ratings=5,4"
1264 "&difficulty=easy"
1265 "&preparationTime=900"
1266 "&totalTime=1200"
1267 "&portions=2"
1268 "&page=1"
1269 "&pageSize=10"
1270 "&tmv=TM7,TM6,TM5,TM31"
1271 )
1272 mocked.get(
1273 url,
1274 payload=COOKIDOO_TEST_RESPONSE_SEARCH_RECIPES,
1275 status=HTTPStatus.OK,
1276 )
1277
1278 data = await cookidoo.search_recipes(
1279 "chicken",
1280 locale="es",
1281 accessories=accessories,
1282 languages=["en", "es"],
1283 categories=categories,
1284 countries=["ar", "es"],
1285 ingredients=["sal", "aceite de oliva"],
1286 exclude_ingredients=["polvo de hornear"],
1287 tags=["De diario"],
1288 ratings=["5", "4"],
1289 difficulty="easy",
1290 preparation_time=900,
1291 total_time=1200,
1292 portions=2,
1293 page=1,
1294 page_size=10,
1295 tmv=["TM7", "TM6", "TM5", "TM31"],
1296 )
1297 assert isinstance(data, CookidooSearchResult)
1298 assert len(data.recipes) == 2
1299 assert data.total == 2
1300
1301 @pytest.mark.parametrize(
1302 "exception",
1303 [
1304 TimeoutError,
1305 ClientError,
1306 ],
1307 )
1308 async def test_search_recipes_request_exception(
1309 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1310 ) -> None:
1311 """Test search_recipes request exceptions."""
1312 mocked.get(
1313 "https://cookidoo.ch/search/de?query=chicken",
1314 exception=exception,
1315 )
1316
1317 with pytest.raises(CookidooRequestException):
1318 await cookidoo.search_recipes("chicken")
1319
1320 async def test_search_recipes_unauthorized(
1321 self, mocked: aioresponses, cookidoo: Cookidoo
1322 ) -> None:
1323 """Test search_recipes unauthorized exception."""
1324 mocked.get(
1325 "https://cookidoo.ch/search/de?query=chicken",
1326 status=HTTPStatus.UNAUTHORIZED,
1327 payload={"error_description": ""},
1328 )
1329 with pytest.raises(CookidooAuthException):
1330 await cookidoo.search_recipes("chicken")
1331
1332 async def test_search_recipes_unauthorized_non_json_body(
1333 self, mocked: aioresponses, cookidoo: Cookidoo
1334 ) -> None:
1335 """Test search_recipes 401 with non-JSON body still raises CookidooAuthException."""
1336 mocked.get(
1337 "https://cookidoo.ch/search/de?query=chicken",
1338 status=HTTPStatus.UNAUTHORIZED,
1339 body="not json",
1340 content_type="text/plain",
1341 )
1342 with pytest.raises(CookidooAuthException):
1343 await cookidoo.search_recipes("chicken")
1344
1345 async def test_search_recipes_parse_exception(
1346 self, mocked: aioresponses, cookidoo: Cookidoo
1347 ) -> None:
1348 """Test search_recipes raises CookidooParseException when response is not valid JSON."""
1349 mocked.get(
1350 "https://cookidoo.ch/search/de?query=chicken",
1351 status=HTTPStatus.OK,
1352 body="not valid json",
1353 content_type="application/json",
1354 )
1355 with pytest.raises(CookidooParseException):
1356 await cookidoo.search_recipes("chicken")
1357
1358 async def test_search_recipes_no_content(
1359 self, mocked: aioresponses, cookidoo: Cookidoo
1360 ) -> None:
1361 """Test search_recipes when API returns 204 No Content."""
1362 mocked.get(
1363 "https://cookidoo.ch/search/de?query=chicken",
1364 status=HTTPStatus.NO_CONTENT,
1365 )
1366
1367 data = await cookidoo.search_recipes("chicken")
1368 assert isinstance(data, CookidooSearchResult)
1369 assert data.recipes == []
1370 assert data.total == 0
1371
1372 async def test_search_recipes_with_string_params(
1373 self, mocked: aioresponses, cookidoo: Cookidoo
1374 ) -> None:
1375 """Test search_recipes with string (non-list) filter params."""
1376 url = (
1377 "https://cookidoo.ch/search/de?"
1378 "query=pasta&accessories=includingFriend&difficulty=easy"
1379 )
1380 mocked.get(
1381 url,
1382 payload=COOKIDOO_TEST_RESPONSE_SEARCH_RECIPES,
1383 status=HTTPStatus.OK,
1384 )
1385
1386 data = await cookidoo.search_recipes(
1387 "pasta",
1388 accessories="includingFriend",
1389 difficulty="easy",
1390 )
1391 assert isinstance(data, CookidooSearchResult)
1392 assert data.total == 2
1393
1394 async def test_search_recipes_with_tmv_single_enum(
1395 self, mocked: aioresponses, cookidoo: Cookidoo
1396 ) -> None:
1397 """Test search_recipes with single ThermomixMachineType (not list)."""
1398 url = "https://cookidoo.ch/search/de?query=soup&tmv=TM7"
1399 mocked.get(
1400 url,
1401 payload=COOKIDOO_TEST_RESPONSE_SEARCH_RECIPES,
1402 status=HTTPStatus.OK,
1403 )
1404
1405 data = await cookidoo.search_recipes("soup", tmv=ThermomixMachineType.TM7)
1406 assert isinstance(data, CookidooSearchResult)
1407 assert data.total == 2
1408
1409 async def test_search_recipes_without_query(
1410 self, mocked: aioresponses, cookidoo: Cookidoo
1411 ) -> None:
1412 """Test search_recipes with optional query omitted (params without query)."""
1413 mocked.get(
1414 "https://cookidoo.ch/search/de",
1415 payload=COOKIDOO_TEST_RESPONSE_SEARCH_RECIPES,
1416 status=HTTPStatus.OK,
1417 )
1418
1419 data = await cookidoo.search_recipes()
1420 assert isinstance(data, CookidooSearchResult)
1421 assert len(data.recipes) == 2
1422 assert data.total == 2
1423
1424 async def test_search_recipes_unexpected_status(
1425 self, mocked: aioresponses, cookidoo: Cookidoo
1426 ) -> None:
1427 """Test search_recipes raises CookidooRequestException on unexpected status."""
1428 mocked.get(
1429 "https://cookidoo.ch/search/de?query=chicken",
1430 status=HTTPStatus.INTERNAL_SERVER_ERROR,
1431 )
1432 with pytest.raises(CookidooRequestException):
1433 await cookidoo.search_recipes("chicken")
1434
1435 async def test_search_recipes_non_dict_response(
1436 self, mocked: aioresponses, cookidoo: Cookidoo
1437 ) -> None:
1438 """Test search_recipes raises CookidooParseException when response is not a dict."""
1439 mocked.get(
1440 "https://cookidoo.ch/search/de?query=chicken",
1441 payload=["not", "a", "dict"],
1442 status=HTTPStatus.OK,
1443 )
1444 with pytest.raises(CookidooParseException):
1445 await cookidoo.search_recipes("chicken")
1446
1447
1448 class TestGetCustomRecipe:
1449 """Tests for get_custom_recipe method."""
1450
1451 async def test_get_custom_recipe(
1452 self, mocked: aioresponses, cookidoo: Cookidoo
1453 ) -> None:
1454 """Test for get_custom_recipe."""
1455
1456 mocked.get(
1457 "https://cookidoo.ch/created-recipes/de-CH/01K2CVHD1DXG1PVETNVV3JPKWW",
1458 payload=COOKIDOO_TEST_RESPONSE_GET_CUSTOM_RECIPE,
1459 status=HTTPStatus.OK,
1460 )
1461
1462 data = await cookidoo.get_custom_recipe("01K2CVHD1DXG1PVETNVV3JPKWW")
1463 assert data
1464 assert isinstance(data, object)
1465 assert data.id == "01K2CVHD1DXG1PVETNVV3JPKWW"
1466 assert data.name == "Vongole alla marinara"
1467 assert isinstance(data.instructions, list)
1468 assert isinstance(data.ingredients, list)
1469 assert isinstance(data.tools, list)
1470 assert isinstance(data.active_time, int)
1471 assert isinstance(data.total_time, int)
1472 assert isinstance(data.serving_size, int)
1473
1474 @pytest.mark.parametrize(
1475 "exception",
1476 [
1477 TimeoutError,
1478 ClientError,
1479 ],
1480 )
1481 async def test_request_exception(
1482 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1483 ) -> None:
1484 """Test request exceptions."""
1485
1486 mocked.get(
1487 "https://cookidoo.ch/created-recipes/de-CH/01K2CVHD1DXG1PVETNVV3JPKWW",
1488 exception=exception,
1489 )
1490
1491 with pytest.raises(CookidooRequestException):
1492 await cookidoo.get_custom_recipe("01K2CVHD1DXG1PVETNVV3JPKWW")
1493
1494 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
1495 """Test unauthorized exception."""
1496 mocked.get(
1497 "https://cookidoo.ch/created-recipes/de-CH/01K2CVHD1DXG1PVETNVV3JPKWW",
1498 status=HTTPStatus.UNAUTHORIZED,
1499 payload={"error_description": ""},
1500 )
1501 with pytest.raises(CookidooAuthException):
1502 await cookidoo.get_custom_recipe("01K2CVHD1DXG1PVETNVV3JPKWW")
1503
1504 @pytest.mark.parametrize(
1505 ("status", "exception"),
1506 [
1507 (HTTPStatus.OK, CookidooParseException),
1508 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
1509 ],
1510 )
1511 async def test_parse_exception(
1512 self,
1513 mocked: aioresponses,
1514 cookidoo: Cookidoo,
1515 status: HTTPStatus,
1516 exception: type[CookidooException],
1517 ) -> None:
1518 """Test parse exceptions."""
1519 mocked.get(
1520 "https://cookidoo.ch/created-recipes/de-CH/01K2CVHD1DXG1PVETNVV3JPKWW",
1521 status=status,
1522 body="not json",
1523 content_type="application/json",
1524 )
1525
1526 with pytest.raises(exception):
1527 await cookidoo.get_custom_recipe("01K2CVHD1DXG1PVETNVV3JPKWW")
1528
1529
1530 class TestListCustomRecipes:
1531 """Tests for list_custom_recipes method."""
1532
1533 async def test_list_custom_recipes(
1534 self, mocked: aioresponses, cookidoo: Cookidoo
1535 ) -> None:
1536 """Test for list_custom_recipes."""
1537 mocked.get(
1538 "https://cookidoo.ch/created-recipes/de-CH",
1539 payload=COOKIDOO_TEST_RESPONSE_LIST_CUSTOM_RECIPES,
1540 status=HTTPStatus.OK,
1541 )
1542
1543 data = await cookidoo.list_custom_recipes()
1544
1545 assert len(data) == 1
1546 assert data[0].id == "01K2CTJ9Y1BABRG5MXK44CFZS4"
1547 assert data[0].name == "Vongole alla marinara"
1548 assert data[0].active_time == 600
1549 assert data[0].total_time == 1800
1550 assert data[0].ingredients == [
1551 "130 g di cipolla",
1552 "65 g di olio extravergine di oliva",
1553 ]
1554
1555 async def test_list_custom_recipes_empty(
1556 self, mocked: aioresponses, cookidoo: Cookidoo
1557 ) -> None:
1558 """Test for list_custom_recipes with no recipes."""
1559 mocked.get(
1560 "https://cookidoo.ch/created-recipes/de-CH",
1561 payload={"items": []},
1562 status=HTTPStatus.OK,
1563 )
1564
1565 data = await cookidoo.list_custom_recipes()
1566
1567 assert data == []
1568
1569 @pytest.mark.parametrize(
1570 "exception",
1571 [
1572 TimeoutError,
1573 ClientError,
1574 ],
1575 )
1576 async def test_request_exception(
1577 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1578 ) -> None:
1579 """Test request exceptions."""
1580 mocked.get(
1581 "https://cookidoo.ch/created-recipes/de-CH",
1582 exception=exception,
1583 )
1584
1585 with pytest.raises(CookidooRequestException):
1586 await cookidoo.list_custom_recipes()
1587
1588 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
1589 """Test unauthorized exception."""
1590 mocked.get(
1591 "https://cookidoo.ch/created-recipes/de-CH",
1592 status=HTTPStatus.UNAUTHORIZED,
1593 payload={"error_description": ""},
1594 )
1595
1596 with pytest.raises(CookidooAuthException):
1597 await cookidoo.list_custom_recipes()
1598
1599 @pytest.mark.parametrize(
1600 ("payload", "exception"),
1601 [
1602 ({}, CookidooParseException),
1603 ({"items": None}, CookidooParseException),
1604 ],
1605 )
1606 async def test_parse_exception(
1607 self,
1608 mocked: aioresponses,
1609 cookidoo: Cookidoo,
1610 payload: dict[str, object],
1611 exception: type[CookidooException],
1612 ) -> None:
1613 """Test parse exceptions."""
1614 mocked.get(
1615 "https://cookidoo.ch/created-recipes/de-CH",
1616 status=HTTPStatus.OK,
1617 payload=payload,
1618 )
1619
1620 with pytest.raises(exception):
1621 await cookidoo.list_custom_recipes()
1622
1623
1624 class TestAddCustomRecipe:
1625 """Tests for add_custom_recipe method."""
1626
1627 async def test_add_custom_recipe(
1628 self, mocked: aioresponses, cookidoo: Cookidoo
1629 ) -> None:
1630 """Test for add_custom_recipe."""
1631
1632 mocked.post(
1633 "https://cookidoo.ch/created-recipes/de-CH",
1634 payload=COOKIDOO_TEST_RESPONSE_ADD_CUSTOM_RECIPE,
1635 status=HTTPStatus.OK,
1636 )
1637
1638 data = await cookidoo.add_custom_recipe_from("r907015", 4)
1639 assert data
1640 assert data.id == "01K2CTJ9Y1BABRG5MXK44CFZS4"
1641 assert data.name == "Vongole alla marinara"
1642
1643 @pytest.mark.parametrize(
1644 "exception",
1645 [
1646 TimeoutError,
1647 ClientError,
1648 ],
1649 )
1650 async def test_request_exception(
1651 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1652 ) -> None:
1653 """Test request exceptions."""
1654
1655 mocked.post(
1656 "https://cookidoo.ch/created-recipes/de-CH",
1657 exception=exception,
1658 )
1659
1660 with pytest.raises(CookidooRequestException):
1661 await cookidoo.add_custom_recipe_from("r907015", 4)
1662
1663 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
1664 """Test unauthorized exception."""
1665 mocked.post(
1666 "https://cookidoo.ch/created-recipes/de-CH",
1667 status=HTTPStatus.UNAUTHORIZED,
1668 payload={"error_description": ""},
1669 )
1670 with pytest.raises(CookidooAuthException):
1671 await cookidoo.add_custom_recipe_from("r907015", 4)
1672
1673 @pytest.mark.parametrize(
1674 ("status", "exception"),
1675 [
1676 (HTTPStatus.OK, CookidooParseException),
1677 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
1678 ],
1679 )
1680 async def test_parse_exception(
1681 self,
1682 mocked: aioresponses,
1683 cookidoo: Cookidoo,
1684 status: HTTPStatus,
1685 exception: type[CookidooException],
1686 ) -> None:
1687 """Test parse exceptions."""
1688 mocked.post(
1689 "https://cookidoo.ch/created-recipes/de-CH",
1690 status=status,
1691 body="not json",
1692 content_type="application/json",
1693 )
1694
1695 with pytest.raises(exception):
1696 await cookidoo.add_custom_recipe_from("r907015", 4)
1697
1698
1699 class TestRemoveCustomRecipe:
1700 """Tests for remove_custom_recipe method."""
1701
1702 async def test_remove_custom_recipe(
1703 self, mocked: aioresponses, cookidoo: Cookidoo
1704 ) -> None:
1705 """Test for remove_custom_recipe."""
1706
1707 mocked.delete(
1708 "https://cookidoo.ch/created-recipes/de-CH/01K2CTJ9Y1BABRG5MXK44CFZS4",
1709 payload=None,
1710 status=HTTPStatus.OK,
1711 )
1712
1713 await cookidoo.remove_custom_recipe("01K2CTJ9Y1BABRG5MXK44CFZS4")
1714
1715 @pytest.mark.parametrize(
1716 "exception",
1717 [
1718 TimeoutError,
1719 ClientError,
1720 ],
1721 )
1722 async def test_request_exception(
1723 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1724 ) -> None:
1725 """Test request exceptions."""
1726
1727 mocked.delete(
1728 "https://cookidoo.ch/created-recipes/de-CH/01K2CTJ9Y1BABRG5MXK44CFZS4",
1729 exception=exception,
1730 )
1731
1732 with pytest.raises(CookidooRequestException):
1733 await cookidoo.remove_custom_recipe("01K2CTJ9Y1BABRG5MXK44CFZS4")
1734
1735 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
1736 """Test unauthorized exception."""
1737 mocked.delete(
1738 "https://cookidoo.ch/created-recipes/de-CH/01K2CTJ9Y1BABRG5MXK44CFZS4",
1739 status=HTTPStatus.UNAUTHORIZED,
1740 payload={"error_description": ""},
1741 )
1742 with pytest.raises(CookidooAuthException):
1743 await cookidoo.remove_custom_recipe("01K2CTJ9Y1BABRG5MXK44CFZS4")
1744
1745 @pytest.mark.parametrize(
1746 ("status", "exception"),
1747 [
1748 # (HTTPStatus.OK, CookidooParseException), # There is nothing to parse
1749 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
1750 ],
1751 )
1752 async def test_parse_exception(
1753 self,
1754 mocked: aioresponses,
1755 cookidoo: Cookidoo,
1756 status: HTTPStatus,
1757 exception: type[CookidooException],
1758 ) -> None:
1759 """Test parse exceptions."""
1760 mocked.delete(
1761 "https://cookidoo.ch/created-recipes/de-CH/01K2CTJ9Y1BABRG5MXK44CFZS4",
1762 status=status,
1763 body="not json",
1764 content_type="application/json",
1765 )
1766
1767 with pytest.raises(exception):
1768 await cookidoo.remove_custom_recipe("01K2CTJ9Y1BABRG5MXK44CFZS4")
1769
1770
1771 class TestGetShoppingListRecipes:
1772 """Tests for get_shopping_list_recipes method."""
1773
1774 async def test_get_shopping_list_recipes(
1775 self, mocked: aioresponses, cookidoo: Cookidoo
1776 ) -> None:
1777 """Test for get_shopping_list_recipes."""
1778
1779 mocked.get(
1780 "https://cookidoo.ch/shopping/de-CH",
1781 payload=COOKIDOO_TEST_RESPONSE_GET_SHOPPING_LIST_RECIPES,
1782 status=HTTPStatus.OK,
1783 )
1784
1785 data = await cookidoo.get_shopping_list_recipes()
1786 assert data
1787 assert isinstance(data, list)
1788 assert len(data) == 2
1789
1790 @pytest.mark.parametrize(
1791 "exception",
1792 [
1793 TimeoutError,
1794 ClientError,
1795 ],
1796 )
1797 async def test_request_exception(
1798 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1799 ) -> None:
1800 """Test request exceptions."""
1801
1802 mocked.get(
1803 "https://cookidoo.ch/shopping/de-CH",
1804 exception=exception,
1805 )
1806
1807 with pytest.raises(CookidooRequestException):
1808 await cookidoo.get_shopping_list_recipes()
1809
1810 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
1811 """Test unauthorized exception."""
1812 mocked.get(
1813 "https://cookidoo.ch/shopping/de-CH",
1814 status=HTTPStatus.UNAUTHORIZED,
1815 payload={"error_description": ""},
1816 )
1817 with pytest.raises(CookidooAuthException):
1818 await cookidoo.get_shopping_list_recipes()
1819
1820 @pytest.mark.parametrize(
1821 ("status", "exception"),
1822 [
1823 (HTTPStatus.OK, CookidooParseException),
1824 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
1825 ],
1826 )
1827 async def test_parse_exception(
1828 self,
1829 mocked: aioresponses,
1830 cookidoo: Cookidoo,
1831 status: HTTPStatus,
1832 exception: type[CookidooException],
1833 ) -> None:
1834 """Test parse exceptions."""
1835 mocked.get(
1836 "https://cookidoo.ch/shopping/de-CH",
1837 status=status,
1838 body="not json",
1839 content_type="application/json",
1840 )
1841
1842 with pytest.raises(exception):
1843 await cookidoo.get_shopping_list_recipes()
1844
1845
1846 class TestGetIngredients:
1847 """Tests for get_ingredient_items method."""
1848
1849 async def test_get_ingredient_items_for_recipes(
1850 self, mocked: aioresponses, cookidoo: Cookidoo
1851 ) -> None:
1852 """Test for get_ingredient_items."""
1853
1854 mocked.get(
1855 "https://cookidoo.ch/shopping/de-CH",
1856 payload=COOKIDOO_TEST_RESPONSE_GET_INGREDIENTS_FOR_RECIPES,
1857 status=HTTPStatus.OK,
1858 )
1859
1860 data = await cookidoo.get_ingredient_items()
1861 assert data
1862 assert isinstance(data, list)
1863 assert len(data) == 14
1864
1865 async def test_get_ingredient_items_for_custom_recipes(
1866 self, mocked: aioresponses, cookidoo: Cookidoo
1867 ) -> None:
1868 """Test for get_ingredient_items."""
1869
1870 mocked.get(
1871 "https://cookidoo.ch/shopping/de-CH",
1872 payload=COOKIDOO_TEST_RESPONSE_GET_INGREDIENTS_FOR_CUSTOM_RECIPES,
1873 status=HTTPStatus.OK,
1874 )
1875
1876 data = await cookidoo.get_ingredient_items()
1877 assert data
1878 assert isinstance(data, list)
1879 assert len(data) == 10
1880
1881 @pytest.mark.parametrize(
1882 "exception",
1883 [
1884 TimeoutError,
1885 ClientError,
1886 ],
1887 )
1888 async def test_request_exception(
1889 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1890 ) -> None:
1891 """Test request exceptions."""
1892
1893 mocked.get(
1894 "https://cookidoo.ch/shopping/de-CH",
1895 exception=exception,
1896 )
1897
1898 with pytest.raises(CookidooRequestException):
1899 await cookidoo.get_ingredient_items()
1900
1901 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
1902 """Test unauthorized exception."""
1903 mocked.get(
1904 "https://cookidoo.ch/shopping/de-CH",
1905 status=HTTPStatus.UNAUTHORIZED,
1906 payload={"error_description": ""},
1907 )
1908 with pytest.raises(CookidooAuthException):
1909 await cookidoo.get_ingredient_items()
1910
1911 @pytest.mark.parametrize(
1912 ("status", "exception"),
1913 [
1914 (HTTPStatus.OK, CookidooParseException),
1915 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
1916 ],
1917 )
1918 async def test_parse_exception(
1919 self,
1920 mocked: aioresponses,
1921 cookidoo: Cookidoo,
1922 status: HTTPStatus,
1923 exception: type[CookidooException],
1924 ) -> None:
1925 """Test parse exceptions."""
1926 mocked.get(
1927 "https://cookidoo.ch/shopping/de-CH",
1928 status=status,
1929 body="not json",
1930 content_type="application/json",
1931 )
1932
1933 with pytest.raises(exception):
1934 await cookidoo.get_ingredient_items()
1935
1936
1937 class TestAddIngredientsForRecipes:
1938 """Tests for add_ingredient_items_for_recipes method."""
1939
1940 async def test_add_ingredient_items_for_recipes(
1941 self, mocked: aioresponses, cookidoo: Cookidoo
1942 ) -> None:
1943 """Test for add_ingredient_items_for_recipes."""
1944
1945 mocked.post(
1946 "https://cookidoo.ch/shopping/de-CH/recipes/add",
1947 payload=COOKIDOO_TEST_RESPONSE_ADD_INGREDIENTS_FOR_RECIPES,
1948 status=HTTPStatus.OK,
1949 )
1950
1951 data = await cookidoo.add_ingredient_items_for_recipes(["r59322", "r907016"])
1952 assert data
1953 assert isinstance(data, list)
1954 assert len(data) == 14
1955
1956 @pytest.mark.parametrize(
1957 "exception",
1958 [
1959 TimeoutError,
1960 ClientError,
1961 ],
1962 )
1963 async def test_request_exception(
1964 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
1965 ) -> None:
1966 """Test request exceptions."""
1967
1968 mocked.post(
1969 "https://cookidoo.ch/shopping/de-CH/recipes/add",
1970 exception=exception,
1971 )
1972
1973 with pytest.raises(CookidooRequestException):
1974 await cookidoo.add_ingredient_items_for_recipes(["r59322", "r907016"])
1975
1976 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
1977 """Test unauthorized exception."""
1978 mocked.post(
1979 "https://cookidoo.ch/shopping/de-CH/recipes/add",
1980 status=HTTPStatus.UNAUTHORIZED,
1981 payload={"error_description": ""},
1982 )
1983 with pytest.raises(CookidooAuthException):
1984 await cookidoo.add_ingredient_items_for_recipes(["r59322", "r907016"])
1985
1986 @pytest.mark.parametrize(
1987 ("status", "exception"),
1988 [
1989 (HTTPStatus.OK, CookidooParseException),
1990 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
1991 ],
1992 )
1993 async def test_parse_exception(
1994 self,
1995 mocked: aioresponses,
1996 cookidoo: Cookidoo,
1997 status: HTTPStatus,
1998 exception: type[CookidooException],
1999 ) -> None:
2000 """Test parse exceptions."""
2001 mocked.post(
2002 "https://cookidoo.ch/shopping/de-CH/recipes/add",
2003 status=status,
2004 body="not json",
2005 content_type="application/json",
2006 )
2007
2008 with pytest.raises(exception):
2009 await cookidoo.add_ingredient_items_for_recipes(["r59322", "r907016"])
2010
2011
2012 class TestRemoveIngredientsForRecipes:
2013 """Tests for remove_ingredient_items_for_recipes method."""
2014
2015 async def test_remove_ingredient_items_for_recipes(
2016 self, mocked: aioresponses, cookidoo: Cookidoo
2017 ) -> None:
2018 """Test for remove_ingredient_items_for_recipes."""
2019
2020 mocked.post(
2021 "https://cookidoo.ch/shopping/de-CH/recipes/remove",
2022 payload=None,
2023 status=HTTPStatus.OK,
2024 )
2025
2026 await cookidoo.remove_ingredient_items_for_recipes(["r59322", "r907016"])
2027
2028 @pytest.mark.parametrize(
2029 "exception",
2030 [
2031 TimeoutError,
2032 ClientError,
2033 ],
2034 )
2035 async def test_request_exception(
2036 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2037 ) -> None:
2038 """Test request exceptions."""
2039
2040 mocked.post(
2041 "https://cookidoo.ch/shopping/de-CH/recipes/remove",
2042 exception=exception,
2043 )
2044
2045 with pytest.raises(CookidooRequestException):
2046 await cookidoo.remove_ingredient_items_for_recipes(["r59322", "r907016"])
2047
2048 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2049 """Test unauthorized exception."""
2050 mocked.post(
2051 "https://cookidoo.ch/shopping/de-CH/recipes/remove",
2052 status=HTTPStatus.UNAUTHORIZED,
2053 payload={"error_description": ""},
2054 )
2055 with pytest.raises(CookidooAuthException):
2056 await cookidoo.remove_ingredient_items_for_recipes(["r59322", "r907016"])
2057
2058 @pytest.mark.parametrize(
2059 ("status", "exception"),
2060 [
2061 # (HTTPStatus.OK, CookidooParseException), # There is nothing to parse
2062 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2063 ],
2064 )
2065 async def test_parse_exception(
2066 self,
2067 mocked: aioresponses,
2068 cookidoo: Cookidoo,
2069 status: HTTPStatus,
2070 exception: type[CookidooException],
2071 ) -> None:
2072 """Test parse exceptions."""
2073 mocked.post(
2074 "https://cookidoo.ch/shopping/de-CH/recipes/remove",
2075 status=status,
2076 body="not json",
2077 content_type="application/json",
2078 )
2079
2080 with pytest.raises(exception):
2081 await cookidoo.remove_ingredient_items_for_recipes(["r59322", "r907016"])
2082
2083
2084 class TestEditIngredientsOwnership:
2085 """Tests for edit_ingredient_items_ownership method."""
2086
2087 async def test_edit_ingredient_items_ownership(
2088 self, mocked: aioresponses, cookidoo: Cookidoo
2089 ) -> None:
2090 """Test for edit_ingredient_items_ownership."""
2091
2092 mocked.post(
2093 "https://cookidoo.ch/shopping/de-CH/owned-ingredients/ownership/edit",
2094 payload=COOKIDOO_TEST_RESPONSE_EDIT_INGREDIENTS_OWNERSHIP,
2095 status=HTTPStatus.OK,
2096 )
2097
2098 data = await cookidoo.edit_ingredient_items_ownership(
2099 [
2100 CookidooIngredientItem(
2101 id="01JBQG02JQD3XPFMM5CXE51K25",
2102 name="Hefe",
2103 is_owned=True,
2104 description="1 Würfel",
2105 )
2106 ]
2107 )
2108 assert data
2109 assert isinstance(data, list)
2110 assert len(data) == 1
2111 assert data[0].is_owned
2112
2113 @pytest.mark.parametrize(
2114 "exception",
2115 [
2116 TimeoutError,
2117 ClientError,
2118 ],
2119 )
2120 async def test_request_exception(
2121 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2122 ) -> None:
2123 """Test request exceptions."""
2124
2125 mocked.post(
2126 "https://cookidoo.ch/shopping/de-CH/owned-ingredients/ownership/edit",
2127 exception=exception,
2128 )
2129
2130 with pytest.raises(CookidooRequestException):
2131 await cookidoo.edit_ingredient_items_ownership(
2132 [
2133 CookidooIngredientItem(
2134 id="01JBQG02JQD3XPFMM5CXE51K25",
2135 name="Hefe",
2136 is_owned=True,
2137 description="1 Würfel",
2138 )
2139 ]
2140 )
2141
2142 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2143 """Test unauthorized exception."""
2144 mocked.post(
2145 "https://cookidoo.ch/shopping/de-CH/owned-ingredients/ownership/edit",
2146 status=HTTPStatus.UNAUTHORIZED,
2147 payload={"error_description": ""},
2148 )
2149 with pytest.raises(CookidooAuthException):
2150 await cookidoo.edit_ingredient_items_ownership(
2151 [
2152 CookidooIngredientItem(
2153 id="01JBQG02JQD3XPFMM5CXE51K25",
2154 name="Hefe",
2155 is_owned=True,
2156 description="1 Würfel",
2157 )
2158 ]
2159 )
2160
2161 @pytest.mark.parametrize(
2162 ("status", "exception"),
2163 [
2164 (HTTPStatus.OK, CookidooParseException),
2165 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2166 ],
2167 )
2168 async def test_parse_exception(
2169 self,
2170 mocked: aioresponses,
2171 cookidoo: Cookidoo,
2172 status: HTTPStatus,
2173 exception: type[CookidooException],
2174 ) -> None:
2175 """Test parse exceptions."""
2176 mocked.post(
2177 "https://cookidoo.ch/shopping/de-CH/owned-ingredients/ownership/edit",
2178 status=status,
2179 body="not json",
2180 content_type="application/json",
2181 )
2182
2183 with pytest.raises(exception):
2184 await cookidoo.edit_ingredient_items_ownership(
2185 [
2186 CookidooIngredientItem(
2187 id="01JBQG02JQD3XPFMM5CXE51K25",
2188 name="Hefe",
2189 is_owned=True,
2190 description="1 Würfel",
2191 )
2192 ]
2193 )
2194
2195
2196 class TestAddIngredientsForCustomRecipes:
2197 """Tests for add_ingredient_items_for_custom_recipes method."""
2198
2199 async def test_add_ingredient_items_for_custom_recipes(
2200 self, mocked: aioresponses, cookidoo: Cookidoo
2201 ) -> None:
2202 """Test for add_ingredient_items_for_custom_recipes."""
2203
2204 mocked.post(
2205 "https://cookidoo.ch/shopping/de-CH/recipes/add",
2206 payload=COOKIDOO_TEST_RESPONSE_ADD_INGREDIENTS_FOR_CUSTOM_RECIPES,
2207 status=HTTPStatus.OK,
2208 )
2209
2210 data = await cookidoo.add_ingredient_items_for_custom_recipes(
2211 ["01K2CTZSSKFKJWPM71017SJYMC"]
2212 )
2213 assert data
2214 assert isinstance(data, list)
2215 assert len(data) == 10
2216
2217 @pytest.mark.parametrize(
2218 "exception",
2219 [
2220 TimeoutError,
2221 ClientError,
2222 ],
2223 )
2224 async def test_request_exception(
2225 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2226 ) -> None:
2227 """Test request exceptions."""
2228
2229 mocked.post(
2230 "https://cookidoo.ch/shopping/de-CH/recipes/add",
2231 exception=exception,
2232 )
2233
2234 with pytest.raises(CookidooRequestException):
2235 await cookidoo.add_ingredient_items_for_custom_recipes(
2236 ["01K2CTZSSKFKJWPM71017SJYMC"]
2237 )
2238
2239 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2240 """Test unauthorized exception."""
2241 mocked.post(
2242 "https://cookidoo.ch/shopping/de-CH/recipes/add",
2243 status=HTTPStatus.UNAUTHORIZED,
2244 payload={"error_description": ""},
2245 )
2246 with pytest.raises(CookidooAuthException):
2247 await cookidoo.add_ingredient_items_for_custom_recipes(
2248 ["01K2CTZSSKFKJWPM71017SJYMC"]
2249 )
2250
2251 @pytest.mark.parametrize(
2252 ("status", "exception"),
2253 [
2254 (HTTPStatus.OK, CookidooParseException),
2255 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2256 ],
2257 )
2258 async def test_parse_exception(
2259 self,
2260 mocked: aioresponses,
2261 cookidoo: Cookidoo,
2262 status: HTTPStatus,
2263 exception: type[CookidooException],
2264 ) -> None:
2265 """Test parse exceptions."""
2266 mocked.post(
2267 "https://cookidoo.ch/shopping/de-CH/recipes/add",
2268 status=status,
2269 body="not json",
2270 content_type="application/json",
2271 )
2272
2273 with pytest.raises(exception):
2274 await cookidoo.add_ingredient_items_for_custom_recipes(
2275 ["01K2CTZSSKFKJWPM71017SJYMC"]
2276 )
2277
2278
2279 class TestRemoveIngredientsForCustomRecipes:
2280 """Tests for remove_ingredient_items_for_custom_recipes method."""
2281
2282 async def test_remove_ingredient_items_for_custom_recipes(
2283 self, mocked: aioresponses, cookidoo: Cookidoo
2284 ) -> None:
2285 """Test for remove_ingredient_items_for_custom_recipes."""
2286
2287 mocked.post(
2288 "https://cookidoo.ch/shopping/de-CH/recipes/remove",
2289 payload=None,
2290 status=HTTPStatus.OK,
2291 )
2292
2293 await cookidoo.remove_ingredient_items_for_custom_recipes(
2294 ["01K2CTZSSKFKJWPM71017SJYMC"]
2295 )
2296
2297 @pytest.mark.parametrize(
2298 "exception",
2299 [
2300 TimeoutError,
2301 ClientError,
2302 ],
2303 )
2304 async def test_request_exception(
2305 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2306 ) -> None:
2307 """Test request exceptions."""
2308
2309 mocked.post(
2310 "https://cookidoo.ch/shopping/de-CH/recipes/remove",
2311 exception=exception,
2312 )
2313
2314 with pytest.raises(CookidooRequestException):
2315 await cookidoo.remove_ingredient_items_for_custom_recipes(
2316 ["01K2CTZSSKFKJWPM71017SJYMC"]
2317 )
2318
2319 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2320 """Test unauthorized exception."""
2321 mocked.post(
2322 "https://cookidoo.ch/shopping/de-CH/recipes/remove",
2323 status=HTTPStatus.UNAUTHORIZED,
2324 payload={"error_description": ""},
2325 )
2326 with pytest.raises(CookidooAuthException):
2327 await cookidoo.remove_ingredient_items_for_custom_recipes(
2328 ["01K2CTZSSKFKJWPM71017SJYMC"]
2329 )
2330
2331 @pytest.mark.parametrize(
2332 ("status", "exception"),
2333 [
2334 # (HTTPStatus.OK, CookidooParseException), # There is nothing to parse
2335 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2336 ],
2337 )
2338 async def test_parse_exception(
2339 self,
2340 mocked: aioresponses,
2341 cookidoo: Cookidoo,
2342 status: HTTPStatus,
2343 exception: type[CookidooException],
2344 ) -> None:
2345 """Test parse exceptions."""
2346 mocked.post(
2347 "https://cookidoo.ch/shopping/de-CH/recipes/remove",
2348 status=status,
2349 body="not json",
2350 content_type="application/json",
2351 )
2352
2353 with pytest.raises(exception):
2354 await cookidoo.remove_ingredient_items_for_custom_recipes(
2355 ["01K2CTZSSKFKJWPM71017SJYMC"]
2356 )
2357
2358
2359 class TestGetAdditionalItems:
2360 """Tests for get_additional_items method."""
2361
2362 async def test_get_additional_items(
2363 self, mocked: aioresponses, cookidoo: Cookidoo
2364 ) -> None:
2365 """Test for get_additional_items."""
2366
2367 mocked.get(
2368 "https://cookidoo.ch/shopping/de-CH",
2369 payload=COOKIDOO_TEST_RESPONSE_GET_ADDITIONAL_ITEMS,
2370 status=HTTPStatus.OK,
2371 )
2372
2373 data = await cookidoo.get_additional_items()
2374 assert data
2375 assert isinstance(data, list)
2376 assert len(data) == 2
2377
2378 @pytest.mark.parametrize(
2379 "exception",
2380 [
2381 TimeoutError,
2382 ClientError,
2383 ],
2384 )
2385 async def test_request_exception(
2386 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2387 ) -> None:
2388 """Test request exceptions."""
2389
2390 mocked.get(
2391 "https://cookidoo.ch/shopping/de-CH",
2392 exception=exception,
2393 )
2394
2395 with pytest.raises(CookidooRequestException):
2396 await cookidoo.get_additional_items()
2397
2398 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2399 """Test unauthorized exception."""
2400 mocked.get(
2401 "https://cookidoo.ch/shopping/de-CH",
2402 status=HTTPStatus.UNAUTHORIZED,
2403 payload={"error_description": ""},
2404 )
2405 with pytest.raises(CookidooAuthException):
2406 await cookidoo.get_additional_items()
2407
2408 @pytest.mark.parametrize(
2409 ("status", "exception"),
2410 [
2411 (HTTPStatus.OK, CookidooParseException),
2412 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2413 ],
2414 )
2415 async def test_parse_exception(
2416 self,
2417 mocked: aioresponses,
2418 cookidoo: Cookidoo,
2419 status: HTTPStatus,
2420 exception: type[CookidooException],
2421 ) -> None:
2422 """Test parse exceptions."""
2423 mocked.get(
2424 "https://cookidoo.ch/shopping/de-CH",
2425 status=status,
2426 body="not json",
2427 content_type="application/json",
2428 )
2429
2430 with pytest.raises(exception):
2431 await cookidoo.get_additional_items()
2432
2433
2434 class TestAddAdditionalItems:
2435 """Tests for add_additional_items method."""
2436
2437 async def test_add_additional_items(
2438 self, mocked: aioresponses, cookidoo: Cookidoo
2439 ) -> None:
2440 """Test for add_additional_items."""
2441
2442 mocked.post(
2443 "https://cookidoo.ch/shopping/de-CH/additional-items/add",
2444 payload=COOKIDOO_TEST_RESPONSE_ADD_ADDITIONAL_ITEMS,
2445 status=HTTPStatus.OK,
2446 )
2447
2448 data = await cookidoo.add_additional_items(["Fleisch", "Fisch"])
2449 assert data
2450 assert isinstance(data, list)
2451 assert len(data) == 2
2452
2453 @pytest.mark.parametrize(
2454 "exception",
2455 [
2456 TimeoutError,
2457 ClientError,
2458 ],
2459 )
2460 async def test_request_exception(
2461 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2462 ) -> None:
2463 """Test request exceptions."""
2464
2465 mocked.post(
2466 "https://cookidoo.ch/shopping/de-CH/additional-items/add",
2467 exception=exception,
2468 )
2469
2470 with pytest.raises(CookidooRequestException):
2471 await cookidoo.add_additional_items(["Fleisch", "Fisch"])
2472
2473 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2474 """Test unauthorized exception."""
2475 mocked.post(
2476 "https://cookidoo.ch/shopping/de-CH/additional-items/add",
2477 status=HTTPStatus.UNAUTHORIZED,
2478 payload={"error_description": ""},
2479 )
2480 with pytest.raises(CookidooAuthException):
2481 await cookidoo.add_additional_items(["Fleisch", "Fisch"])
2482
2483 @pytest.mark.parametrize(
2484 ("status", "exception"),
2485 [
2486 (HTTPStatus.OK, CookidooParseException),
2487 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2488 ],
2489 )
2490 async def test_parse_exception(
2491 self,
2492 mocked: aioresponses,
2493 cookidoo: Cookidoo,
2494 status: HTTPStatus,
2495 exception: type[CookidooException],
2496 ) -> None:
2497 """Test parse exceptions."""
2498 mocked.post(
2499 "https://cookidoo.ch/shopping/de-CH/additional-items/add",
2500 status=status,
2501 body="not json",
2502 content_type="application/json",
2503 )
2504
2505 with pytest.raises(exception):
2506 await cookidoo.add_additional_items(["Fleisch", "Fisch"])
2507
2508
2509 class TestRemoveAdditionalItems:
2510 """Tests for remove_ingredient_items_for_recipes method."""
2511
2512 async def test_remove_ingredient_items_for_recipes(
2513 self, mocked: aioresponses, cookidoo: Cookidoo
2514 ) -> None:
2515 """Test for remove_ingredient_items_for_recipes."""
2516
2517 mocked.post(
2518 "https://cookidoo.ch/shopping/de-CH/additional-items/remove",
2519 payload=None,
2520 status=HTTPStatus.OK,
2521 )
2522
2523 await cookidoo.remove_additional_items(
2524 ["01JBQGDMRMR7RJW1C8AWDGD6YP", "01JBQGDMRNHAM7AMCR6YKPYKJQ"]
2525 )
2526
2527 @pytest.mark.parametrize(
2528 "exception",
2529 [
2530 TimeoutError,
2531 ClientError,
2532 ],
2533 )
2534 async def test_request_exception(
2535 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2536 ) -> None:
2537 """Test request exceptions."""
2538
2539 mocked.post(
2540 "https://cookidoo.ch/shopping/de-CH/additional-items/remove",
2541 exception=exception,
2542 )
2543
2544 with pytest.raises(CookidooRequestException):
2545 await cookidoo.remove_additional_items(
2546 ["01JBQGDMRMR7RJW1C8AWDGD6YP", "01JBQGDMRNHAM7AMCR6YKPYKJQ"]
2547 )
2548
2549 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2550 """Test unauthorized exception."""
2551 mocked.post(
2552 "https://cookidoo.ch/shopping/de-CH/additional-items/remove",
2553 status=HTTPStatus.UNAUTHORIZED,
2554 payload={"error_description": ""},
2555 )
2556 with pytest.raises(CookidooAuthException):
2557 await cookidoo.remove_additional_items(
2558 ["01JBQGDMRMR7RJW1C8AWDGD6YP", "01JBQGDMRNHAM7AMCR6YKPYKJQ"]
2559 )
2560
2561 @pytest.mark.parametrize(
2562 ("status", "exception"),
2563 [
2564 # (HTTPStatus.OK, CookidooParseException), # There is nothing to parse
2565 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2566 ],
2567 )
2568 async def test_parse_exception(
2569 self,
2570 mocked: aioresponses,
2571 cookidoo: Cookidoo,
2572 status: HTTPStatus,
2573 exception: type[CookidooException],
2574 ) -> None:
2575 """Test parse exceptions."""
2576 mocked.post(
2577 "https://cookidoo.ch/shopping/de-CH/additional-items/remove",
2578 status=status,
2579 body="not json",
2580 content_type="application/json",
2581 )
2582
2583 with pytest.raises(exception):
2584 await cookidoo.remove_additional_items(
2585 ["01JBQGDMRMR7RJW1C8AWDGD6YP", "01JBQGDMRNHAM7AMCR6YKPYKJQ"]
2586 )
2587
2588
2589 class TestEditAdditionalItemsOwnership:
2590 """Tests for edit_additional_items_ownership method."""
2591
2592 async def test_edit_additional_items_ownership(
2593 self, mocked: aioresponses, cookidoo: Cookidoo
2594 ) -> None:
2595 """Test for edit_additional_items_ownership."""
2596
2597 mocked.post(
2598 "https://cookidoo.ch/shopping/de-CH/additional-items/ownership/edit",
2599 payload=COOKIDOO_TEST_RESPONSE_EDIT_ADDITIONAL_ITEMS_OWNERSHIP,
2600 status=HTTPStatus.OK,
2601 )
2602
2603 data = await cookidoo.edit_additional_items_ownership(
2604 [
2605 CookidooAdditionalItem(
2606 id="01JBQGMGMY4KD9ZGTKAS6GQME0",
2607 name="Fisch",
2608 is_owned=True,
2609 )
2610 ]
2611 )
2612 assert data
2613 assert isinstance(data, list)
2614 assert len(data) == 1
2615 assert data[0].is_owned
2616
2617 @pytest.mark.parametrize(
2618 "exception",
2619 [
2620 TimeoutError,
2621 ClientError,
2622 ],
2623 )
2624 async def test_request_exception(
2625 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2626 ) -> None:
2627 """Test request exceptions."""
2628
2629 mocked.post(
2630 "https://cookidoo.ch/shopping/de-CH/additional-items/ownership/edit",
2631 exception=exception,
2632 )
2633
2634 with pytest.raises(CookidooRequestException):
2635 await cookidoo.edit_additional_items_ownership(
2636 [
2637 CookidooAdditionalItem(
2638 id="01JBQGMGMY4KD9ZGTKAS6GQME0",
2639 name="Fisch",
2640 is_owned=True,
2641 )
2642 ]
2643 )
2644
2645 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2646 """Test unauthorized exception."""
2647 mocked.post(
2648 "https://cookidoo.ch/shopping/de-CH/additional-items/ownership/edit",
2649 status=HTTPStatus.UNAUTHORIZED,
2650 payload={"error_description": ""},
2651 )
2652 with pytest.raises(CookidooAuthException):
2653 await cookidoo.edit_additional_items_ownership(
2654 [
2655 CookidooAdditionalItem(
2656 id="01JBQGMGMY4KD9ZGTKAS6GQME0",
2657 name="Fisch",
2658 is_owned=True,
2659 )
2660 ]
2661 )
2662
2663 @pytest.mark.parametrize(
2664 ("status", "exception"),
2665 [
2666 (HTTPStatus.OK, CookidooParseException),
2667 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2668 ],
2669 )
2670 async def test_parse_exception(
2671 self,
2672 mocked: aioresponses,
2673 cookidoo: Cookidoo,
2674 status: HTTPStatus,
2675 exception: type[CookidooException],
2676 ) -> None:
2677 """Test parse exceptions."""
2678 mocked.post(
2679 "https://cookidoo.ch/shopping/de-CH/additional-items/ownership/edit",
2680 status=status,
2681 body="not json",
2682 content_type="application/json",
2683 )
2684
2685 with pytest.raises(exception):
2686 await cookidoo.edit_additional_items_ownership(
2687 [
2688 CookidooAdditionalItem(
2689 id="01JBQGMGMY4KD9ZGTKAS6GQME0",
2690 name="Fisch",
2691 is_owned=True,
2692 )
2693 ]
2694 )
2695
2696
2697 class TestEditAdditionalItems:
2698 """Tests for edit_additional_items method."""
2699
2700 async def test_edit_additional_items(
2701 self, mocked: aioresponses, cookidoo: Cookidoo
2702 ) -> None:
2703 """Test for edit_additional_items."""
2704
2705 mocked.post(
2706 "https://cookidoo.ch/shopping/de-CH/additional-items/edit",
2707 payload=COOKIDOO_TEST_RESPONSE_EDIT_ADDITIONAL_ITEMS,
2708 status=HTTPStatus.OK,
2709 )
2710
2711 data = await cookidoo.edit_additional_items(
2712 [
2713 CookidooAdditionalItem(
2714 id="01JBQGT72WP8Z31VCPQPT5VC6F",
2715 name="Vogel",
2716 is_owned=True,
2717 )
2718 ]
2719 )
2720 assert data
2721 assert isinstance(data, list)
2722 assert len(data) == 1
2723 assert data[0].name == "Vogel"
2724
2725 @pytest.mark.parametrize(
2726 "exception",
2727 [
2728 TimeoutError,
2729 ClientError,
2730 ],
2731 )
2732 async def test_request_exception(
2733 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2734 ) -> None:
2735 """Test request exceptions."""
2736
2737 mocked.post(
2738 "https://cookidoo.ch/shopping/de-CH/additional-items/edit",
2739 exception=exception,
2740 )
2741
2742 with pytest.raises(CookidooRequestException):
2743 await cookidoo.edit_additional_items(
2744 [
2745 CookidooAdditionalItem(
2746 id="01JBQGT72WP8Z31VCPQPT5VC6F",
2747 name="Vogel",
2748 is_owned=True,
2749 )
2750 ]
2751 )
2752
2753 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2754 """Test unauthorized exception."""
2755 mocked.post(
2756 "https://cookidoo.ch/shopping/de-CH/additional-items/edit",
2757 status=HTTPStatus.UNAUTHORIZED,
2758 payload={"error_description": ""},
2759 )
2760 with pytest.raises(CookidooAuthException):
2761 await cookidoo.edit_additional_items(
2762 [
2763 CookidooAdditionalItem(
2764 id="01JBQGT72WP8Z31VCPQPT5VC6F",
2765 name="Vogel",
2766 is_owned=True,
2767 )
2768 ]
2769 )
2770
2771 @pytest.mark.parametrize(
2772 ("status", "exception"),
2773 [
2774 (HTTPStatus.OK, CookidooParseException),
2775 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2776 ],
2777 )
2778 async def test_parse_exception(
2779 self,
2780 mocked: aioresponses,
2781 cookidoo: Cookidoo,
2782 status: HTTPStatus,
2783 exception: type[CookidooException],
2784 ) -> None:
2785 """Test parse exceptions."""
2786 mocked.post(
2787 "https://cookidoo.ch/shopping/de-CH/additional-items/edit",
2788 status=status,
2789 body="not json",
2790 content_type="application/json",
2791 )
2792
2793 with pytest.raises(exception):
2794 await cookidoo.edit_additional_items(
2795 [
2796 CookidooAdditionalItem(
2797 id="01JBQGT72WP8Z31VCPQPT5VC6F",
2798 name="Vogel",
2799 is_owned=True,
2800 )
2801 ]
2802 )
2803
2804
2805 class TestClearShoppingList:
2806 """Tests for clear_shopping_list method."""
2807
2808 async def test_clear_shopping_list(
2809 self, mocked: aioresponses, cookidoo: Cookidoo
2810 ) -> None:
2811 """Test for clear_shopping_list."""
2812
2813 mocked.delete(
2814 "https://cookidoo.ch/shopping/de-CH",
2815 payload=None,
2816 status=HTTPStatus.OK,
2817 )
2818
2819 await cookidoo.clear_shopping_list()
2820
2821 @pytest.mark.parametrize(
2822 "exception",
2823 [
2824 TimeoutError,
2825 ClientError,
2826 ],
2827 )
2828 async def test_request_exception(
2829 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2830 ) -> None:
2831 """Test request exceptions."""
2832
2833 mocked.delete(
2834 "https://cookidoo.ch/shopping/de-CH",
2835 exception=exception,
2836 )
2837
2838 with pytest.raises(CookidooRequestException):
2839 await cookidoo.clear_shopping_list()
2840
2841 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2842 """Test unauthorized exception."""
2843 mocked.delete(
2844 "https://cookidoo.ch/shopping/de-CH",
2845 status=HTTPStatus.UNAUTHORIZED,
2846 payload={"error_description": ""},
2847 )
2848 with pytest.raises(CookidooAuthException):
2849 await cookidoo.clear_shopping_list()
2850
2851 @pytest.mark.parametrize(
2852 ("status", "exception"),
2853 [
2854 # (HTTPStatus.OK, CookidooParseException), # There is nothing to parse
2855 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2856 ],
2857 )
2858 async def test_parse_exception(
2859 self,
2860 mocked: aioresponses,
2861 cookidoo: Cookidoo,
2862 status: HTTPStatus,
2863 exception: type[CookidooException],
2864 ) -> None:
2865 """Test parse exceptions."""
2866 mocked.delete(
2867 "https://cookidoo.ch/shopping/de-CH",
2868 status=status,
2869 body="not json",
2870 content_type="application/json",
2871 )
2872
2873 with pytest.raises(exception):
2874 await cookidoo.clear_shopping_list()
2875
2876
2877 class TestCountManagedLists:
2878 """Tests for count_managed_lists method."""
2879
2880 async def test_count_managed_lists(
2881 self, mocked: aioresponses, cookidoo: Cookidoo
2882 ) -> None:
2883 """Test for count_managed_lists."""
2884
2885 mocked.get(
2886 "https://cookidoo.ch/organize/de-CH/api/managed-list",
2887 payload=COOKIDOO_TEST_RESPONSE_GET_MANAGED_COLLECTIONS,
2888 status=HTTPStatus.OK,
2889 )
2890
2891 count_recipes, count_pages = await cookidoo.count_managed_collections()
2892 assert count_recipes == 1
2893 assert count_pages == 1
2894
2895 @pytest.mark.parametrize(
2896 "exception",
2897 [
2898 TimeoutError,
2899 ClientError,
2900 ],
2901 )
2902 async def test_request_exception(
2903 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2904 ) -> None:
2905 """Test request exceptions."""
2906
2907 mocked.get(
2908 "https://cookidoo.ch/organize/de-CH/api/managed-list",
2909 exception=exception,
2910 )
2911
2912 with pytest.raises(CookidooRequestException):
2913 await cookidoo.count_managed_collections()
2914
2915 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2916 """Test unauthorized exception."""
2917 mocked.get(
2918 "https://cookidoo.ch/organize/de-CH/api/managed-list",
2919 status=HTTPStatus.UNAUTHORIZED,
2920 payload={"error_description": ""},
2921 )
2922 with pytest.raises(CookidooAuthException):
2923 await cookidoo.count_managed_collections()
2924
2925 @pytest.mark.parametrize(
2926 ("status", "exception"),
2927 [
2928 (HTTPStatus.OK, CookidooParseException),
2929 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
2930 ],
2931 )
2932 async def test_parse_exception(
2933 self,
2934 mocked: aioresponses,
2935 cookidoo: Cookidoo,
2936 status: HTTPStatus,
2937 exception: type[CookidooException],
2938 ) -> None:
2939 """Test parse exceptions."""
2940 mocked.get(
2941 "https://cookidoo.ch/organize/de-CH/api/managed-list",
2942 status=status,
2943 body="not json",
2944 content_type="application/json",
2945 )
2946
2947 with pytest.raises(exception):
2948 await cookidoo.count_managed_collections()
2949
2950
2951 class TestGetManagedLists:
2952 """Tests for get_managed_lists method."""
2953
2954 async def test_get_managed_lists(
2955 self, mocked: aioresponses, cookidoo: Cookidoo
2956 ) -> None:
2957 """Test for get_managed_lists."""
2958
2959 mocked.get(
2960 "https://cookidoo.ch/organize/de-CH/api/managed-list?page=0",
2961 payload=COOKIDOO_TEST_RESPONSE_GET_MANAGED_COLLECTIONS,
2962 status=HTTPStatus.OK,
2963 )
2964
2965 data = await cookidoo.get_managed_collections()
2966 assert data
2967 assert isinstance(data, list)
2968 assert len(data) == 1
2969
2970 @pytest.mark.parametrize(
2971 "exception",
2972 [
2973 TimeoutError,
2974 ClientError,
2975 ],
2976 )
2977 async def test_request_exception(
2978 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
2979 ) -> None:
2980 """Test request exceptions."""
2981
2982 mocked.get(
2983 "https://cookidoo.ch/organize/de-CH/api/managed-list?page=0",
2984 exception=exception,
2985 )
2986
2987 with pytest.raises(CookidooRequestException):
2988 await cookidoo.get_managed_collections()
2989
2990 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
2991 """Test unauthorized exception."""
2992 mocked.get(
2993 "https://cookidoo.ch/organize/de-CH/api/managed-list?page=0",
2994 status=HTTPStatus.UNAUTHORIZED,
2995 payload={"error_description": ""},
2996 )
2997 with pytest.raises(CookidooAuthException):
2998 await cookidoo.get_managed_collections()
2999
3000 @pytest.mark.parametrize(
3001 ("status", "exception"),
3002 [
3003 (HTTPStatus.OK, CookidooParseException),
3004 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3005 ],
3006 )
3007 async def test_parse_exception(
3008 self,
3009 mocked: aioresponses,
3010 cookidoo: Cookidoo,
3011 status: HTTPStatus,
3012 exception: type[CookidooException],
3013 ) -> None:
3014 """Test parse exceptions."""
3015 mocked.get(
3016 "https://cookidoo.ch/organize/de-CH/api/managed-list?page=0",
3017 status=status,
3018 body="not json",
3019 content_type="application/json",
3020 )
3021
3022 with pytest.raises(exception):
3023 await cookidoo.get_managed_collections()
3024
3025
3026 class TestAddManagedCollection:
3027 """Tests for add_managed_collection method."""
3028
3029 async def test_add_managed_collection(
3030 self, mocked: aioresponses, cookidoo: Cookidoo
3031 ) -> None:
3032 """Test for add_managed_collection."""
3033
3034 mocked.post(
3035 "https://cookidoo.ch/organize/de-CH/api/managed-list",
3036 payload=COOKIDOO_TEST_RESPONSE_ADD_MANAGED_COLLECTION,
3037 status=HTTPStatus.OK,
3038 )
3039
3040 data = await cookidoo.add_managed_collection("col500561")
3041 assert data
3042 assert data.id == "col500561"
3043
3044 @pytest.mark.parametrize(
3045 "exception",
3046 [
3047 TimeoutError,
3048 ClientError,
3049 ],
3050 )
3051 async def test_request_exception(
3052 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3053 ) -> None:
3054 """Test request exceptions."""
3055
3056 mocked.post(
3057 "https://cookidoo.ch/organize/de-CH/api/managed-list",
3058 exception=exception,
3059 )
3060
3061 with pytest.raises(CookidooRequestException):
3062 await cookidoo.add_managed_collection("col500561")
3063
3064 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3065 """Test unauthorized exception."""
3066 mocked.post(
3067 "https://cookidoo.ch/organize/de-CH/api/managed-list",
3068 status=HTTPStatus.UNAUTHORIZED,
3069 payload={"error_description": ""},
3070 )
3071 with pytest.raises(CookidooAuthException):
3072 await cookidoo.add_managed_collection("col500561")
3073
3074 @pytest.mark.parametrize(
3075 ("status", "exception"),
3076 [
3077 (HTTPStatus.OK, CookidooParseException),
3078 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3079 ],
3080 )
3081 async def test_parse_exception(
3082 self,
3083 mocked: aioresponses,
3084 cookidoo: Cookidoo,
3085 status: HTTPStatus,
3086 exception: type[CookidooException],
3087 ) -> None:
3088 """Test parse exceptions."""
3089 mocked.post(
3090 "https://cookidoo.ch/organize/de-CH/api/managed-list",
3091 status=status,
3092 body="not json",
3093 content_type="application/json",
3094 )
3095
3096 with pytest.raises(exception):
3097 await cookidoo.add_managed_collection("col500561")
3098
3099
3100 class TestRemoveManagedCollection:
3101 """Tests for remove_managed_collection method."""
3102
3103 async def test_remove_managed_collection(
3104 self, mocked: aioresponses, cookidoo: Cookidoo
3105 ) -> None:
3106 """Test for remove_managed_collection."""
3107
3108 mocked.delete(
3109 "https://cookidoo.ch/organize/de-CH/api/managed-list/col500561",
3110 payload=None,
3111 status=HTTPStatus.OK,
3112 )
3113
3114 await cookidoo.remove_managed_collection("col500561")
3115
3116 @pytest.mark.parametrize(
3117 "exception",
3118 [
3119 TimeoutError,
3120 ClientError,
3121 ],
3122 )
3123 async def test_request_exception(
3124 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3125 ) -> None:
3126 """Test request exceptions."""
3127
3128 mocked.delete(
3129 "https://cookidoo.ch/organize/de-CH/api/managed-list/col500561",
3130 exception=exception,
3131 )
3132
3133 with pytest.raises(CookidooRequestException):
3134 await cookidoo.remove_managed_collection("col500561")
3135
3136 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3137 """Test unauthorized exception."""
3138 mocked.delete(
3139 "https://cookidoo.ch/organize/de-CH/api/managed-list/col500561",
3140 status=HTTPStatus.UNAUTHORIZED,
3141 payload={"error_description": ""},
3142 )
3143 with pytest.raises(CookidooAuthException):
3144 await cookidoo.remove_managed_collection("col500561")
3145
3146 @pytest.mark.parametrize(
3147 ("status", "exception"),
3148 [
3149 # (HTTPStatus.OK, CookidooParseException), # There is nothing to parse
3150 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3151 ],
3152 )
3153 async def test_parse_exception(
3154 self,
3155 mocked: aioresponses,
3156 cookidoo: Cookidoo,
3157 status: HTTPStatus,
3158 exception: type[CookidooException],
3159 ) -> None:
3160 """Test parse exceptions."""
3161 mocked.delete(
3162 "https://cookidoo.ch/organize/de-CH/api/managed-list/col500561",
3163 status=status,
3164 body="not json",
3165 content_type="application/json",
3166 )
3167
3168 with pytest.raises(exception):
3169 await cookidoo.remove_managed_collection("col500561")
3170
3171
3172 class TestCountCustomLists:
3173 """Tests for count_custom_lists method."""
3174
3175 async def test_count_custom_lists(
3176 self, mocked: aioresponses, cookidoo: Cookidoo
3177 ) -> None:
3178 """Test for count_custom_lists."""
3179
3180 mocked.get(
3181 "https://cookidoo.ch/organize/de-CH/api/custom-list",
3182 payload=COOKIDOO_TEST_RESPONSE_GET_CUSTOM_COLLECTIONS,
3183 status=HTTPStatus.OK,
3184 )
3185
3186 count_recipes, count_pages = await cookidoo.count_custom_collections()
3187 assert count_recipes == 1
3188 assert count_pages == 1
3189
3190 @pytest.mark.parametrize(
3191 "exception",
3192 [
3193 TimeoutError,
3194 ClientError,
3195 ],
3196 )
3197 async def test_request_exception(
3198 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3199 ) -> None:
3200 """Test request exceptions."""
3201
3202 mocked.get(
3203 "https://cookidoo.ch/organize/de-CH/api/custom-list",
3204 exception=exception,
3205 )
3206
3207 with pytest.raises(CookidooRequestException):
3208 await cookidoo.count_custom_collections()
3209
3210 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3211 """Test unauthorized exception."""
3212 mocked.get(
3213 "https://cookidoo.ch/organize/de-CH/api/custom-list",
3214 status=HTTPStatus.UNAUTHORIZED,
3215 payload={"error_description": ""},
3216 )
3217 with pytest.raises(CookidooAuthException):
3218 await cookidoo.count_custom_collections()
3219
3220 @pytest.mark.parametrize(
3221 ("status", "exception"),
3222 [
3223 (HTTPStatus.OK, CookidooParseException),
3224 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3225 ],
3226 )
3227 async def test_parse_exception(
3228 self,
3229 mocked: aioresponses,
3230 cookidoo: Cookidoo,
3231 status: HTTPStatus,
3232 exception: type[CookidooException],
3233 ) -> None:
3234 """Test parse exceptions."""
3235 mocked.get(
3236 "https://cookidoo.ch/organize/de-CH/api/custom-list",
3237 status=status,
3238 body="not json",
3239 content_type="application/json",
3240 )
3241
3242 with pytest.raises(exception):
3243 await cookidoo.count_custom_collections()
3244
3245
3246 class TestGetCustomLists:
3247 """Tests for get_custom_lists method."""
3248
3249 async def test_get_custom_lists(
3250 self, mocked: aioresponses, cookidoo: Cookidoo
3251 ) -> None:
3252 """Test for get_custom_lists."""
3253
3254 mocked.get(
3255 "https://cookidoo.ch/organize/de-CH/api/custom-list?page=0",
3256 payload=COOKIDOO_TEST_RESPONSE_GET_CUSTOM_COLLECTIONS,
3257 status=HTTPStatus.OK,
3258 )
3259
3260 data = await cookidoo.get_custom_collections()
3261 assert data
3262 assert isinstance(data, list)
3263 assert len(data) == 1
3264
3265 @pytest.mark.parametrize(
3266 "exception",
3267 [
3268 TimeoutError,
3269 ClientError,
3270 ],
3271 )
3272 async def test_request_exception(
3273 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3274 ) -> None:
3275 """Test request exceptions."""
3276
3277 mocked.get(
3278 "https://cookidoo.ch/organize/de-CH/api/custom-list?page=0",
3279 exception=exception,
3280 )
3281
3282 with pytest.raises(CookidooRequestException):
3283 await cookidoo.get_custom_collections()
3284
3285 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3286 """Test unauthorized exception."""
3287 mocked.get(
3288 "https://cookidoo.ch/organize/de-CH/api/custom-list?page=0",
3289 status=HTTPStatus.UNAUTHORIZED,
3290 payload={"error_description": ""},
3291 )
3292 with pytest.raises(CookidooAuthException):
3293 await cookidoo.get_custom_collections()
3294
3295 @pytest.mark.parametrize(
3296 ("status", "exception"),
3297 [
3298 (HTTPStatus.OK, CookidooParseException),
3299 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3300 ],
3301 )
3302 async def test_parse_exception(
3303 self,
3304 mocked: aioresponses,
3305 cookidoo: Cookidoo,
3306 status: HTTPStatus,
3307 exception: type[CookidooException],
3308 ) -> None:
3309 """Test parse exceptions."""
3310 mocked.get(
3311 "https://cookidoo.ch/organize/de-CH/api/custom-list?page=0",
3312 status=status,
3313 body="not json",
3314 content_type="application/json",
3315 )
3316
3317 with pytest.raises(exception):
3318 await cookidoo.get_custom_collections()
3319
3320
3321 class TestAddCustomCollection:
3322 """Tests for add_custom_collection method."""
3323
3324 async def test_add_custom_collection(
3325 self, mocked: aioresponses, cookidoo: Cookidoo
3326 ) -> None:
3327 """Test for add_custom_collection."""
3328
3329 mocked.post(
3330 "https://cookidoo.ch/organize/de-CH/api/custom-list",
3331 payload=COOKIDOO_TEST_RESPONSE_ADD_CUSTOM_COLLECTION,
3332 status=HTTPStatus.OK,
3333 )
3334
3335 data = await cookidoo.add_custom_collection("Testliste")
3336 assert data
3337 assert data.id == "01JC1SRPRSW0SHE0AK8GCASABX"
3338 assert data.name == "Testliste"
3339
3340 @pytest.mark.parametrize(
3341 "exception",
3342 [
3343 TimeoutError,
3344 ClientError,
3345 ],
3346 )
3347 async def test_request_exception(
3348 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3349 ) -> None:
3350 """Test request exceptions."""
3351
3352 mocked.post(
3353 "https://cookidoo.ch/organize/de-CH/api/custom-list",
3354 exception=exception,
3355 )
3356
3357 with pytest.raises(CookidooRequestException):
3358 await cookidoo.add_custom_collection("TEST_COLLECTION")
3359
3360 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3361 """Test unauthorized exception."""
3362 mocked.post(
3363 "https://cookidoo.ch/organize/de-CH/api/custom-list",
3364 status=HTTPStatus.UNAUTHORIZED,
3365 payload={"error_description": ""},
3366 )
3367 with pytest.raises(CookidooAuthException):
3368 await cookidoo.add_custom_collection("TEST_COLLECTION")
3369
3370 @pytest.mark.parametrize(
3371 ("status", "exception"),
3372 [
3373 (HTTPStatus.OK, CookidooParseException),
3374 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3375 ],
3376 )
3377 async def test_parse_exception(
3378 self,
3379 mocked: aioresponses,
3380 cookidoo: Cookidoo,
3381 status: HTTPStatus,
3382 exception: type[CookidooException],
3383 ) -> None:
3384 """Test parse exceptions."""
3385 mocked.post(
3386 "https://cookidoo.ch/organize/de-CH/api/custom-list",
3387 status=status,
3388 body="not json",
3389 content_type="application/json",
3390 )
3391
3392 with pytest.raises(exception):
3393 await cookidoo.add_custom_collection("TEST_COLLECTION")
3394
3395
3396 class TestRemoveCustomCollection:
3397 """Tests for remove_custom_collection method."""
3398
3399 async def test_remove_custom_collection(
3400 self, mocked: aioresponses, cookidoo: Cookidoo
3401 ) -> None:
3402 """Test for remove_custom_collection."""
3403
3404 mocked.delete(
3405 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX",
3406 payload=None,
3407 status=HTTPStatus.OK,
3408 )
3409
3410 await cookidoo.remove_custom_collection("01JC1SRPRSW0SHE0AK8GCASABX")
3411
3412 @pytest.mark.parametrize(
3413 "exception",
3414 [
3415 TimeoutError,
3416 ClientError,
3417 ],
3418 )
3419 async def test_request_exception(
3420 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3421 ) -> None:
3422 """Test request exceptions."""
3423
3424 mocked.delete(
3425 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX",
3426 exception=exception,
3427 )
3428
3429 with pytest.raises(CookidooRequestException):
3430 await cookidoo.remove_custom_collection("01JC1SRPRSW0SHE0AK8GCASABX")
3431
3432 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3433 """Test unauthorized exception."""
3434 mocked.delete(
3435 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX",
3436 status=HTTPStatus.UNAUTHORIZED,
3437 payload={"error_description": ""},
3438 )
3439 with pytest.raises(CookidooAuthException):
3440 await cookidoo.remove_custom_collection("01JC1SRPRSW0SHE0AK8GCASABX")
3441
3442 @pytest.mark.parametrize(
3443 ("status", "exception"),
3444 [
3445 # (HTTPStatus.OK, CookidooParseException), # There is nothing to parse
3446 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3447 ],
3448 )
3449 async def test_parse_exception(
3450 self,
3451 mocked: aioresponses,
3452 cookidoo: Cookidoo,
3453 status: HTTPStatus,
3454 exception: type[CookidooException],
3455 ) -> None:
3456 """Test parse exceptions."""
3457 mocked.delete(
3458 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX",
3459 status=status,
3460 body="not json",
3461 content_type="application/json",
3462 )
3463
3464 with pytest.raises(exception):
3465 await cookidoo.remove_custom_collection("01JC1SRPRSW0SHE0AK8GCASABX")
3466
3467
3468 class TestAddRecipesToCustomCollection:
3469 """Tests for add_recipes_to_custom_collection method."""
3470
3471 async def test_add_recipes_to_custom_collection(
3472 self, mocked: aioresponses, cookidoo: Cookidoo
3473 ) -> None:
3474 """Test for add_recipes_to_custom_collection."""
3475
3476 mocked.put(
3477 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX",
3478 payload=COOKIDOO_TEST_RESPONSE_ADD_RECIPES_TO_CUSTOM_COLLECTION,
3479 status=HTTPStatus.OK,
3480 )
3481
3482 data = await cookidoo.add_recipes_to_custom_collection(
3483 "01JC1SRPRSW0SHE0AK8GCASABX", ["r907015"]
3484 )
3485 assert data
3486 assert data.id == "01JC1SRPRSW0SHE0AK8GCASABX"
3487 assert data.chapters[0].recipes[0].id == "r907015"
3488
3489 @pytest.mark.parametrize(
3490 "exception",
3491 [
3492 TimeoutError,
3493 ClientError,
3494 ],
3495 )
3496 async def test_request_exception(
3497 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3498 ) -> None:
3499 """Test request exceptions."""
3500
3501 mocked.put(
3502 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX",
3503 exception=exception,
3504 )
3505
3506 with pytest.raises(CookidooRequestException):
3507 await cookidoo.add_recipes_to_custom_collection(
3508 "01JC1SRPRSW0SHE0AK8GCASABX", ["r907015"]
3509 )
3510
3511 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3512 """Test unauthorized exception."""
3513 mocked.put(
3514 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX",
3515 status=HTTPStatus.UNAUTHORIZED,
3516 payload={"error_description": ""},
3517 )
3518 with pytest.raises(CookidooAuthException):
3519 await cookidoo.add_recipes_to_custom_collection(
3520 "01JC1SRPRSW0SHE0AK8GCASABX", ["r907015"]
3521 )
3522
3523 @pytest.mark.parametrize(
3524 ("status", "exception"),
3525 [
3526 (HTTPStatus.OK, CookidooParseException),
3527 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3528 ],
3529 )
3530 async def test_parse_exception(
3531 self,
3532 mocked: aioresponses,
3533 cookidoo: Cookidoo,
3534 status: HTTPStatus,
3535 exception: type[CookidooException],
3536 ) -> None:
3537 """Test parse exceptions."""
3538 mocked.put(
3539 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX",
3540 status=status,
3541 body="not json",
3542 content_type="application/json",
3543 )
3544
3545 with pytest.raises(exception):
3546 await cookidoo.add_recipes_to_custom_collection(
3547 "01JC1SRPRSW0SHE0AK8GCASABX", ["r907015"]
3548 )
3549
3550
3551 class TestRemoveRecipeFromCustomCollection:
3552 """Tests for remove_recipe_from_custom_collection method."""
3553
3554 async def test_remove_recipe_from_custom_collection(
3555 self, mocked: aioresponses, cookidoo: Cookidoo
3556 ) -> None:
3557 """Test for remove_recipe_from_custom_collection."""
3558
3559 mocked.delete(
3560 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX/recipes/r907015",
3561 payload=COOKIDOO_TEST_RESPONSE_REMOVE_RECIPE_FROM_CUSTOM_COLLECTION,
3562 status=HTTPStatus.OK,
3563 )
3564
3565 data = await cookidoo.remove_recipe_from_custom_collection(
3566 "01JC1SRPRSW0SHE0AK8GCASABX", "r907015"
3567 )
3568 assert data
3569 assert data.id == "01JC1SRPRSW0SHE0AK8GCASABX"
3570 assert len(data.chapters[0].recipes) == 0
3571
3572 @pytest.mark.parametrize(
3573 "exception",
3574 [
3575 TimeoutError,
3576 ClientError,
3577 ],
3578 )
3579 async def test_request_exception(
3580 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3581 ) -> None:
3582 """Test request exceptions."""
3583
3584 mocked.delete(
3585 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX/recipes/r907015",
3586 exception=exception,
3587 )
3588
3589 with pytest.raises(CookidooRequestException):
3590 await cookidoo.remove_recipe_from_custom_collection(
3591 "01JC1SRPRSW0SHE0AK8GCASABX", "r907015"
3592 )
3593
3594 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3595 """Test unauthorized exception."""
3596 mocked.delete(
3597 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX/recipes/r907015",
3598 status=HTTPStatus.UNAUTHORIZED,
3599 payload={"error_description": ""},
3600 )
3601 with pytest.raises(CookidooAuthException):
3602 await cookidoo.remove_recipe_from_custom_collection(
3603 "01JC1SRPRSW0SHE0AK8GCASABX", "r907015"
3604 )
3605
3606 @pytest.mark.parametrize(
3607 ("status", "exception"),
3608 [
3609 (HTTPStatus.OK, CookidooParseException),
3610 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3611 ],
3612 )
3613 async def test_parse_exception(
3614 self,
3615 mocked: aioresponses,
3616 cookidoo: Cookidoo,
3617 status: HTTPStatus,
3618 exception: type[CookidooException],
3619 ) -> None:
3620 """Test parse exceptions."""
3621 mocked.delete(
3622 "https://cookidoo.ch/organize/de-CH/api/custom-list/01JC1SRPRSW0SHE0AK8GCASABX/recipes/r907015",
3623 status=status,
3624 body="not json",
3625 content_type="application/json",
3626 )
3627
3628 with pytest.raises(exception):
3629 await cookidoo.remove_recipe_from_custom_collection(
3630 "01JC1SRPRSW0SHE0AK8GCASABX", "r907015"
3631 )
3632
3633
3634 class TestGetCalendarWeek:
3635 """Tests for get_calendar_week method."""
3636
3637 async def test_get_calendar_week(
3638 self, mocked: aioresponses, cookidoo: Cookidoo
3639 ) -> None:
3640 """Test for get_calendar_week."""
3641
3642 mocked.get(
3643 "https://cookidoo.ch/planning/de-CH/api/my-week/2025-03-03",
3644 payload=COOKIDOO_TEST_RESPONSE_CALENDAR_WEEK,
3645 status=HTTPStatus.OK,
3646 )
3647
3648 data = await cookidoo.get_recipes_in_calendar_week(
3649 datetime.fromisoformat("2025-03-03").date()
3650 )
3651 assert data
3652 assert isinstance(data, list)
3653 assert len(data) == 2
3654 assert data[0].id == "2025-03-04"
3655 assert data[0].recipes[0].id == "r214846"
3656 assert data[1].id == "2025-03-05"
3657 assert data[1].recipes[0].id == "r338888"
3658
3659 @pytest.mark.parametrize(
3660 "exception",
3661 [
3662 TimeoutError,
3663 ClientError,
3664 ],
3665 )
3666 async def test_request_exception(
3667 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3668 ) -> None:
3669 """Test request exceptions."""
3670
3671 mocked.get(
3672 "https://cookidoo.ch/planning/de-CH/api/my-week/2025-03-03",
3673 exception=exception,
3674 )
3675
3676 with pytest.raises(CookidooRequestException):
3677 await cookidoo.get_recipes_in_calendar_week(
3678 datetime.fromisoformat("2025-03-03").date()
3679 )
3680
3681 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3682 """Test unauthorized exception."""
3683 mocked.get(
3684 "https://cookidoo.ch/planning/de-CH/api/my-week/2025-03-03",
3685 status=HTTPStatus.UNAUTHORIZED,
3686 payload={"error_description": ""},
3687 )
3688 with pytest.raises(CookidooAuthException):
3689 await cookidoo.get_recipes_in_calendar_week(
3690 datetime.fromisoformat("2025-03-03").date()
3691 )
3692
3693 @pytest.mark.parametrize(
3694 ("status", "exception"),
3695 [
3696 (HTTPStatus.OK, CookidooParseException),
3697 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3698 ],
3699 )
3700 async def test_parse_exception(
3701 self,
3702 mocked: aioresponses,
3703 cookidoo: Cookidoo,
3704 status: HTTPStatus,
3705 exception: type[CookidooException],
3706 ) -> None:
3707 """Test parse exceptions."""
3708 mocked.get(
3709 "https://cookidoo.ch/planning/de-CH/api/my-week/2025-03-03",
3710 status=status,
3711 body="not json",
3712 content_type="application/json",
3713 )
3714
3715 with pytest.raises(exception):
3716 await cookidoo.get_recipes_in_calendar_week(
3717 datetime.fromisoformat("2025-03-03").date()
3718 )
3719
3720
3721 class TestAddRecipesToCalendar:
3722 """Tests for add_recipes_to_calendar method."""
3723
3724 async def test_add_recipes_to_custom_collection(
3725 self, mocked: aioresponses, cookidoo: Cookidoo
3726 ) -> None:
3727 """Test for add_recipes_to_calendar."""
3728
3729 mocked.put(
3730 "https://cookidoo.ch/planning/de-CH/api/my-day",
3731 payload=COOKIDOO_TEST_RESPONSE_ADD_RECIPES_TO_CALENDAR,
3732 status=HTTPStatus.OK,
3733 )
3734
3735 data = await cookidoo.add_recipes_to_calendar(
3736 datetime.fromisoformat("2025-03-04").date(), ["r214846"]
3737 )
3738 assert data
3739 assert data.id == "2025-03-04"
3740 assert data.recipes[0].id == "r214846"
3741
3742 @pytest.mark.parametrize(
3743 "exception",
3744 [
3745 TimeoutError,
3746 ClientError,
3747 ],
3748 )
3749 async def test_request_exception(
3750 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3751 ) -> None:
3752 """Test request exceptions."""
3753
3754 mocked.put(
3755 "https://cookidoo.ch/planning/de-CH/api/my-day",
3756 exception=exception,
3757 )
3758
3759 with pytest.raises(CookidooRequestException):
3760 await cookidoo.add_recipes_to_calendar(
3761 datetime.fromisoformat("2025-03-04").date(), ["r214846"]
3762 )
3763
3764 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3765 """Test unauthorized exception."""
3766 mocked.put(
3767 "https://cookidoo.ch/planning/de-CH/api/my-day",
3768 status=HTTPStatus.UNAUTHORIZED,
3769 payload={"error_description": ""},
3770 )
3771 with pytest.raises(CookidooAuthException):
3772 await cookidoo.add_recipes_to_calendar(
3773 datetime.fromisoformat("2025-03-04").date(), ["r214846"]
3774 )
3775
3776 @pytest.mark.parametrize(
3777 ("status", "exception"),
3778 [
3779 (HTTPStatus.OK, CookidooParseException),
3780 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3781 ],
3782 )
3783 async def test_parse_exception(
3784 self,
3785 mocked: aioresponses,
3786 cookidoo: Cookidoo,
3787 status: HTTPStatus,
3788 exception: type[CookidooException],
3789 ) -> None:
3790 """Test parse exceptions."""
3791 mocked.put(
3792 "https://cookidoo.ch/planning/de-CH/api/my-day",
3793 status=status,
3794 body="not json",
3795 content_type="application/json",
3796 )
3797
3798 with pytest.raises(exception):
3799 await cookidoo.add_recipes_to_calendar(
3800 datetime.fromisoformat("2025-03-04").date(), ["r214846"]
3801 )
3802
3803
3804 class TestRemoveRecipeFromCalendar:
3805 """Tests for remove_recipe_from_calendar method."""
3806
3807 async def test_remove_recipe_from_calendar(
3808 self, mocked: aioresponses, cookidoo: Cookidoo
3809 ) -> None:
3810 """Test for remove_recipe_from_calendar."""
3811
3812 mocked.delete(
3813 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-03-04/recipes/r214846",
3814 payload=COOKIDOO_TEST_RESPONSE_REMOVE_RECIPE_FROM_CALENDAR,
3815 status=HTTPStatus.OK,
3816 )
3817
3818 data = await cookidoo.remove_recipe_from_calendar(
3819 datetime.fromisoformat("2025-03-04").date(), "r214846"
3820 )
3821 assert data
3822 assert data.id == "2025-03-04"
3823 assert data.recipes[0].id == "r214846"
3824
3825 async def test_remove_last_recipe_from_calendar(
3826 self, mocked: aioresponses, cookidoo: Cookidoo
3827 ) -> None:
3828 """Test for remove_recipe_from_calendar when the day becomes empty."""
3829
3830 mocked.delete(
3831 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-03-04/recipes/r214846",
3832 payload={"message": "Recipe Waffles was removed!", "content": None},
3833 status=HTTPStatus.OK,
3834 )
3835
3836 data = await cookidoo.remove_recipe_from_calendar(
3837 datetime.fromisoformat("2025-03-04").date(), "r214846"
3838 )
3839 assert data
3840 assert data.id == "2025-03-04"
3841 assert data.recipes == []
3842
3843 @pytest.mark.parametrize(
3844 "exception",
3845 [
3846 TimeoutError,
3847 ClientError,
3848 ],
3849 )
3850 async def test_request_exception(
3851 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3852 ) -> None:
3853 """Test request exceptions."""
3854
3855 mocked.delete(
3856 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-03-04/recipes/r214846",
3857 exception=exception,
3858 )
3859
3860 with pytest.raises(CookidooRequestException):
3861 await cookidoo.remove_recipe_from_calendar(
3862 datetime.fromisoformat("2025-03-04").date(), "r214846"
3863 )
3864
3865 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3866 """Test unauthorized exception."""
3867 mocked.delete(
3868 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-03-04/recipes/r214846",
3869 status=HTTPStatus.UNAUTHORIZED,
3870 payload={"error_description": ""},
3871 )
3872 with pytest.raises(CookidooAuthException):
3873 await cookidoo.remove_recipe_from_calendar(
3874 datetime.fromisoformat("2025-03-04").date(), "r214846"
3875 )
3876
3877 @pytest.mark.parametrize(
3878 ("status", "exception"),
3879 [
3880 (HTTPStatus.OK, CookidooParseException),
3881 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3882 ],
3883 )
3884 async def test_parse_exception(
3885 self,
3886 mocked: aioresponses,
3887 cookidoo: Cookidoo,
3888 status: HTTPStatus,
3889 exception: type[CookidooException],
3890 ) -> None:
3891 """Test parse exceptions."""
3892 mocked.delete(
3893 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-03-04/recipes/r214846",
3894 status=status,
3895 body="not json",
3896 content_type="application/json",
3897 )
3898
3899 with pytest.raises(exception):
3900 await cookidoo.remove_recipe_from_calendar(
3901 datetime.fromisoformat("2025-03-04").date(), "r214846"
3902 )
3903
3904
3905 class TestAddCustomRecipesToCalendar:
3906 """Tests for add_custom_recipes_to_calendar method."""
3907
3908 async def test_add_custom_recipes_to_custom_collection(
3909 self, mocked: aioresponses, cookidoo: Cookidoo
3910 ) -> None:
3911 """Test for add_custom_recipes_to_calendar."""
3912
3913 mocked.put(
3914 "https://cookidoo.ch/planning/de-CH/api/my-day",
3915 payload=COOKIDOO_TEST_RESPONSE_ADD_CUSTOM_RECIPES_TO_CALENDAR,
3916 status=HTTPStatus.OK,
3917 )
3918
3919 data = await cookidoo.add_custom_recipes_to_calendar(
3920 datetime.fromisoformat("2025-08-11").date(), ["01K2CTJ9Y1BABRG5MXK44CFZS4"]
3921 )
3922 assert data
3923 assert data.id == "2025-08-11"
3924
3925 @pytest.mark.parametrize(
3926 "exception",
3927 [
3928 TimeoutError,
3929 ClientError,
3930 ],
3931 )
3932 async def test_request_exception(
3933 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
3934 ) -> None:
3935 """Test request exceptions."""
3936
3937 mocked.put(
3938 "https://cookidoo.ch/planning/de-CH/api/my-day",
3939 exception=exception,
3940 )
3941
3942 with pytest.raises(CookidooRequestException):
3943 await cookidoo.add_custom_recipes_to_calendar(
3944 datetime.fromisoformat("2025-08-11").date(),
3945 ["01K2CTJ9Y1BABRG5MXK44CFZS4"],
3946 )
3947
3948 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
3949 """Test unauthorized exception."""
3950 mocked.put(
3951 "https://cookidoo.ch/planning/de-CH/api/my-day",
3952 status=HTTPStatus.UNAUTHORIZED,
3953 payload={"error_description": ""},
3954 )
3955 with pytest.raises(CookidooAuthException):
3956 await cookidoo.add_custom_recipes_to_calendar(
3957 datetime.fromisoformat("2025-08-11").date(),
3958 ["01K2CTJ9Y1BABRG5MXK44CFZS4"],
3959 )
3960
3961 @pytest.mark.parametrize(
3962 ("status", "exception"),
3963 [
3964 (HTTPStatus.OK, CookidooParseException),
3965 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
3966 ],
3967 )
3968 async def test_parse_exception(
3969 self,
3970 mocked: aioresponses,
3971 cookidoo: Cookidoo,
3972 status: HTTPStatus,
3973 exception: type[CookidooException],
3974 ) -> None:
3975 """Test parse exceptions."""
3976 mocked.put(
3977 "https://cookidoo.ch/planning/de-CH/api/my-day",
3978 status=status,
3979 body="not json",
3980 content_type="application/json",
3981 )
3982
3983 with pytest.raises(exception):
3984 await cookidoo.add_custom_recipes_to_calendar(
3985 datetime.fromisoformat("2025-08-11").date(),
3986 ["01K2CTJ9Y1BABRG5MXK44CFZS4"],
3987 )
3988
3989
3990 class TestRemoveCustomRecipeFromCalendar:
3991 """Tests for remove_custom_recipe_from_calendar method."""
3992
3993 async def test_remove_custom_recipe_from_calendar(
3994 self, mocked: aioresponses, cookidoo: Cookidoo
3995 ) -> None:
3996 """Test for remove_custom_recipe_from_calendar."""
3997
3998 mocked.delete(
3999 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-08-11/recipes/r214846?recipeSource=CUSTOMER",
4000 payload=COOKIDOO_TEST_RESPONSE_REMOVE_CUSTOM_RECIPE_FROM_CALENDAR,
4001 status=HTTPStatus.OK,
4002 )
4003
4004 data = await cookidoo.remove_custom_recipe_from_calendar(
4005 datetime.fromisoformat("2025-08-11").date(), "r214846"
4006 )
4007 assert data
4008 assert data.id == "2025-08-11"
4009
4010 async def test_remove_last_custom_recipe_from_calendar(
4011 self, mocked: aioresponses, cookidoo: Cookidoo
4012 ) -> None:
4013 """Test remove_custom_recipe_from_calendar when the day becomes empty."""
4014
4015 mocked.delete(
4016 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-08-11/recipes/r214846?recipeSource=CUSTOMER",
4017 payload={"message": "Recipe removed!", "content": None},
4018 status=HTTPStatus.OK,
4019 )
4020
4021 data = await cookidoo.remove_custom_recipe_from_calendar(
4022 datetime.fromisoformat("2025-08-11").date(), "r214846"
4023 )
4024 assert data
4025 assert data.id == "2025-08-11"
4026 assert data.recipes == []
4027
4028 @pytest.mark.parametrize(
4029 "exception",
4030 [
4031 TimeoutError,
4032 ClientError,
4033 ],
4034 )
4035 async def test_request_exception(
4036 self, mocked: aioresponses, cookidoo: Cookidoo, exception: Exception
4037 ) -> None:
4038 """Test request exceptions."""
4039
4040 mocked.delete(
4041 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-08-11/recipes/01K2CTJ9Y1BABRG5MXK44CFZS4?recipeSource=CUSTOMER",
4042 exception=exception,
4043 )
4044
4045 with pytest.raises(CookidooRequestException):
4046 await cookidoo.remove_custom_recipe_from_calendar(
4047 datetime.fromisoformat("2025-08-11").date(),
4048 "01K2CTJ9Y1BABRG5MXK44CFZS4",
4049 )
4050
4051 async def test_unauthorized(self, mocked: aioresponses, cookidoo: Cookidoo) -> None:
4052 """Test unauthorized exception."""
4053 mocked.delete(
4054 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-08-11/recipes/01K2CTJ9Y1BABRG5MXK44CFZS4?recipeSource=CUSTOMER",
4055 status=HTTPStatus.UNAUTHORIZED,
4056 payload={"error_description": ""},
4057 )
4058 with pytest.raises(CookidooAuthException):
4059 await cookidoo.remove_custom_recipe_from_calendar(
4060 datetime.fromisoformat("2025-08-11").date(),
4061 "01K2CTJ9Y1BABRG5MXK44CFZS4",
4062 )
4063
4064 @pytest.mark.parametrize(
4065 ("status", "exception"),
4066 [
4067 (HTTPStatus.OK, CookidooParseException),
4068 (HTTPStatus.UNAUTHORIZED, CookidooAuthException),
4069 ],
4070 )
4071 async def test_parse_exception(
4072 self,
4073 mocked: aioresponses,
4074 cookidoo: Cookidoo,
4075 status: HTTPStatus,
4076 exception: type[CookidooException],
4077 ) -> None:
4078 """Test parse exceptions."""
4079 mocked.delete(
4080 "https://cookidoo.ch/planning/de-CH/api/my-day/2025-08-11/recipes/01K2CTJ9Y1BABRG5MXK44CFZS4?recipeSource=CUSTOMER",
4081 status=status,
4082 body="not json",
4083 content_type="application/json",
4084 )
4085
4086 with pytest.raises(exception):
4087 await cookidoo.remove_custom_recipe_from_calendar(
4088 datetime.fromisoformat("2025-08-11").date(),
4089 "01K2CTJ9Y1BABRG5MXK44CFZS4",
4090 )
4091
4092
4093 class TestRemoteMonitoring:
4094 """Tests for remote-monitoring (device management) methods."""
4095
4096 MOBILE_HOME_URL = "https://cookidoo.ch/.well-known/mobile-home"
4097 RMI_CONFIG_URL = (
4098 "https://it.tmmobile.vorwerk-digital.com/rmi-config/.well-known/home"
4099 )
4100 DEVICES_URL = "https://iot-api.production-eu.cookidoo.vorwerk-digital.com/devices"
4101 REGISTER_URL = (
4102 "https://iot-api.production-eu.cookidoo.vorwerk-digital.com/device-token"
4103 )
4104 UNREGISTER_URL = "https://iot-api.production-eu.cookidoo.vorwerk-digital.com/token"
4105
4106 def _mock_rmi_resolution(self, mocked: aioresponses) -> None:
4107 mocked.get(self.MOBILE_HOME_URL, payload=COOKIDOO_TEST_RESPONSE_MOBILE_HOME)
4108 mocked.get(self.RMI_CONFIG_URL, payload=COOKIDOO_TEST_RESPONSE_RMI_CONFIG)
4109
4110 async def test_get_monitored_device_ids(
4111 self, mocked: aioresponses, cookidoo: Cookidoo
4112 ) -> None:
4113 """Test listing monitorable device ids."""
4114 self._mock_rmi_resolution(mocked)
4115 mocked.get(self.DEVICES_URL, payload=COOKIDOO_TEST_RESPONSE_MONITORED_DEVICES)
4116
4117 ids = await cookidoo.get_monitored_device_ids()
4118 assert ids == [
4119 "22e920b2d6184cec6c854cd005d6aa8fb851d7e783478b50f361ac8d1ab97bfe"
4120 ]
4121
4122 async def test_get_monitored_device_ids_empty(
4123 self, mocked: aioresponses, cookidoo: Cookidoo
4124 ) -> None:
4125 """Test listing when no device is currently monitorable."""
4126 self._mock_rmi_resolution(mocked)
4127 mocked.get(self.DEVICES_URL, payload=[])
4128
4129 assert await cookidoo.get_monitored_device_ids() == []
4130
4131 async def test_register_push_token(
4132 self, mocked: aioresponses, cookidoo: Cookidoo
4133 ) -> None:
4134 """Test registering a push token."""
4135 self._mock_rmi_resolution(mocked)
4136 mocked.post(self.REGISTER_URL, payload={"message": "OK"})
4137
4138 await cookidoo.register_push_token("fcm-token", "app-install-id")
4139
4140 async def test_unregister_push_token(
4141 self, mocked: aioresponses, cookidoo: Cookidoo
4142 ) -> None:
4143 """Test unregistering a push token."""
4144 self._mock_rmi_resolution(mocked)
4145 mocked.delete(self.UNREGISTER_URL, payload={"message": "OK"})
4146
4147 await cookidoo.unregister_push_token("fcm-token")
4148
4149 async def test_rmi_config_link_missing(
4150 self, mocked: aioresponses, cookidoo: Cookidoo
4151 ) -> None:
4152 """A home doc without the rmi-config link raises."""
4153 mocked.get(self.MOBILE_HOME_URL, payload={"_links": {}})
4154
4155 with pytest.raises(CookidooParseException, match="rmi-config link missing"):
4156 await cookidoo.get_monitored_device_ids()
4157
4158 async def test_rmi_links_are_cached(
4159 self, mocked: aioresponses, cookidoo: Cookidoo
4160 ) -> None:
4161 """The resolution walk runs once and is reused afterwards."""
4162 self._mock_rmi_resolution(mocked)
4163 mocked.get(self.DEVICES_URL, payload=[])
4164 mocked.get(self.DEVICES_URL, payload=[])
4165
4166 await cookidoo.get_monitored_device_ids()
4167 await cookidoo.get_monitored_device_ids()
4168
4169 # Only the first call walked mobile-home -> rmi-config.
4170 assert len(mocked.requests[("get", URL(self.MOBILE_HOME_URL))]) == 1
4171 assert len(mocked.requests[("get", URL(self.RMI_CONFIG_URL))]) == 1
4172
4173 async def test_mobile_home_without_links(
4174 self, mocked: aioresponses, cookidoo: Cookidoo
4175 ) -> None:
4176 """A home doc whose ``_links`` is not an object raises."""
4177 mocked.get(self.MOBILE_HOME_URL, payload={"_links": "not-an-object"})
4178
4179 with pytest.raises(CookidooParseException, match="rmi-config link missing"):
4180 await cookidoo.get_monitored_device_ids()
4181
4182 async def test_rmi_config_without_links(
4183 self, mocked: aioresponses, cookidoo: Cookidoo
4184 ) -> None:
4185 """An rmi-config document without a ``_links`` object raises."""
4186 mocked.get(self.MOBILE_HOME_URL, payload=COOKIDOO_TEST_RESPONSE_MOBILE_HOME)
4187 mocked.get(self.RMI_CONFIG_URL, payload={"_links": "not-an-object"})
4188
4189 with pytest.raises(CookidooParseException, match="during parsing"):
4190 await cookidoo.get_monitored_device_ids()
4191
4192 async def test_rmi_links_accept_both_hal_shapes(
4193 self, mocked: aioresponses, cookidoo: Cookidoo
4194 ) -> None:
4195 """A rel maps either to a bare href string or to a ``{"href": ...}``."""
4196 mocked.get(
4197 self.MOBILE_HOME_URL,
4198 payload={"_links": {"tmde2:rmi-config": self.RMI_CONFIG_URL}},
4199 )
4200 mocked.get(
4201 self.RMI_CONFIG_URL,
4202 payload={
4203 "_links": {
4204 "rmi:devices": self.DEVICES_URL,
4205 "rmi:unregister": {"href": self.UNREGISTER_URL},
4206 "rmi:ignored": {"no-href": True},
4207 }
4208 },
4209 )
4210 mocked.get(self.DEVICES_URL, payload=[])
4211
4212 assert await cookidoo.get_monitored_device_ids() == []
4213
4214 @pytest.mark.parametrize(
4215 ("rel", "call", "args"),
4216 [
4217 ("rmi:devices", "get_monitored_device_ids", ()),
4218 ("rmi:register-token", "register_push_token", ("fcm-token", "install-id")),
4219 ("rmi:unregister", "unregister_push_token", ("fcm-token",)),
4220 ],
4221 )
4222 async def test_rmi_endpoint_link_missing(
4223 self,
4224 mocked: aioresponses,
4225 cookidoo: Cookidoo,
4226 rel: str,
4227 call: str,
4228 args: tuple[str, ...],
4229 ) -> None:
4230 """Each endpoint reports its own missing link rather than failing late."""
4231 links = {
4232 k: v
4233 for k, v in COOKIDOO_TEST_RESPONSE_RMI_CONFIG["_links"].items()
4234 if k != rel
4235 }
4236 mocked.get(self.MOBILE_HOME_URL, payload=COOKIDOO_TEST_RESPONSE_MOBILE_HOME)
4237 mocked.get(self.RMI_CONFIG_URL, payload={"_links": links})
4238
4239 with pytest.raises(CookidooParseException, match=f"{rel} link missing"):
4240 await getattr(cookidoo, call)(*args)
4241
4242 @pytest.mark.parametrize(
4243 ("field", "value", "attr", "expected"),
4244 [
4245 # _push_timestamp: unparseable and empty strings degrade to None
4246 ("completedDate", "not-a-date", "completed_at", None),
4247 ("completedDate", "", "completed_at", None),
4248 ("completedDate", None, "completed_at", None),
4249 ("completedDate", ["unexpected", "shape"], "completed_at", None),
4250 # _push_number: sentinels, comma decimals and native numbers
4251 ("secondaryInfo", "---", "target_temperature", None),
4252 ("secondaryInfo", "", "target_temperature", None),
4253 ("secondaryInfo", "not-a-number", "target_temperature", None),
4254 ("secondaryInfo", "37,5", "target_temperature", 37.5),
4255 ("secondaryInfo", 95, "target_temperature", 95.0),
4256 ("secondaryInfo", None, "target_temperature", None),
4257 # _push_bool: real bools pass through, strings are coerced
4258 ("isTimeEstimated", True, "is_time_estimated", True),
4259 ("isTimeEstimated", "yes", "is_time_estimated", True),
4260 ("isTimeEstimated", "FALSE", "is_time_estimated", False),
4261 ("isTimeEstimated", 1, "is_time_estimated", True),
4262 ],
4263 )
4264 def test_cooking_activity_from_push_field_parsing(
4265 self, field: str, value: object, attr: str, expected: object
4266 ) -> None:
4267 """Malformed or alternately-typed push fields degrade instead of raising."""
4268 payload = {**COOKIDOO_TEST_PUSH_COOKING_ACTIVITY, field: value}
4269
4270 assert getattr(cooking_activity_from_push(payload), attr) == expected
4271
4272 @pytest.mark.parametrize("remaining", ["600", 600])
4273 def test_cooking_activity_from_push_remaining_duration(
4274 self, remaining: object
4275 ) -> None:
4276 """``remainingDuration`` arrives as a string or an int; both are used."""
4277 payload = {
4278 **COOKIDOO_TEST_PUSH_COOKING_ACTIVITY,
4279 "remainingDuration": remaining,
4280 }
4281
4282 assert cooking_activity_from_push(payload).remaining_seconds == 600
4283
4284 def test_cooking_activity_from_push_remaining_duration_unparseable(self) -> None:
4285 """An unparseable duration falls back to deriving it from the finish time."""
4286 payload = {
4287 **COOKIDOO_TEST_PUSH_COOKING_ACTIVITY,
4288 "remainingDuration": "not-a-number",
4289 }
4290
4291 remaining = cooking_activity_from_push(payload).remaining_seconds
4292 assert remaining is None or isinstance(remaining, int)
4293
4294 def test_cooking_activity_from_push_epoch_seconds(self) -> None:
4295 """Epoch timestamps arrive in millis or seconds; both decode."""
4296 millis = cooking_activity_from_push(
4297 {**COOKIDOO_TEST_PUSH_COOKING_ACTIVITY, "completedDate": "1787924895000"}
4298 )
4299 seconds = cooking_activity_from_push(
4300 {**COOKIDOO_TEST_PUSH_COOKING_ACTIVITY, "completedDate": 1787924895}
4301 )
4302
4303 assert millis.completed_at is not None
4304 assert seconds.completed_at is not None
4305 assert millis.completed_at == seconds.completed_at
4306
4307 def test_cooking_activity_from_push(self) -> None:
4308 """Test decoding a remote-monitoring push payload."""
4309 activity = cooking_activity_from_push(COOKIDOO_TEST_PUSH_COOKING_ACTIVITY)
4310 assert activity.state == CookidooCookState.RUNNING
4311 assert activity.is_active
4312 assert activity.recipe_name == "Purè di patate"
4313 assert activity.step == "5/9"
4314 assert activity.target_temperature == 95.0
4315 assert activity.current_temperature is None # "---" -> None
4316 assert activity.is_time_estimated is False # "false" -> False
4317 assert activity.recipe_type == "VORWERK"
4318 assert activity.completed_at is not None
4319 assert activity.stale_at is not None and activity.stale_at.year == 2026
4320
4321 def test_cooking_activity_from_push_done_is_inactive(self) -> None:
4322 """A done cook is not active."""
4323 activity = cooking_activity_from_push(
4324 {**COOKIDOO_TEST_PUSH_COOKING_ACTIVITY, "state": "done"}
4325 )
4326 assert activity.state == CookidooCookState.DONE
4327 assert not activity.is_active