8000 Fix formatting for new ruff rules · codesalatdev/python-picnic-api@eb28e02 · GitHub
[go: up one dir, main page]

Skip to content

Commit eb28e02

Browse files
committed
Fix formatting for new ruff rules
1 parent aaab1fb commit eb28e02

File tree

11 files changed

+125
-64
lines changed

11 files changed

+125
-64
lines changed

.github/workflows/ci.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ jobs:
4444
4545
- name: Lint with ruff
4646
run: |
47-
python -m poetry run ruff check
47+
python -m poetry run ruff check --output-format=github --ignore FIX
4848
4949

5050

integration_tests/test_client.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
from python_picnic_api2 import PicnicAPI
2-
from dotenv import load_dotenv
31
import os
4-
import pytest
52
import time
63

4+
import pytest
5+
from dotenv import load_dotenv
6+
7+
from python_picnic_api2 import PicnicAPI
8+
79
load_dotenv()
810

911
username = os.getenv("USERNAME")
@@ -28,23 +30,23 @@ def _get_amount(cart: dict, product_id: str):
2830
def test_get_user():
2931
response = picnic.get_user()
3032
assert isinstance(response, dict)
31-
assert "contact_email" in response.keys()
33+
assert "contact_email" in response
3234
assert response["contact_email"] == username
3335

3436

3537
def test_search():
3638
response = picnic.search("kaffee")
3739
assert isinstance(response, list)
3840
assert isinstance(response[0], dict)
39-
assert "items" in response[0].keys()
41+
assert "items" in response[0]
4042
assert isinstance(response[0]["items"], list)
4143
assert "id" in response[0]["items"][0]
4244

4345

4446
def test_get_article():
4547
response = picnic.get_article("s1018620")
4648
assert isinstance(response, dict)
47-
assert "id" in response.keys()
49+
assert "id" in response
4850
assert response["id"] == "s1018620"
4951
assert response["name"] == "Gut&Günstig H-Milch 3,5%"
5052

@@ -57,7 +59,7 @@ def test_get_article_with_category_name():
5759
def test_get_cart():
5860
response = picnic.get_cart()
5961
assert isinstance(response, dict)
60-
assert "id" in response.keys()
62+
assert "id" in response
6163
assert response["id"] == "shopping_cart"
6264

6365

@@ -67,9 +69,8 @@ def test_add_product():
6769
response = picnic.add_product("s1018620", count=2)
6870

6971
assert isinstance(response, dict)
70-
assert "items" in response.keys()
71-
assert any(
72-
item["id"] == "s1018620" for item in response["items"][0]["items"])
72+
assert "items" in response
73+
assert any(item["id"] == "s1018620" for item in response["items"][0]["items"])
7374
assert _get_amount(response, "s1018620") == 2
7475

7576

@@ -83,7 +84,7 @@ def test_remove_product():
8384
amount = _get_amount(response, "s1018620")
8485

8586
assert isinstance(response, dict)
86-
assert "items" in response.keys()
87+
assert "items" in response
8788
assert amount == 1
8889

8990

@@ -96,14 +97,14 @@ def test_clear_cart():
9697
response = picnic.clear_cart()
9798

9899
assert isinstance(response, dict)
99-
assert "items" in response.keys()
100+
assert "items" in response
100101
assert len(response["items"]) == 0
101102

102103

103104
def test_get_delivery_slots():
104105
response = picnic.get_delivery_slots()
105106
assert isinstance(response, dict)
106-
assert "delivery_slots" in response.keys()
107+
assert "delivery_slots" in response
107108
assert isinstance(response["delivery_slots"], list)
108109

109110

@@ -143,4 +144,4 @@ def test_print_categories(capsys):
143144
assert isinstance(captured.out, str)
144145

145146

146-
# TO DO: add test for re-logging
147+
# TODO: add test for re-logging

integration_tests/test_helper.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
from python_picnic_api2.helper import get_image, get_recipe_image
21
import requests
32

3+
from python_picnic_api2.helper import get_image, get_recipe_image
4+
45

56
def test_get_image():
67
id = "8560e1f1c2d2811dfefbbb2342ef0d95250533f2131416aca459bde35d73e901"

integration_tests/test_session.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
from python_picnic_api2.session import PicnicAPISession, PicnicAuthError
2-
from python_picnic_api2.client import PicnicAPI
3-
from requests import Session
4-
from dotenv import load_dotenv
51
import os
62

3+
from dotenv import load_dotenv
4+
from requests import Session
5+
6+
from python_picnic_api2.client import PicnicAPI
7+
from python_picnic_api2.session import PicnicAPISession, PicnicAuthError
8+
79
load_dotenv()
810

911
username = os.getenv("USERNAME")
@@ -19,16 +21,20 @@ def test_init():
1921

2022

2123
def test_login():
22-
client = PicnicAPI(username=username, password=password,
23-
country_code=country_code)
24-
assert "x-picnic-auth" in client.session.headers.keys()
24+
client = PicnicAPI(
25+
username=username, password=password, country_code=country_code
26+
)
27+
assert "x-picnic-auth" in client.session.headers
2528

2629

2730
def test_login_auth_error():
2831
try:
29-
PicnicAPI(username="doesnotexistblue@me.com", password="PasSWorD12345!",
30-
country_code=country_code)
32+
PicnicAPI(
33+
username="doesnotexistblue@me.com",
34+
password="PasSWorD12345!",
35+
country_code=country_code,
36+
)
3137
except PicnicAuthError:
3238
assert True
3339
else:
34-
assert False
40+
raise AssertionError()

poetry.lock

Lines changed: 13 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ authors = [
1414
urls = {homepage = "https://github.com/codesalatdev/python-picnic-api", repository = "https://github.com/codesalatdev/python-picnic-api"}
1515
requires-python = ">=3.11"
1616
dependencies = [
17-
"requests>=2.24.0"
17+
"requests>=2.24.0",
18+
"typing_extensions>=4.12.2"
1819
]
1920

2021
[tool.poetry.group.dev.dependencies]
@@ -23,10 +24,28 @@ ruff = "^0.9.6"
2324
python-dotenv = "^0.15.0"
2425

2526
[tool.ruff]
26-
line-length = 80
27+
line-length = 88
2728
indent-width = 4
2829
target-version = "py311"
2930

31+
[tool.ruff.lint]
32+
select = [
33+
# pycodestyle
34+
"E",
35+
# Pyflakes
36+
"F",
37+
# pyupgrade
38+
"UP",
39+
# flake8-bugbear
40+
"B",
41+
# flake8-simplify
42+
"SIM",
43+
# isort
44+
"I",
45+
# flake8-fixme
46+
"FIX"
47+
]
48+
3049
[build-system]
3150
requires = ["poetry-core"]
3251
build-backend = "poetry.core.masonry.api"

python_picnic_api2/client.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
from hashlib import md5
21
import re
2+
from hashlib import md5
3+
4+
import typing_extensions
35

46
from .helper import (
7+
_extract_search_results,
58
_tree_generator,
69
_url_generator,
7-
_extract_search_results,
810
)
911
from .session import PicnicAPISession, PicnicAuthError
1012

@@ -60,12 +62,13 @@ def _get(self, path: str, add_picnic_headers=False):
6062
return response
6163

6264
def _post(self, path: str, data=None, base_url_override=None):
63-
url = (self._base_url if not base_url_override else base_url_override) + path
65+
url = (base_url_override if base_url_override else self._base_url) + path
6466
response = self.session.post(url, json=data).json()
6567

6668
if self._contains_auth_error(response):
6769
raise PicnicAuthError(
68-
f"Picnic authentication error: {response['error'].get('message')}"
70+
f"Picnic authentication error: \
71+
{response['error'].get('message')}"
6972
)
7073

7174
return response
@@ -114,13 +117,9 @@ def get_article(self, article_id: str, add_category_name=False):
114117

115118
color_regex = re.compile(r"#\(#\d{6}\)")
116119
producer = re.sub(color_regex, "", str(article_details[1]["markdown"]))
117-
article_name = re.sub(color_regex, "", str(
118-
article_details[0]["markdown"]))
120+
article_name = re.sub(color_regex, "", str(article_details[0]["markdown"]))
119121

120-
article = {
121-
"name": f"{producer} {article_name}",
122-
"id": article_id
123-
}
122+
article = {"name": f"{producer} {article_name}", "id": article_id}
124123

125124
return article
126125

@@ -154,7 +153,14 @@ def get_delivery_position(self, delivery_id: str):
154153
path = "/deliveries/" + delivery_id + "/position"
155154
return self._get(path, add_picnic_headers=True)
156155

157-
def get_deliveries(self, summary: bool = True, data=None):
156+
@typing_extensions.deprecated(
157+
"""The option to show unsummarized deliveries was removed by picnic.
158+
The optional parameter 'summary' will be removed in the future and default
159+
to True.
160+
You can ignore this warning if you do not pass the 'summary' argument to
161+
this function."""
162+
)
163+
def get_deliveries(self, summary: bool = True, data: list = None):
158164
data = [] if data is None else data
159165
if not summary:
160166
raise NotImplementedError()

python_picnic_api2/helper.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import json
22
import re
3-
from typing import Optional
43

54
# prefix components:
65
space = " "
@@ -10,7 +9,9 @@
109
last = "└── "
1110

1211
IMAGE_SIZES = ["small", "medium", "regular", "large", "extra-large"]
13-
IMAGE_BASE_URL = "https://storefront-prod.nl.picnicinternational.com/static/images"
12+
IMAGE_BASE_URL = (
13+
"https://storefront-prod.nl.picnicinternational.com/static/images"
14+
)
1415

1516
SOLE_ARTICLE_ID_PATTERN = re.compile(r'"sole_article_id":"(\w+)"')
1617

@@ -22,13 +23,13 @@ def _tree_generator(response: list, prefix: str = ""):
2223
"""
2324
# response each get pointers that are ├── with a final └── :
2425
pointers = [tee] * (len(response) - 1) + [last]
25-
for pointer, item in zip(pointers, response):
26+
for pointer, item in zip(pointers, response, strict=False):
2627
if "name" in item: # print the item
2728
pre = ""
28-
if "unit_quantity" in item.keys():
29+
if "unit_quantity" in item:
2930
pre = f"{item['unit_quantity']} "
3031
after = ""
31-
if "display_price" in item.keys():
32+
if "display_price" in item:
3233
after = f" €{int(item['display_price']) / 100.0:.2f}"
3334

3435
yield prefix + pointer + pre + item["name"] + after
@@ -42,7 +43,7 @@ def _url_generator(url: str, country_code: str, api_version: str):
4243
return url.format(country_code.lower(), api_version)
4344

4445

45-
def _get_category_id_from_link(category_link: str) -> Optional[str]:
46+
def _get_category_id_from_link(category_link: str) -> str | None:
4647
pattern = r"categories/(\d+)"
4748
first_number = re.search(pattern, category_link)
4849
if first_number:
@@ -52,7 +53,7 @@ def _get_category_id_from_link(category_link: str) -> Optional[str]:
5253
return None
5354

5455

55-
def _get_category_name(category_link: str, categories: list) -> Optional[str]:
56+
def _get_category_name(category_link: str, categories: list) -> str | None:
5657
category_id = _get_category_id_from_link(category_link)
5758
if category_id:
5859
category = next(
@@ -84,16 +85,20 @@ def get_image(id: str, size="regular", suffix="webp"):
8485

8586

8687
def _extract_search_results(raw_results, max_items: int = 10):
87-
"""Extract search results from the nested dictionary structure returned by Picnic search.
88-
Number of max items can be defined to reduce excessive nested search"""
88+
"""Extract search results from the nested dictionary structure returned by
89+
Picnic search. Number of max items can be defined to reduce excessive nested
90+
search"""
8991
search_results = []
9092

9193
def find_articles(node):
9294
if len(search_results) >= max_items:
9395
return
9496

9597
content = node.get("content", {})
96-
if content.get("type") == "SELLING_UNIT_TILE" and "sellingUnit" in content:
98+
if (
99+
content.get("type") == "SELLING_UNIT_TILE"
100+
and "sellingUnit" in content
101+
):
97102
selling_unit = content["sellingUnit"]
98103
sole_article_ids = SOLE_ARTICLE_ID_PATTERN.findall(json.dumps(node))
99104
sole_article_id = sole_article_ids[0] if sole_article_ids else None

python_picnic_api2/session.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ def __init__(self, auth_token: str = None):
2222

2323
@property
2424
def authenticated(self):
25-
"""Returns whether the user is authenticated by checking if the authentication token is set."""
25+
"""Returns whether the user is authenticated by checking if the
26+
authentication token is set."""
2627
return bool(self._auth_token)
2728

2829
@property
@@ -38,14 +39,14 @@ def _update_auth_token(self, auth_token):
3839

3940
def get(self, url, **kwargs) -> Response:
4041
"""Do a GET request and update the auth token if set."""
41-
response = super(PicnicAPISession, self).get(url, **kwargs)
42+
response = super().get(url, **kwargs)
4243
self._update_auth_token(response.headers.get(self.AUTH_HEADER))
4344

4445
return response
4546

4647
def post(self, url, data=None, json=None, **kwargs) -> Response:
4748
"""Do a POST request and update the auth token if set."""
48-
response = super(PicnicAPISession, self).post(url, data, json, **kwargs)
49+
response = super().post(url, data, json, **kwargs)
4950
self._update_auth_token(response.headers.get(self.AUTH_HEADER))
5051

5152
return response

0 commit comments

Comments
 (0)
0