Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method set_list_article_language #60

Merged
merged 1 commit into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add method set_list_article_language
  • Loading branch information
tr4nt0r committed Jul 24, 2024
commit b37180dacd6dea4bb73f38c597953f4ac3a0edd6
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

# 0.8.0

* **New API method:** `set_list_article_language` sets the article language for a specified shopping list.

# 0.7.3

* Change `name` and `photoPath` in type definitions for `BringSyncCurrentUserResponse` and `BringAuthResponse` to optional parameters
Expand Down
67 changes: 67 additions & 0 deletions bring_api/bring.py
Original file line number Diff line number Diff line change
Expand Up @@ -1511,3 +1511,70 @@ async def retrieve_new_access_token(
self.expires_in = data["expires_in"]

return data

async def set_list_article_language(
self, list_uuid: str, language: str
) -> aiohttp.ClientResponse:
"""Set the article language for a specified list.

Parameters
----------
list_uuid : str
The unique identifier for the list.
language : str
The language to set for the list articles.

Returns
-------
aiohttp.ClientResponse
The server response object.

Raises
------
ValueError
If the specified language is not supported.
BringRequestException
If the request fails.
BringAuthException
If the request fails due to invalid or expired authorization token.

"""
if language not in BRING_SUPPORTED_LOCALES:
raise ValueError(f"Language {language} not supported.")

url = f"{self.url}bringusersettings/{self.uuid}/{list_uuid}/listArticleLanguage"

data = {"value": language}
try:
async with self._session.post(url, headers=self.headers, data=data) as r:
_LOGGER.debug(
"Response from %s [%s]: %s", url, r.status, await r.text()
)
if r.status == HTTPStatus.UNAUTHORIZED:
raise BringAuthException(
"Set list article language failed due to authorization failure, "
"the authorization token is invalid or expired."
)
r.raise_for_status()
self.user_list_settings = await self.__load_user_list_settings()
return r
except asyncio.TimeoutError as e:
_LOGGER.debug(
"Exception: Cannot set article language to %s for list %s:\n%s",
language,
list_uuid,
traceback.format_exc(),
)
raise BringRequestException(
"Set list article language failed due to connection timeout."
) from e
except aiohttp.ClientError as e:
_LOGGER.debug(
"Exception: Cannot set article language to %s for list %s:\n%s",
language,
list_uuid,
traceback.format_exc(),
)
raise BringRequestException(
"Set list article language failed due to request exception."
) from e
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = bring-api
version = 0.7.3
version = 0.8.0
author = Cyrill Raccaud
author_email = cyrill.raccaud+pypi@gmail.com
description = Unofficial package to access Bring! shopping lists API.
Expand Down
3 changes: 3 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Test script for Bring API."""

import asyncio
import logging
import os
Expand Down Expand Up @@ -230,5 +231,7 @@ async def main():

await test_batch_list_operations(bring, lst)

await bring.set_list_article_language(lst["listUuid"], "de-DE")


asyncio.run(main())
60 changes: 60 additions & 0 deletions tests/test_bring.py
Original file line number Diff line number Diff line change
Expand Up @@ -1395,3 +1395,63 @@ async def test_parse_exception(self, mocked, bring, status):

with pytest.raises(BringParseException):
await bring.retrieve_new_access_token()


class TestSetListArticleLanguage:
"""Tests for set_list_article_language method."""

async def test_set_list_article_language(self, mocked, bring, monkeypatch):
"""Test set list article language."""
mocked.post(
f"https://api.getbring.com/rest/bringusersettings/{UUID}/{UUID}/listArticleLanguage",
status=HTTPStatus.OK,
)

monkeypatch.setattr(bring, "uuid", UUID)

async def mocked__load_user_list_settings(*args, **kwargs):
"""Mock __load_user_list_settings."""
return {UUID: {"listArticleLanguage": "de-DE"}}

monkeypatch.setattr(
Bring, "_Bring__load_user_list_settings", mocked__load_user_list_settings
)

resp = await bring.set_list_article_language(UUID, "de-DE")
assert resp.status == HTTPStatus.OK

@pytest.mark.parametrize(
"exception",
[
asyncio.TimeoutError,
aiohttp.ClientError,
],
)
async def test_request_exception(self, mocked, bring, monkeypatch, exception):
"""Test request exceptions."""

mocked.post(
f"https://api.getbring.com/rest/bringusersettings/{UUID}/{UUID}/listArticleLanguage",
exception=exception,
)

monkeypatch.setattr(bring, "uuid", UUID)

with pytest.raises(BringRequestException):
await bring.set_list_article_language(UUID, "de-DE")

async def test_unauthorized(self, mocked, bring, monkeypatch):
"""Test unauthorized exception."""
mocked.post(
f"https://api.getbring.com/rest/bringusersettings/{UUID}/{UUID}/listArticleLanguage",
status=HTTPStatus.UNAUTHORIZED,
)
monkeypatch.setattr(bring, "uuid", UUID)
with pytest.raises(BringAuthException):
await bring.set_list_article_language(UUID, "de-DE")

async def test_value_error(self, bring):
"""Test ValueError exception."""

with pytest.raises(ValueError):
await bring.set_list_article_language(UUID, "es-CO")