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