Debian Codegraph @

tests/test_cookidoo.py

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