Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Enable bugbear lint rules in Ruff

Patryk Zawadzki29d03d36414d
diff --git a/pyproject.toml b/pyproject.toml
index a02c4336e3..46ca1b03c0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -185,10 +185,45 @@ exclude = [
[tool.ruff]
-lint.extend-select = ["D", "I", "ISC001", "ISC002", "PIE", "PT", "T20", "UP"]
-lint.ignore = ["D100", "D101", "D102", "D103", "D104", "D105", "D106", "D107", "D202", "D203", "D206", "D213", "D407", "PT019"]
target-version = "py39"
+ [tool.ruff.lint]
+ select = [
+ "ASYNC",
+ "B",
+ "D",
+ "E",
+ "F",
+ "I",
+ "ISC001",
+ "ISC002",
+ "PIE",
+ "PT",
+ "T20",
+ "UP",
+ "W"
+ ]
+ ignore = [
+ "B009", # Do not call getattr with a constant value
+ "B010", # Do not call setattr with a constant value
+ "B023", # Function definition does not bind loop variable
+ "D100", # Missing docstring in public module
+ "D101", # Missing docstring in public class
+ "D102", # Missing docstring in public method
+ "D103", # Missing docstring in public function
+ "D104", # Missing docstring in public package
+ "D105", # Missing docstring in magic method
+ "D106", # Missing docstring in public nested class
+ "D107", # Missing docstring in __init__
+ "D202", # No blank lines allowed after function docstring
+ "D203", # 1 blank line required before class docstring
+ "D206", # Docstring should be indented with spaces, not tabs
+ "D213", # Multi-line docstring summary should start at the second line
+ "D407", # Missing dashed underline after section
+ "E501", # Line too long
+ "PT019" # Fixture without value is injected as parameter, use @pytest.mark.usefixtures instead
+ ]
+
[tool.ruff.lint.flake8-pytest-style]
fixture-parentheses = false
mark-parentheses = false
diff --git a/saleor/account/i18n.py b/saleor/account/i18n.py
index 48f8fd241b..b1f9c14d85 100644
--- a/saleor/account/i18n.py
+++ b/saleor/account/i18n.py
@@ -313,6 +313,6 @@ COUNTRY_CHOICES = [
# Sort choices list by country name
COUNTRY_CHOICES = sorted(COUNTRY_CHOICES, key=lambda choice: str(choice[1]))
-for country, label in COUNTRY_CHOICES:
+for country, _label in COUNTRY_CHOICES:
country_rules = i18naddress.get_validation_rules({"country_code": country})
COUNTRY_FORMS[country] = construct_address_form(country, country_rules)
diff --git a/saleor/account/management/commands/createsuperuser.py b/saleor/account/management/commands/createsuperuser.py
index 2e0532b477..19794be69f 100644
--- a/saleor/account/management/commands/createsuperuser.py
+++ b/saleor/account/management/commands/createsuperuser.py
@@ -233,7 +233,7 @@ class Command(BaseCommand):
self.stderr.write("\nOperation cancelled.")
sys.exit(1)
except exceptions.ValidationError as e:
- raise CommandError("; ".join(e.messages))
+ raise CommandError("; ".join(e.messages)) from e
except NotRunningInTTYException:
self.stdout.write(
"Superuser creation skipped due to not running in a TTY. "
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index d81d6df5a7..c18bba8cee 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -44,14 +44,14 @@ class AppInstallationError(HTTPError):
def validate_app_install_response(response: Response):
try:
response.raise_for_status()
- except HTTPError as err:
+ except HTTPError as e:
try:
error_msg = str(response.json()["error"]["message"])
except Exception:
- raise err
+ raise e from None
raise AppInstallationError(
error_msg, request=response.request, response=response
- )
+ ) from e
def send_app_token(target_url: str, token: str):
@@ -111,9 +111,9 @@ def fetch_icon_image(
)
content.seek(0)
image_file = File(content, filename)
- except requests.RequestException:
+ except requests.RequestException as e:
code = AppErrorCode.MANIFEST_URL_CANT_CONNECT.value
- raise ValidationError("Unable to fetch image.", code=code)
+ raise ValidationError("Unable to fetch image.", code=code) from e
validate_icon_image(image_file, code)
return image_file
diff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.py
index 093fff4f81..e7b3b7fc9d 100644
--- a/saleor/app/management/commands/create_app.py
+++ b/saleor/app/management/commands/create_app.py
@@ -69,7 +69,7 @@ class Command(BaseCommand):
allow_redirects=False,
)
except RequestException as e:
- raise CommandError(f"Request failed. Exception: {e}")
+ raise CommandError(f"Request failed. Exception: {e}") from e
response.raise_for_status()
def handle(self, *args: Any, **options: Any) -> Optional[str]:
diff --git a/saleor/app/management/commands/install_app.py b/saleor/app/management/commands/install_app.py
index a1229ac525..559dccc9f4 100644
--- a/saleor/app/management/commands/install_app.py
+++ b/saleor/app/management/commands/install_app.py
@@ -28,8 +28,10 @@ class Command(BaseCommand):
url_validator = AppURLValidator()
try:
url_validator(manifest_url)
- except ValidationError:
- raise CommandError(f"Incorrect format of manifest-url: {manifest_url}")
+ except ValidationError as e:
+ raise CommandError(
+ f"Incorrect format of manifest-url: {manifest_url}"
+ ) from e
def handle(self, *args: Any, **options: Any) -> Optional[str]:
activate = options["activate"]
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index 8366ce0753..be0ea7c5ae 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -83,10 +83,10 @@ def clean_extension_url(extension: dict, manifest_data: dict):
def clean_manifest_url(manifest_url):
try:
_clean_app_url(manifest_url)
- except (ValidationError, AttributeError):
+ except (ValidationError, AttributeError) as e:
msg = "Enter a valid URL."
code = AppErrorCode.INVALID_URL_FORMAT.value
- raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
+ raise ValidationError({"manifest_url": ValidationError(msg, code=code)}) from e
def clean_permissions(
@@ -355,9 +355,9 @@ def clean_required_saleor_version(
return None
try:
spec = RequiredSaleorVersionSpec(required_version)
- except Exception:
+ except Exception as e:
msg = "Incorrect value for required Saleor version."
- raise ValidationError(msg, code=AppErrorCode.INVALID.value)
+ raise ValidationError(msg, code=AppErrorCode.INVALID.value) from e
version = parse_version(saleor_version)
satisfied = spec.match(version)
if raise_for_saleor_version and not satisfied:
diff --git a/saleor/app/validators.py b/saleor/app/validators.py
index d8b4253a09..3e7983a2ed 100644
--- a/saleor/app/validators.py
+++ b/saleor/app/validators.py
@@ -33,10 +33,10 @@ def brand_validator(brand):
return
try:
logo_url = brand["logo"]["default"]
- except (TypeError, KeyError):
+ except (TypeError, KeyError) as e:
raise ValidationError(
"Missing required field: logo.default.", code=AppErrorCode.REQUIRED.value
- )
+ ) from e
image_url_validator(logo_url)
filetype = mimetypes.guess_type(logo_url)[0]
if filetype not in ICON_MIME_TYPES:
diff --git a/saleor/asgi/__init__.py b/saleor/asgi/__init__.py
index 98eeb93327..8f9cee117a 100644
--- a/saleor/asgi/__init__.py
+++ b/saleor/asgi/__init__.py
@@ -23,7 +23,7 @@ def preload_app() -> None:
from django.conf import settings
from django.urls import get_resolver
- get_resolver(settings.ROOT_URLCONF).url_patterns
+ getattr(get_resolver(settings.ROOT_URLCONF), "url_patterns")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saleor.settings")
diff --git a/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py b/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
index 6f4c200d42..0dc441666b 100644
--- a/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
+++ b/saleor/attribute/migrations/0022_attribute_value_translations_propagate_names.py
@@ -80,7 +80,8 @@ def clean_text_data(text: str):
if url.scheme in BLACKLISTED_URL_SCHEMES:
warnings.warn(
f"An invalid url was sent: {original_url} "
- f"-- Scheme: {url.scheme} is blacklisted"
+ f"-- Scheme: {url.scheme} is blacklisted",
+ stacklevel=1,
)
new_url = "#invalid"
diff --git a/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py b/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
index 9424129446..34ef498903 100644
--- a/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
+++ b/saleor/attribute/migrations/0025_attribute_value_translations_propagate_names.py
@@ -80,7 +80,8 @@ def clean_text_data(text: str):
if url.scheme in BLACKLISTED_URL_SCHEMES:
warnings.warn(
f"An invalid url was sent: {original_url} "
- f"-- Scheme: {url.scheme} is blacklisted"
+ f"-- Scheme: {url.scheme} is blacklisted",
+ stacklevel=1,
)
new_url = "#invalid"
diff --git a/saleor/channel/utils.py b/saleor/channel/utils.py
index 1f214290d3..afc30f135e 100644
--- a/saleor/channel/utils.py
+++ b/saleor/channel/utils.py
@@ -32,16 +32,16 @@ def get_default_channel(allow_replica: bool = False) -> Channel:
try:
channel = Channel.objects.using(database_connection_name).get()
- except Channel.MultipleObjectsReturned:
+ except Channel.MultipleObjectsReturned as e:
channels = list(
Channel.objects.using(database_connection_name).filter(is_active=True)
)
if len(channels) == 1:
- warnings.warn(DEPRECATION_WARNING_MESSAGE)
+ warnings.warn(DEPRECATION_WARNING_MESSAGE, stacklevel=1)
return channels[0]
- raise ChannelNotDefined()
- except Channel.DoesNotExist:
- raise NoDefaultChannel()
+ raise ChannelNotDefined() from e
+ except Channel.DoesNotExist as e:
+ raise NoDefaultChannel() from e
else:
- warnings.warn(DEPRECATION_WARNING_MESSAGE)
+ warnings.warn(DEPRECATION_WARNING_MESSAGE, stacklevel=1)
return channel
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index d9116f8ef1..8f38deb7f2 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -180,8 +180,8 @@ def validate_checkout(
# can raise TaxError
try:
manager.preprocess_order_creation(checkout_info, lines)
- except TaxError as tax_error:
+ except TaxError as e:
raise ValidationError(
- f"Unable to calculate taxes - {str(tax_error)}",
+ f"Unable to calculate taxes - {str(e)}",
code=OrderCreateFromCheckoutErrorCode.TAX_ERROR.value,
- )
+ ) from e
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 798f000c42..81031e9c95 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -771,10 +771,10 @@ def _prepare_checkout(
if redirect_url:
try:
validate_storefront_url(redirect_url)
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
- {"redirect_url": error}, code=AccountErrorCode.INVALID.value
- )
+ {"redirect_url": e}, code=AccountErrorCode.INVALID.value
+ ) from e
to_update = []
if redirect_url and redirect_url != checkout.redirect_url:
@@ -824,11 +824,11 @@ def _prepare_checkout_with_transactions(
)
try:
manager.preprocess_order_creation(checkout_info, lines)
- except TaxError as tax_error:
+ except TaxError as e:
raise ValidationError(
- f"Unable to calculate taxes - {str(tax_error)}",
+ f"Unable to calculate taxes - {str(e)}",
code=CheckoutErrorCode.TAX_ERROR.value,
- )
+ ) from e
def _prepare_checkout_with_payment(
@@ -872,19 +872,19 @@ def _get_order_data(
)
except InsufficientStock as e:
error = prepare_insufficient_stock_checkout_validation_error(e)
- raise error
- except NotApplicable:
+ raise error from e
+ except NotApplicable as e:
raise ValidationError(
"Voucher not applicable",
code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
- )
+ ) from e
except GiftCardNotApplicable as e:
- raise ValidationError(e.message, code=e.code)
- except TaxError as tax_error:
+ raise ValidationError(e.message, code=e.code) from e
+ except TaxError as e:
raise ValidationError(
- f"Unable to calculate taxes - {str(tax_error)}",
+ f"Unable to calculate taxes - {str(e)}",
code=CheckoutErrorCode.TAX_ERROR.value,
- )
+ ) from e
return order_data
@@ -924,7 +924,7 @@ def _process_payment(
raise PaymentError(txn.error)
except PaymentError as e:
_complete_checkout_fail_handler(checkout_info, manager)
- raise ValidationError(str(e), code=CheckoutErrorCode.PAYMENT_ERROR.value)
+ raise ValidationError(str(e), code=CheckoutErrorCode.PAYMENT_ERROR.value) from e
return txn
@@ -1031,7 +1031,7 @@ def complete_checkout_post_payment_part(
payment=payment,
)
error = prepare_insufficient_stock_checkout_validation_error(e)
- raise error
+ raise error from e
except GiftCardNotApplicable as e:
_complete_checkout_fail_handler(
checkout_info,
@@ -1040,7 +1040,7 @@ def complete_checkout_post_payment_part(
voucher=checkout_info.voucher,
payment=payment,
)
- raise ValidationError(code=e.code, message=e.message)
+ raise ValidationError(code=e.code, message=e.message) from e
# if the order total value is 0 it is paid from the definition
if order.total.net.amount == 0:
@@ -1588,7 +1588,7 @@ def complete_checkout_with_transaction(
private_metadata_list=private_metadata_list,
is_automatic_completion=is_automatic_completion,
)
- except NotApplicable:
+ except NotApplicable as e:
raise ValidationError(
{
"voucher_code": ValidationError(
@@ -1596,12 +1596,12 @@ def complete_checkout_with_transaction(
code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
)
}
- )
+ ) from e
except InsufficientStock as e:
error = prepare_insufficient_stock_checkout_validation_error(e)
- raise error
+ raise error from e
except GiftCardNotApplicable as e:
- raise ValidationError({"gift_cards": e})
+ raise ValidationError({"gift_cards": e}) from e
def complete_checkout_with_payment(
diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.py
index 4b18e634d2..9b17170a11 100644
--- a/saleor/checkout/tasks.py
+++ b/saleor/checkout/tasks.py
@@ -95,7 +95,7 @@ def delete_expired_checkouts(
total_deleted: int = 0
has_more: bool = True
- for batch_number in range(batch_count):
+ for _batch_number in range(batch_count):
ids = list(qs.values_list("pk", flat=True))
with allow_writer():
deleted_count, _ = Checkout.objects.filter(pk__in=ids).delete()
diff --git a/saleor/checkout/tests/test_associate_checkout_with_account.py b/saleor/checkout/tests/test_associate_checkout_with_account.py
index a80a74e25f..ba546b6885 100644
--- a/saleor/checkout/tests/test_associate_checkout_with_account.py
+++ b/saleor/checkout/tests/test_associate_checkout_with_account.py
@@ -26,7 +26,6 @@ def test_associate_guest_checkout_with_account_if_exists(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- checkout_info.channel.order_mark_as_paid_strategy == paid_strategy
# call the complete_checkout function with the checkout object
order, _, _ = complete_checkout(
@@ -65,7 +64,6 @@ def test_associate_guest_checkout_with_account_if_exists_with_guest_user(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- checkout_info.channel.order_mark_as_paid_strategy == paid_strategy
# call the complete_checkout function with the checkout object
order, _, _ = complete_checkout(
@@ -104,7 +102,6 @@ def test_associate_guest_checkout_with_account_if_exists_with_inactive_user(
manager = get_plugins_manager(allow_replica=False)
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- checkout_info.channel.order_mark_as_paid_strategy == paid_strategy
# call the complete_checkout function with the checkout object
order, _, _ = complete_checkout(
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index d4ebd1bfec..beb24085f3 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -1077,7 +1077,7 @@ def test_fetch_order_data_plugin_tax_data_with_wrong_number_of_lines_no_shipping
checkout_info = fetch_checkout_info(checkout, checkout_lines_info, manager)
for line in checkout_lines_info:
- line.product_type
+ assert line.product_type
# when
fetch_checkout_data(checkout_info, manager, checkout_lines_info, force_update=True)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 4d42016df4..125cf6ceac 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -724,7 +724,7 @@ def add_voucher_code_to_checkout(
add_voucher_to_checkout(
manager, checkout_info, lines, code_instance.voucher, code_instance
)
- except NotApplicable:
+ except NotApplicable as e:
raise ValidationError(
{
"promo_code": ValidationError(
@@ -732,7 +732,7 @@ def add_voucher_code_to_checkout(
code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value,
)
}
- )
+ ) from e
def add_voucher_to_checkout(
diff --git a/saleor/core/apps.py b/saleor/core/apps.py
index 7dbf39ebe3..d77c5c3267 100644
--- a/saleor/core/apps.py
+++ b/saleor/core/apps.py
@@ -27,7 +27,7 @@ class CoreAppConfig(AppConfig):
try:
jwt_manager = import_string(jwt_manager_path)
except ImportError as e:
- raise ImportError(f"Failed to import JWT manager: {e}.")
+ raise ImportError(f"Failed to import JWT manager: {e}.") from e
validate_method: Optional[Callable[[], None]] = getattr(
jwt_manager, "validate_configuration", None
diff --git a/saleor/core/hashers.py b/saleor/core/hashers.py
index e95de8dc00..ebc71ebde2 100644
--- a/saleor/core/hashers.py
+++ b/saleor/core/hashers.py
@@ -18,7 +18,7 @@ class SHA512Base64PBKDF2PasswordHasher(PBKDF2PasswordHasher):
def encode(self, password, salt, iterations=None):
symfony_iterations = 5000
digest = hashlib.sha512(force_bytes(password, encoding="ISO-8859-1")).digest()
- for i in range(symfony_iterations - 1):
+ for _i in range(symfony_iterations - 1):
digest = hashlib.sha512(
digest + force_bytes(password, encoding="ISO-8859-1")
).digest()
diff --git a/saleor/core/jwt_manager.py b/saleor/core/jwt_manager.py
index bbb7b87c3a..3b3638b657 100644
--- a/saleor/core/jwt_manager.py
+++ b/saleor/core/jwt_manager.py
@@ -219,7 +219,9 @@ class JWTManager(JWTManagerBase):
try:
cls.get_private_key()
except Exception as e:
- raise ImproperlyConfigured(f"Unable to load provided PEM private key. {e}")
+ raise ImproperlyConfigured(
+ f"Unable to load provided PEM private key. {e}"
+ ) from e
@classmethod
def get_issuer(cls) -> str:
diff --git a/saleor/core/notify.py b/saleor/core/notify.py
index 099582c831..a1675d5e08 100644
--- a/saleor/core/notify.py
+++ b/saleor/core/notify.py
@@ -14,7 +14,7 @@ class NotifyHandler:
def __init__(self, payload_func):
self.generate_payload_func = payload_func
- @cache
+ @cache # noqa: B019
def payload(self):
return self.generate_payload_func()
diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.py
index 9120abd6f2..cdf7b4fd91 100644
--- a/saleor/core/tests/test_core.py
+++ b/saleor/core/tests/test_core.py
@@ -137,9 +137,9 @@ def test_create_fake_order(db, monkeypatch, image, media_root, warehouse):
pass
for _ in random_data.create_users("password", 3):
pass
- for msg in random_data.create_page_type():
+ for _ in random_data.create_page_type():
pass
- for msg in random_data.create_pages():
+ for _ in random_data.create_pages():
pass
random_data.create_products_by_schema("/", False)
how_many_orders = 2
diff --git a/saleor/core/utils/editorjs.py b/saleor/core/utils/editorjs.py
index 5eea977500..7ad8690e59 100644
--- a/saleor/core/utils/editorjs.py
+++ b/saleor/core/utils/editorjs.py
@@ -140,7 +140,8 @@ def clean_text_data_block(text: str) -> str:
if url_scheme in BLACKLISTED_URL_SCHEMES:
warnings.warn(
f"An invalid url was sent: {original_url} "
- f"-- Scheme: {url_scheme} is blacklisted"
+ f"-- Scheme: {url_scheme} is blacklisted",
+ stacklevel=1,
)
new_url = "#invalid"
diff --git a/saleor/core/utils/url.py b/saleor/core/utils/url.py
index 1eb556426e..7eade00ae2 100644
--- a/saleor/core/utils/url.py
+++ b/saleor/core/utils/url.py
@@ -21,8 +21,8 @@ def validate_storefront_url(url):
raise ValidationError(
"Invalid URL. Please check if URL is in RFC 1808 format."
)
- except ValueError as error:
- raise ValidationError(str(error))
+ except ValueError as e:
+ raise ValidationError(str(e)) from e
if not validate_host(domain, settings.ALLOWED_CLIENT_HOSTS):
error_message = (
f"{domain or url} is not allowed. Please check "
diff --git a/saleor/core/utils/validators.py b/saleor/core/utils/validators.py
index 5610477b79..599eb754bf 100644
--- a/saleor/core/utils/validators.py
+++ b/saleor/core/utils/validators.py
@@ -24,7 +24,7 @@ def get_oembed_data(url: str, field_name: str) -> tuple[dict[str, Any], str]:
url, maxwidth=MEDIA_MAX_WIDTH, maxheight=MEDIA_MAX_HEIGHT
)
return oembed_data, SUPPORTED_MEDIA_TYPES[oembed_data["type"]]
- except (micawber.exceptions.ProviderException, KeyError):
+ except (micawber.exceptions.ProviderException, KeyError) as e:
raise ValidationError(
{
field_name: ValidationError(
@@ -32,7 +32,7 @@ def get_oembed_data(url: str, field_name: str) -> tuple[dict[str, Any], str]:
code=ProductErrorCode.UNSUPPORTED_MEDIA_PROVIDER.value,
)
}
- )
+ ) from e
def is_date_in_future(given_date):
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index 9f8f3c7b33..6aa96bc8c3 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -48,8 +48,8 @@ def add_gift_card_code_to_checkout(
.filter(currency=currency)
.get(code=promo_code)
)
- except GiftCard.DoesNotExist:
- raise InvalidPromoCode()
+ except GiftCard.DoesNotExist as e:
+ raise InvalidPromoCode() from e
checkout.gift_cards.add(gift_card)
checkout.save(update_fields=["last_change"])
diff --git a/saleor/graphql/account/mutations/account/account_register.py b/saleor/graphql/account/mutations/account/account_register.py
index 5ccb0c361e..54793a72c6 100644
--- a/saleor/graphql/account/mutations/account/account_register.py
+++ b/saleor/graphql/account/mutations/account/account_register.py
@@ -120,14 +120,14 @@ class AccountRegister(ModelMutation):
try:
validate_storefront_url(data["redirect_url"])
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
{
"redirect_url": ValidationError(
- error.message, code=AccountErrorCode.INVALID.value
+ e.message, code=AccountErrorCode.INVALID.value
)
}
- )
+ ) from e
data["channel"] = clean_channel(
data.get("channel"), error_class=AccountErrorCode, allow_replica=False
@@ -138,8 +138,8 @@ class AccountRegister(ModelMutation):
password = data["password"]
try:
password_validation.validate_password(password, instance)
- except ValidationError as error:
- raise ValidationError({"password": error})
+ except ValidationError as e:
+ raise ValidationError({"password": e}) from e
data["language_code"] = data.get("language_code", settings.LANGUAGE_CODE)
return super().clean_input(info, instance, data, **kwargs)
diff --git a/saleor/graphql/account/mutations/account/account_request_deletion.py b/saleor/graphql/account/mutations/account/account_request_deletion.py
index c6f45b7af8..04f9e2acde 100644
--- a/saleor/graphql/account/mutations/account/account_request_deletion.py
+++ b/saleor/graphql/account/mutations/account/account_request_deletion.py
@@ -60,10 +60,10 @@ class AccountRequestDeletion(BaseMutation):
user = info.context.user
try:
validate_storefront_url(redirect_url)
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
- {"redirect_url": error}, code=AccountErrorCode.INVALID.value
- )
+ {"redirect_url": e}, code=AccountErrorCode.INVALID.value
+ ) from e
channel_slug = clean_channel(
channel, error_class=AccountErrorCode, allow_replica=False
).slug
diff --git a/saleor/graphql/account/mutations/account/confirm_account.py b/saleor/graphql/account/mutations/account/confirm_account.py
index 013a5f6983..3cbaad7ddf 100644
--- a/saleor/graphql/account/mutations/account/confirm_account.py
+++ b/saleor/graphql/account/mutations/account/confirm_account.py
@@ -49,7 +49,7 @@ class ConfirmAccount(BaseMutation):
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
try:
user = models.User.objects.get(email=data["email"])
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"email": ValidationError(
@@ -57,7 +57,7 @@ class ConfirmAccount(BaseMutation):
code=AccountErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
if not default_token_generator.check_token(user, data["token"]):
raise ValidationError(
diff --git a/saleor/graphql/account/mutations/account/confirm_email_change.py b/saleor/graphql/account/mutations/account/confirm_email_change.py
index 25f284b7c1..21eee99c65 100644
--- a/saleor/graphql/account/mutations/account/confirm_email_change.py
+++ b/saleor/graphql/account/mutations/account/confirm_email_change.py
@@ -60,7 +60,7 @@ class ConfirmEmailChange(BaseMutation):
def get_token_payload(cls, token):
try:
payload = jwt_decode(token)
- except jwt.PyJWTError:
+ except jwt.PyJWTError as e:
raise ValidationError(
{
"token": ValidationError(
@@ -68,7 +68,7 @@ class ConfirmEmailChange(BaseMutation):
code=AccountErrorCode.JWT_INVALID_TOKEN.value,
)
}
- )
+ ) from e
return payload
@classmethod
diff --git a/saleor/graphql/account/mutations/account/request_email_change.py b/saleor/graphql/account/mutations/account/request_email_change.py
index 22fd29c533..d84c5889a4 100644
--- a/saleor/graphql/account/mutations/account/request_email_change.py
+++ b/saleor/graphql/account/mutations/account/request_email_change.py
@@ -94,10 +94,10 @@ class RequestEmailChange(BaseMutation):
)
try:
validate_storefront_url(redirect_url)
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
- {"redirect_url": error}, code=AccountErrorCode.INVALID.value
- )
+ {"redirect_url": e}, code=AccountErrorCode.INVALID.value
+ ) from e
channel_slug = clean_channel(
channel, error_class=AccountErrorCode, allow_replica=False
).slug
diff --git a/saleor/graphql/account/mutations/account/send_confirmation_email.py b/saleor/graphql/account/mutations/account/send_confirmation_email.py
index 74434527bb..79bfb7530a 100644
--- a/saleor/graphql/account/mutations/account/send_confirmation_email.py
+++ b/saleor/graphql/account/mutations/account/send_confirmation_email.py
@@ -84,11 +84,11 @@ class SendConfirmationEmail(BaseMutation):
try:
validate_storefront_url(redirect_url)
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
- {"redirect_url": error},
+ {"redirect_url": e},
code=SendConfirmationEmailErrorCode.INVALID.value,
- )
+ ) from e
return user
diff --git a/saleor/graphql/account/mutations/authentication/password_change.py b/saleor/graphql/account/mutations/authentication/password_change.py
index a055e9f3e3..3778ef9ef1 100644
--- a/saleor/graphql/account/mutations/authentication/password_change.py
+++ b/saleor/graphql/account/mutations/authentication/password_change.py
@@ -62,8 +62,8 @@ class PasswordChange(BaseMutation):
cls.raise_invalid_credentials()
try:
password_validation.validate_password(new_password, user)
- except ValidationError as error:
- raise ValidationError({"new_password": error})
+ except ValidationError as e:
+ raise ValidationError({"new_password": e}) from e
user.set_password(new_password)
user.save(update_fields=["password", "updated_at"])
diff --git a/saleor/graphql/account/mutations/authentication/refresh_token.py b/saleor/graphql/account/mutations/authentication/refresh_token.py
index 9807e79fe0..2c3d4023fe 100644
--- a/saleor/graphql/account/mutations/authentication/refresh_token.py
+++ b/saleor/graphql/account/mutations/authentication/refresh_token.py
@@ -54,7 +54,7 @@ class RefreshToken(BaseMutation):
try:
payload = get_payload(refresh_token)
except ValidationError as e:
- raise ValidationError({"refreshToken": e})
+ raise ValidationError({"refreshToken": e}) from e
return payload
@classmethod
@@ -117,7 +117,7 @@ class RefreshToken(BaseMutation):
try:
user = get_user(payload)
except ValidationError as e:
- raise ValidationError({"refresh_token": e})
+ raise ValidationError({"refresh_token": e}) from e
return user
@classmethod
diff --git a/saleor/graphql/account/mutations/authentication/request_password_reset.py b/saleor/graphql/account/mutations/authentication/request_password_reset.py
index 9f8c9015fa..e039117cff 100644
--- a/saleor/graphql/account/mutations/authentication/request_password_reset.py
+++ b/saleor/graphql/account/mutations/authentication/request_password_reset.py
@@ -66,10 +66,10 @@ class RequestPasswordReset(BaseMutation):
def clean_user(cls, email, redirect_url, info: ResolveInfo):
try:
validate_storefront_url(redirect_url)
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
- {"redirect_url": error}, code=AccountErrorCode.INVALID.value
- )
+ {"redirect_url": e}, code=AccountErrorCode.INVALID.value
+ ) from e
user = retrieve_user_by_email(email)
if not user:
diff --git a/saleor/graphql/account/mutations/authentication/set_password.py b/saleor/graphql/account/mutations/authentication/set_password.py
index 73f55a7602..a6a0132dba 100644
--- a/saleor/graphql/account/mutations/authentication/set_password.py
+++ b/saleor/graphql/account/mutations/authentication/set_password.py
@@ -52,14 +52,14 @@ class SetPassword(CreateToken):
def _set_password_for_user(cls, email, password, token):
try:
user = models.User.objects.get(email=email)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"email": ValidationError(
"User doesn't exist", code=AccountErrorCode.NOT_FOUND.value
)
}
- )
+ ) from e
if not default_token_generator.check_token(user, token):
raise ValidationError(
{
@@ -70,8 +70,8 @@ class SetPassword(CreateToken):
)
try:
password_validation.validate_password(password, user)
- except ValidationError as error:
- raise ValidationError({"password": error})
+ except ValidationError as e:
+ raise ValidationError({"password": e}) from e
fields_to_save = ["password", "updated_at"]
user.set_password(password)
# To reset the password user need to process the token sent separately by email,
diff --git a/saleor/graphql/account/mutations/authentication/utils.py b/saleor/graphql/account/mutations/authentication/utils.py
index 05f7de5948..8e0dbd7f6e 100644
--- a/saleor/graphql/account/mutations/authentication/utils.py
+++ b/saleor/graphql/account/mutations/authentication/utils.py
@@ -35,18 +35,18 @@ def get_user(payload):
def get_payload(token):
try:
payload = jwt_decode(token)
- except jwt.ExpiredSignatureError:
+ except jwt.ExpiredSignatureError as e:
raise ValidationError(
"Signature has expired", code=AccountErrorCode.JWT_SIGNATURE_EXPIRED.value
- )
- except jwt.DecodeError:
+ ) from e
+ except jwt.DecodeError as e:
raise ValidationError(
"Error decoding signature", code=AccountErrorCode.JWT_DECODE_ERROR.value
- )
- except jwt.InvalidTokenError:
+ ) from e
+ except jwt.InvalidTokenError as e:
raise ValidationError(
"Invalid token", code=AccountErrorCode.JWT_INVALID_TOKEN.value
- )
+ ) from e
return payload
diff --git a/saleor/graphql/account/mutations/authentication/verify_token.py b/saleor/graphql/account/mutations/authentication/verify_token.py
index b6a4c68460..3a334085da 100644
--- a/saleor/graphql/account/mutations/authentication/verify_token.py
+++ b/saleor/graphql/account/mutations/authentication/verify_token.py
@@ -35,7 +35,7 @@ class VerifyToken(BaseMutation):
try:
payload = get_payload(token)
except ValidationError as e:
- raise ValidationError({"token": e})
+ raise ValidationError({"token": e}) from e
return payload
@classmethod
@@ -43,7 +43,7 @@ class VerifyToken(BaseMutation):
try:
user = get_user(payload)
except ValidationError as e:
- raise ValidationError({"token": e})
+ raise ValidationError({"token": e}) from e
return user
@classmethod
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 34f179b5b8..cb8545c187 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -294,10 +294,10 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):
if cleaned_input.get("redirect_url"):
try:
validate_storefront_url(cleaned_input.get("redirect_url"))
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
- {"redirect_url": error}, code=AccountErrorCode.INVALID.value
- )
+ {"redirect_url": e}, code=AccountErrorCode.INVALID.value
+ ) from e
email = cleaned_input.get("email")
if email:
diff --git a/saleor/graphql/account/tests/test_account_utils.py b/saleor/graphql/account/tests/test_account_utils.py
index 27b679f64a..00510f0257 100644
--- a/saleor/graphql/account/tests/test_account_utils.py
+++ b/saleor/graphql/account/tests/test_account_utils.py
@@ -41,7 +41,7 @@ def test_can_user_manage_group_is_true(
can_manage = can_user_manage_group(info, staff_user, permission_group_manage_users)
# then
- can_manage is True
+ assert can_manage is True
def test_can_user_manage_group_superuser(
@@ -53,7 +53,7 @@ def test_can_user_manage_group_superuser(
)
# then
- can_manage is True
+ assert can_manage is True
def test_can_user_manage_group_no_channel_access(
@@ -69,7 +69,7 @@ def test_can_user_manage_group_no_channel_access(
can_manage = can_user_manage_group(info, staff_user, permission_group_manage_apps)
# then
- can_manage is False
+ assert can_manage is False
def test_can_user_manage_group_no_permissions(
@@ -87,7 +87,7 @@ def test_can_user_manage_group_no_permissions(
)
# then
- can_manage is False
+ assert can_manage is False
def test_can_manage_group_user_without_permissions(
diff --git a/saleor/graphql/account/tests/utils.py b/saleor/graphql/account/tests/utils.py
index 17ba383be1..b18d230c14 100644
--- a/saleor/graphql/account/tests/utils.py
+++ b/saleor/graphql/account/tests/utils.py
@@ -8,7 +8,7 @@ def convert_dict_keys_to_camel_case(d):
into GraphQL input.
"""
data = {}
- for k, v in d.items():
+ for k in d.keys():
new_key = snake_to_camel_case(k)
data[new_key] = d[k]
return data
diff --git a/saleor/graphql/app/mutations/app_fetch_manifest.py b/saleor/graphql/app/mutations/app_fetch_manifest.py
index b19d3905a2..79974782bc 100644
--- a/saleor/graphql/app/mutations/app_fetch_manifest.py
+++ b/saleor/graphql/app/mutations/app_fetch_manifest.py
@@ -39,22 +39,30 @@ class AppFetchManifest(BaseMutation):
def fetch_manifest(cls, manifest_url):
try:
return fetch_manifest(manifest_url)
- except requests.Timeout:
+ except requests.Timeout as e:
msg = "The request to fetch manifest data timed out."
code = AppErrorCode.MANIFEST_URL_CANT_CONNECT.value
- raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
- except requests.HTTPError:
+ raise ValidationError(
+ {"manifest_url": ValidationError(msg, code=code)}
+ ) from e
+ except requests.HTTPError as e:
msg = "Unable to fetch manifest data."
code = AppErrorCode.MANIFEST_URL_CANT_CONNECT.value
- raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
- except ValueError:
+ raise ValidationError(
+ {"manifest_url": ValidationError(msg, code=code)}
+ ) from e
+ except ValueError as e:
msg = "Incorrect structure of manifest."
code = AppErrorCode.INVALID_MANIFEST_FORMAT.value
- raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
- except Exception:
+ raise ValidationError(
+ {"manifest_url": ValidationError(msg, code=code)}
+ ) from e
+ except OSError as e:
msg = "Can't fetch manifest data. Please try later."
code = AppErrorCode.INVALID.value
- raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
+ raise ValidationError(
+ {"manifest_url": ValidationError(msg, code=code)}
+ ) from e
@classmethod
def construct_instance(cls, instance, cleaned_data):
diff --git a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
index 309810fed7..94ee4c0ba7 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -271,7 +271,7 @@ def test_app_fetch_manifest_handle_exception(
staff_user, staff_api_client, permission_manage_apps, monkeypatch
):
mocked_get = Mock()
- mocked_get.side_effect = Exception()
+ mocked_get.side_effect = OSError("oops")
monkeypatch.setattr(HTTPSession, "request", mocked_get)
manifest_url = "http://localhost:3000/manifest-wrong-format"
diff --git a/saleor/graphql/attribute/mutations/attribute_reorder_values.py b/saleor/graphql/attribute/mutations/attribute_reorder_values.py
index c8b9f9dab0..f7313540ca 100644
--- a/saleor/graphql/attribute/mutations/attribute_reorder_values.py
+++ b/saleor/graphql/attribute/mutations/attribute_reorder_values.py
@@ -59,7 +59,7 @@ class AttributeReorderValues(BaseMutation):
try:
attribute = models.Attribute.objects.prefetch_related("values").get(pk=pk)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"attribute_id": ValidationError(
@@ -67,7 +67,7 @@ class AttributeReorderValues(BaseMutation):
code=AttributeErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
values_m2m = attribute.values.all()
operations = {}
@@ -80,7 +80,7 @@ class AttributeReorderValues(BaseMutation):
try:
m2m_info = values_m2m.get(pk=int(value_pk))
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"moves": ValidationError(
@@ -88,7 +88,7 @@ class AttributeReorderValues(BaseMutation):
code=AttributeErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
operations[m2m_info.pk] = move_info.sort_order
with traced_atomic_transaction():
diff --git a/saleor/graphql/attribute/mutations/base_reorder_attributes.py b/saleor/graphql/attribute/mutations/base_reorder_attributes.py
index e863ce84e7..65c7469a2d 100644
--- a/saleor/graphql/attribute/mutations/base_reorder_attributes.py
+++ b/saleor/graphql/attribute/mutations/base_reorder_attributes.py
@@ -87,9 +87,9 @@ class BaseReorderAttributeValuesMutation(BaseMutation):
try:
operations = cls.prepare_operations(moves, values_m2m)
- except ValidationError as error:
- error.code = error_code_enum.NOT_FOUND.value
- raise ValidationError({"moves": error})
+ except ValidationError as e:
+ e.code = error_code_enum.NOT_FOUND.value
+ raise ValidationError({"moves": e}) from e
with traced_atomic_transaction():
perform_reordering(values_m2m, operations)
@@ -112,7 +112,7 @@ class BaseReorderAttributeValuesMutation(BaseMutation):
attribute_assignment = instance.attributes.prefetch_related("values").get(
assignment__attribute_id=attribute_pk
)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"attribute_id": ValidationError(
@@ -121,7 +121,7 @@ class BaseReorderAttributeValuesMutation(BaseMutation):
code=error_code_enum.NOT_FOUND.value,
)
}
- )
+ ) from e
return attribute_assignment
@classmethod
diff --git a/saleor/graphql/attribute/mutations/mixins.py b/saleor/graphql/attribute/mutations/mixins.py
index e2acfbacd4..693d4839ee 100644
--- a/saleor/graphql/attribute/mutations/mixins.py
+++ b/saleor/graphql/attribute/mutations/mixins.py
@@ -86,15 +86,15 @@ class AttributeMixin:
attribute_value = models.AttributeValue(**value_data, attribute=attribute)
try:
attribute_value.full_clean()
- except ValidationError as validation_errors:
- for field, err in validation_errors.error_dict.items():
+ except ValidationError as e:
+ for field, err in e.error_dict.items():
if field == "attribute":
continue
errors = []
for error in err:
error.code = AttributeErrorCode.INVALID.value
errors.append(error)
- raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: errors})
+ raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: errors}) from e
@classmethod
def validate_non_swatch_attr_value(cls, value_data: dict):
@@ -159,9 +159,9 @@ class AttributeMixin:
cleaned_input = validate_slug_and_generate_if_needed(
instance, "name", cleaned_input
)
- except ValidationError as error:
- error.code = AttributeErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
+ except ValidationError as e:
+ e.code = AttributeErrorCode.REQUIRED.value
+ raise ValidationError({"slug": e}) from e
cls._clean_attribute_settings(instance, cleaned_input)
return cleaned_input
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py b/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py
index e93ad250ec..cc275e27dd 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py
@@ -141,7 +141,7 @@ def test_sort_values_within_attribute(
actual_order = []
- for attr, expected_pk in zip(gql_values, expected_order):
+ for attr, _expected_pk in zip(gql_values, expected_order):
gql_type, gql_attr_id = graphene.Node.from_global_id(attr["node"]["id"])
assert gql_type == "AttributeValue"
actual_order.append(int(gql_attr_id))
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index db7b06ae24..2229103cad 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -164,7 +164,7 @@ class AttributeAssignmentMixin:
global_id, only_type="Attribute"
)
except GraphQLError as e:
- raise ValidationError(str(e), code=error_class.GRAPHQL_ERROR.value)
+ raise ValidationError(str(e), code=error_class.GRAPHQL_ERROR.value) from e
if not internal_id.isnumeric():
raise ValidationError(
f"An invalid ID value was passed: {global_id}",
@@ -249,11 +249,11 @@ class AttributeAssignmentMixin:
external_reference,
use_camel_case=True,
)
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
- error.message,
+ e.message,
code=error_class.REQUIRED.value,
- )
+ ) from e
values = AttrValuesInput(
global_id=global_id,
@@ -346,10 +346,10 @@ class AttributeAssignmentMixin:
)
values.references = ref_instances
return values
- except GraphQLError:
+ except GraphQLError as e:
raise ValidationError(
"Invalid reference type.", code=error_class.INVALID.value
- )
+ ) from e
@classmethod
def _validate_attributes_input(
diff --git a/saleor/graphql/channel/utils.py b/saleor/graphql/channel/utils.py
index 705700cbe0..43cbe0bf46 100644
--- a/saleor/graphql/channel/utils.py
+++ b/saleor/graphql/channel/utils.py
@@ -31,7 +31,7 @@ def get_default_channel_or_graphql_error(allow_replica: bool = False) -> Channel
try:
channel = get_default_channel(allow_replica)
except (ChannelNotDefined, NoDefaultChannel) as e:
- raise GraphQLError(str(e))
+ raise GraphQLError(str(e)) from e
else:
return channel
@@ -39,7 +39,7 @@ def get_default_channel_or_graphql_error(allow_replica: bool = False) -> Channel
def validate_channel(channel_slug, error_class):
try:
channel = Channel.objects.get(slug=channel_slug)
- except Channel.DoesNotExist:
+ except Channel.DoesNotExist as e:
raise ValidationError(
{
"channel": ValidationError(
@@ -47,7 +47,7 @@ def validate_channel(channel_slug, error_class):
code=error_class.NOT_FOUND.value,
)
}
- )
+ ) from e
if not channel.is_active:
raise ValidationError(
{
@@ -70,7 +70,7 @@ def clean_channel(
else:
try:
channel = get_default_channel(allow_replica)
- except ChannelNotDefined:
+ except ChannelNotDefined as e:
raise ValidationError(
{
"channel": ValidationError(
@@ -78,7 +78,7 @@ def clean_channel(
code=error_class.MISSING_CHANNEL_SLUG.value,
)
}
- )
+ ) from e
return channel
diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.py
index 4c9c7fef9b..785d6f2280 100644
--- a/saleor/graphql/checkout/mutations/checkout_complete.py
+++ b/saleor/graphql/checkout/mutations/checkout_complete.py
@@ -267,7 +267,7 @@ class CheckoutComplete(BaseMutation, I18nMixin):
code=CheckoutErrorCode.CHANNEL_INACTIVE.value,
)
}
- )
+ ) from e
# The order is already created. We return it as a success
# checkoutComplete response. Order is anonymized for not logged in
# user
diff --git a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
index d55f013361..4a8702b7d6 100644
--- a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
@@ -93,8 +93,8 @@ class CheckoutRemovePromoCode(BaseMutation):
if promo_code:
try:
remove_promo_code_from_checkout_or_error(checkout_info, promo_code)
- except ValidationError as error:
- raise ValidationError({"promo_code": error})
+ except ValidationError as e:
+ raise ValidationError({"promo_code": e}) from e
else:
object_type, promo_code_pk = cls.clean_promo_code_id(promo_code_id)
cls.remove_promo_code_by_id_or_error(
@@ -133,7 +133,7 @@ class CheckoutRemovePromoCode(BaseMutation):
str(e), code=CheckoutErrorCode.GRAPHQL_ERROR.value
)
}
- )
+ ) from e
if object_type not in (str(Voucher), str(GiftCard)):
raise ValidationError(
diff --git a/saleor/graphql/checkout/mutations/order_create_from_checkout.py b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
index 5965c6ef4c..4e2e7921d3 100644
--- a/saleor/graphql/checkout/mutations/order_create_from_checkout.py
+++ b/saleor/graphql/checkout/mutations/order_create_from_checkout.py
@@ -197,7 +197,7 @@ class OrderCreateFromCheckout(BaseMutation):
metadata_list=metadata,
private_metadata_list=private_metadata,
)
- except NotApplicable:
+ except NotApplicable as e:
code = OrderCreateFromCheckoutErrorCode.VOUCHER_NOT_APPLICABLE.value
raise ValidationError(
{
@@ -206,11 +206,11 @@ class OrderCreateFromCheckout(BaseMutation):
code=code,
)
}
- )
+ ) from e
except InsufficientStock as e:
error = prepare_insufficient_stock_checkout_validation_error(e)
- raise error
+ raise error from e
except GiftCardNotApplicable as e:
- raise ValidationError({"gift_cards": e})
+ raise ValidationError({"gift_cards": e}) from e
return OrderCreateFromCheckout(order=order)
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index 0edb9b1ea2..3511bb9ec5 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -220,7 +220,7 @@ def check_lines_quantity(
)
for item in e.items
]
- raise ValidationError({"quantity": errors})
+ raise ValidationError({"quantity": errors}) from e
def get_not_available_variants_for_purchase(
@@ -310,7 +310,7 @@ def get_checkout_by_token(
)
try:
checkout = qs.get(token=token)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"token": ValidationError(
@@ -318,7 +318,7 @@ def get_checkout_by_token(
code=CheckoutErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
return checkout
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index f548fd08cd..d096224825 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -2061,7 +2061,7 @@ def test_order_from_draft_create_with_preorder_variant(
assert order.lines.count() == len(variants_and_quantities)
for variant_id, quantity in variants_and_quantities.items():
- order.lines.get(variant_id=variant_id).quantity == quantity
+ assert order.lines.get(variant_id=variant_id).quantity == quantity
assert order.shipping_address == address
assert order.shipping_method == checkout.shipping_method
diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.py
index f7185c42bd..788f04beea 100644
--- a/saleor/graphql/core/connection.py
+++ b/saleor/graphql/core/connection.py
@@ -73,8 +73,8 @@ def _prepare_filter_by_rank_expression(
try:
rank = Decimal(cursor[0])
id = coerce_id(cursor[1])
- except (InvalidOperation, ValueError, TypeError):
- raise GraphQLError("Received cursor is invalid.")
+ except (InvalidOperation, ValueError, TypeError) as e:
+ raise GraphQLError("Received cursor is invalid.") from e
# Because rank is float number, it gets mangled by PostgreSQL's query parser
# making equal comparisons impossible. Instead we compare rank against small
@@ -270,8 +270,8 @@ def connection_from_queryset_slice(
cursor = after or before
try:
cursor = from_global_cursor(cursor) if cursor else None
- except ValueError:
- raise GraphQLError("Received cursor is invalid.")
+ except ValueError as e:
+ raise GraphQLError("Received cursor is invalid.") from e
sort_by = args.get("sort_by", {})
sorting_fields = _get_sorting_fields(sort_by, qs)
@@ -290,8 +290,8 @@ def connection_from_queryset_slice(
)
try:
filtered_qs = qs.filter(filter_kwargs)
- except ValueError:
- raise GraphQLError("Received cursor is invalid.")
+ except ValueError as e:
+ raise GraphQLError("Received cursor is invalid.") from e
filtered_qs = filtered_qs[:end_margin]
edges, page_info = _get_edges_for_connection(
edge_type, filtered_qs, args, sorting_fields
diff --git a/saleor/graphql/core/filters.py b/saleor/graphql/core/filters.py
index b84af61bb3..a2b0e70049 100644
--- a/saleor/graphql/core/filters.py
+++ b/saleor/graphql/core/filters.py
@@ -136,14 +136,14 @@ class GlobalIDFormField(Field):
try:
_type, _id = from_global_id(value)
- except (TypeError, ValueError):
- raise ValidationError(self.error_messages["invalid"])
+ except (TypeError, ValueError) as e:
+ raise ValidationError(self.error_messages["invalid"]) from e
try:
CharField().clean(_id)
CharField().clean(_type)
- except ValidationError:
- raise ValidationError(self.error_messages["invalid"])
+ except ValidationError as e:
+ raise ValidationError(self.error_messages["invalid"]) from e
return value
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 8ddbce4de0..bab2647ad7 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -265,7 +265,7 @@ class BaseMutation(graphene.Mutation):
except GraphQLError as e:
raise ValidationError(
{field: ValidationError(str(e), code="graphql_error")}
- )
+ ) from e
return pk
@overload
@@ -364,7 +364,7 @@ class BaseMutation(graphene.Mutation):
except (AssertionError, GraphQLError) as e:
raise ValidationError(
{field: ValidationError(str(e), code="graphql_error")}
- )
+ ) from e
else:
if node is None:
raise ValidationError(
@@ -390,7 +390,7 @@ class BaseMutation(graphene.Mutation):
except GraphQLError as e:
raise ValidationError(
{field: ValidationError(str(e), code="graphql_error")}
- )
+ ) from e
return pks
@overload
@@ -412,7 +412,7 @@ class BaseMutation(graphene.Mutation):
except GraphQLError as e:
raise ValidationError(
{field: ValidationError(str(e), code="graphql_error")}
- )
+ ) from e
return instances
@staticmethod
diff --git a/saleor/graphql/core/tests/test_validators.py b/saleor/graphql/core/tests/test_validators.py
index 6a05bf2cd3..466d5e8974 100644
--- a/saleor/graphql/core/tests/test_validators.py
+++ b/saleor/graphql/core/tests/test_validators.py
@@ -99,7 +99,7 @@ def test_validate_one_of_args_is_in_query_single_arg():
def test_validate_one_of_args_is_in_query_single_arg_absent():
with pytest.raises(GraphQLError) as error:
- validate_one_of_args_is_in_query("arg1", None) is None
+ assert validate_one_of_args_is_in_query("arg1", None) is None
assert error.value.message == "At least one of arguments is required: 'arg1'."
diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.py
index 131429e103..83779fcc82 100644
--- a/saleor/graphql/core/utils/__init__.py
+++ b/saleor/graphql/core/utils/__init__.py
@@ -82,10 +82,12 @@ def from_global_id_or_error(
id_ = global_id
else:
validate_if_int_or_uuid(id_)
- except (binascii.Error, UnicodeDecodeError, ValueError, ValidationError):
+ except (binascii.Error, UnicodeDecodeError, ValueError, ValidationError) as e:
if only_type:
- raise GraphQLError(f"Invalid ID: {global_id}. Expected: {only_type}.")
- raise GraphQLError(f"Invalid ID: {global_id}.")
+ raise GraphQLError(
+ f"Invalid ID: {global_id}. Expected: {only_type}."
+ ) from e
+ raise GraphQLError(f"Invalid ID: {global_id}.") from e
if only_type and str(type_) != str(only_type):
if not raise_error:
diff --git a/saleor/graphql/core/validators/__init__.py b/saleor/graphql/core/validators/__init__.py
index a1bb991459..af7602147f 100644
--- a/saleor/graphql/core/validators/__init__.py
+++ b/saleor/graphql/core/validators/__init__.py
@@ -21,7 +21,7 @@ def validate_one_of_args_is_in_mutation(*args, **kwargs):
try:
validate_one_of_args_is_in_query(*args, **kwargs)
except GraphQLError as e:
- raise ValidationError(str(e), code="graphql_error")
+ raise ValidationError(str(e), code="graphql_error") from e
def validate_one_of_args_is_in_query(*args, **kwargs):
@@ -213,5 +213,5 @@ def validate_if_int_or_uuid(id):
except ValueError:
try:
UUID(id)
- except (AttributeError, ValueError):
- raise ValidationError("Must receive an int or UUID.")
+ except (AttributeError, ValueError) as e:
+ raise ValidationError("Must receive an int or UUID.") from e
diff --git a/saleor/graphql/core/validators/file.py b/saleor/graphql/core/validators/file.py
index 8c1ae6d896..de3f77d66b 100644
--- a/saleor/graphql/core/validators/file.py
+++ b/saleor/graphql/core/validators/file.py
@@ -87,7 +87,7 @@ def clean_image_file(cleaned_input, img_field_name, error_class):
code=error_class.INVALID.value,
)
}
- )
+ ) from e
try:
# validate if the image MIME type is supported
@@ -95,7 +95,7 @@ def clean_image_file(cleaned_input, img_field_name, error_class):
except ValueError as e:
raise ValidationError(
{img_field_name: ValidationError(str(e), code=error_class.INVALID.value)}
- )
+ ) from e
add_hash_to_file_name(img_file)
return img_file
@@ -145,4 +145,4 @@ def _validate_image_exif(img, field_name, error_class):
code=error_class.INVALID.value,
)
}
- )
+ ) from e
diff --git a/saleor/graphql/discount/mutations/promotion/promotion_update.py b/saleor/graphql/discount/mutations/promotion/promotion_update.py
index 592d2d2f4c..5d26bdc7f9 100644
--- a/saleor/graphql/discount/mutations/promotion/promotion_update.py
+++ b/saleor/graphql/discount/mutations/promotion/promotion_update.py
@@ -92,9 +92,9 @@ class PromotionUpdate(ModelMutation):
end_date = cleaned_input.get("end_date") or instance.end_date
try:
validate_end_is_after_start(start_date, end_date)
- except ValidationError as error:
- error.code = PromotionUpdateErrorCode.INVALID.value
- raise ValidationError({"endDate": error})
+ except ValidationError as e:
+ e.code = PromotionUpdateErrorCode.INVALID.value
+ raise ValidationError({"endDate": e}) from e
return cleaned_input
@classmethod
diff --git a/saleor/graphql/discount/mutations/promotion/validators.py b/saleor/graphql/discount/mutations/promotion/validators.py
index 4649bb8a95..e0f576e1e2 100644
--- a/saleor/graphql/discount/mutations/promotion/validators.py
+++ b/saleor/graphql/discount/mutations/promotion/validators.py
@@ -541,12 +541,12 @@ def clean_fixed_discount_value(
):
try:
validate_price_precision(reward_value, currency_code)
- except ValidationError:
+ except ValidationError as e:
raise ValidationError(
"Invalid amount precision.",
code=error_code,
params={"index": index} if index is not None else {},
- )
+ ) from e
def clean_percentage_discount_value(
diff --git a/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py b/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
index 504de252d2..949c1f4f5c 100644
--- a/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
+++ b/saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
@@ -112,7 +112,7 @@ class SaleChannelListingUpdate(BaseChannelListingMutation):
old_listing_ids = PromotionRule.get_old_channel_listing_ids(
len(rules_to_create)
)
- for idx, (channel, rule) in enumerate(rules_to_create):
+ for idx, (_channel, rule) in enumerate(rules_to_create):
rule.old_channel_listing_id = old_listing_ids[idx][0]
cls.save_promotion_rules(rules_to_create, rules_to_update)
diff --git a/saleor/graphql/discount/mutations/sale/sale_create.py b/saleor/graphql/discount/mutations/sale/sale_create.py
index 2487bf736b..249f194eb8 100644
--- a/saleor/graphql/discount/mutations/sale/sale_create.py
+++ b/saleor/graphql/discount/mutations/sale/sale_create.py
@@ -106,9 +106,9 @@ class SaleCreate(ModelMutation):
end_date = instance.end_date
try:
validate_end_is_after_start(start_date, end_date)
- except ValidationError as error:
- error.code = DiscountErrorCode.INVALID.value
- raise ValidationError({"end_date": error})
+ except ValidationError as e:
+ e.code = DiscountErrorCode.INVALID.value
+ raise ValidationError({"end_date": e}) from e
@classmethod
def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
diff --git a/saleor/graphql/discount/mutations/sale/sale_update.py b/saleor/graphql/discount/mutations/sale/sale_update.py
index 68c147ef77..7a1ec2ba3d 100644
--- a/saleor/graphql/discount/mutations/sale/sale_update.py
+++ b/saleor/graphql/discount/mutations/sale/sale_update.py
@@ -126,9 +126,9 @@ class SaleUpdate(ModelMutation):
end_date = input.get("end_date") or instance.end_date
try:
validate_end_is_after_start(start_date, end_date)
- except ValidationError as error:
- error.code = DiscountErrorCode.INVALID.value
- raise ValidationError({"end_date": error})
+ except ValidationError as e:
+ e.code = DiscountErrorCode.INVALID.value
+ raise ValidationError({"end_date": e}) from e
@classmethod
def update_fields(
diff --git a/saleor/graphql/discount/mutations/voucher/voucher_code_bulk_delete.py b/saleor/graphql/discount/mutations/voucher/voucher_code_bulk_delete.py
index dc76c1589a..238e14aa95 100644
--- a/saleor/graphql/discount/mutations/voucher/voucher_code_bulk_delete.py
+++ b/saleor/graphql/discount/mutations/voucher/voucher_code_bulk_delete.py
@@ -45,7 +45,7 @@ class VoucherCodeBulkDelete(BaseMutation):
invalid_codes_ids = []
cleaned_ids = set()
- for index, code in enumerate(codes):
+ for code in codes:
obj_type, code_pk = graphene.Node.from_global_id(code)
if obj_type != "VoucherCode":
invalid_codes_ids.append(code)
diff --git a/saleor/graphql/discount/mutations/voucher/voucher_create.py b/saleor/graphql/discount/mutations/voucher/voucher_create.py
index 58f8a734d7..29cba2983b 100644
--- a/saleor/graphql/discount/mutations/voucher/voucher_create.py
+++ b/saleor/graphql/discount/mutations/voucher/voucher_create.py
@@ -238,9 +238,9 @@ class VoucherCreate(ModelMutation):
try:
validate_end_is_after_start(start_date, end_date)
- except ValidationError as error:
- error.code = DiscountErrorCode.INVALID.value
- raise ValidationError({"end_date": error})
+ except ValidationError as e:
+ e.code = DiscountErrorCode.INVALID.value
+ raise ValidationError({"end_date": e}) from e
@classmethod
def clean_codes_instance(cls, code_instances):
diff --git a/saleor/graphql/giftcard/bulk_mutations/gift_card_bulk_create.py b/saleor/graphql/giftcard/bulk_mutations/gift_card_bulk_create.py
index 69b472f039..17ae290b6d 100644
--- a/saleor/graphql/giftcard/bulk_mutations/gift_card_bulk_create.py
+++ b/saleor/graphql/giftcard/bulk_mutations/gift_card_bulk_create.py
@@ -129,9 +129,9 @@ class GiftCardBulkCreate(BaseMutation):
currency = balance["currency"]
try:
validate_price_precision(amount, currency)
- except ValidationError as error:
- error.code = GiftCardErrorCode.INVALID.value
- raise ValidationError({"balance": error})
+ except ValidationError as e:
+ e.code = GiftCardErrorCode.INVALID.value
+ raise ValidationError({"balance": e}) from e
if not amount > 0:
raise ValidationError(
{
diff --git a/saleor/graphql/giftcard/mutations/gift_card_add_note.py b/saleor/graphql/giftcard/mutations/gift_card_add_note.py
index 1c352b630c..abe9f5394f 100644
--- a/saleor/graphql/giftcard/mutations/gift_card_add_note.py
+++ b/saleor/graphql/giftcard/mutations/gift_card_add_note.py
@@ -53,7 +53,7 @@ class GiftCardAddNote(BaseMutation):
def clean_input(cls, _info: ResolveInfo, _instance, data):
try:
cleaned_input = validate_required_string_field(data, "message")
- except ValidationError:
+ except ValidationError as e:
raise ValidationError(
{
"message": ValidationError(
@@ -61,7 +61,7 @@ class GiftCardAddNote(BaseMutation):
code=GiftCardErrorCode.REQUIRED.value,
)
}
- )
+ ) from e
return cleaned_input
@classmethod
diff --git a/saleor/graphql/giftcard/mutations/gift_card_create.py b/saleor/graphql/giftcard/mutations/gift_card_create.py
index 47ae6e09a5..1e8cc4fcda 100644
--- a/saleor/graphql/giftcard/mutations/gift_card_create.py
+++ b/saleor/graphql/giftcard/mutations/gift_card_create.py
@@ -132,7 +132,7 @@ class GiftCardCreate(ModelMutation):
if email := data.get("user_email"):
try:
validate_email(email)
- except ValidationError:
+ except ValidationError as e:
raise ValidationError(
{
"email": ValidationError(
@@ -140,7 +140,7 @@ class GiftCardCreate(ModelMutation):
code=GiftCardErrorCode.INVALID.value,
)
}
- )
+ ) from e
if not data.get("channel"):
raise ValidationError(
{
@@ -184,9 +184,9 @@ class GiftCardCreate(ModelMutation):
currency = balance["currency"]
try:
validate_price_precision(amount, currency)
- except ValidationError as error:
- error.code = GiftCardErrorCode.INVALID.value
- raise ValidationError({"balance": error})
+ except ValidationError as e:
+ e.code = GiftCardErrorCode.INVALID.value
+ raise ValidationError({"balance": e}) from e
if instance.pk:
if currency != instance.currency:
raise ValidationError(
diff --git a/saleor/graphql/giftcard/mutations/gift_card_resend.py b/saleor/graphql/giftcard/mutations/gift_card_resend.py
index 94f4ba194a..234838112e 100644
--- a/saleor/graphql/giftcard/mutations/gift_card_resend.py
+++ b/saleor/graphql/giftcard/mutations/gift_card_resend.py
@@ -58,7 +58,7 @@ class GiftCardResend(BaseMutation):
if email := data.get("email"):
try:
validate_email(email)
- except ValidationError:
+ except ValidationError as e:
raise ValidationError(
{
"email": ValidationError(
@@ -66,7 +66,7 @@ class GiftCardResend(BaseMutation):
code=GiftCardErrorCode.INVALID.value,
)
}
- )
+ ) from e
return data
diff --git a/saleor/graphql/giftcard/mutations/gift_card_update.py b/saleor/graphql/giftcard/mutations/gift_card_update.py
index 2929e8fe1b..92512f1440 100644
--- a/saleor/graphql/giftcard/mutations/gift_card_update.py
+++ b/saleor/graphql/giftcard/mutations/gift_card_update.py
@@ -74,9 +74,9 @@ class GiftCardUpdate(GiftCardCreate):
currency = instance.currency
try:
validate_price_precision(amount, currency)
- except ValidationError as error:
- error.code = GiftCardErrorCode.INVALID.value
- raise ValidationError({"balance_amount": error})
+ except ValidationError as e:
+ e.code = GiftCardErrorCode.INVALID.value
+ raise ValidationError({"balance_amount": e}) from e
cleaned_input["current_balance_amount"] = amount
cleaned_input["initial_balance_amount"] = amount
diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card.py b/saleor/graphql/giftcard/tests/queries/test_gift_card.py
index 70d75f6db0..68a9c7800a 100644
--- a/saleor/graphql/giftcard/tests/queries/test_gift_card.py
+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card.py
@@ -527,7 +527,7 @@ def test_query_gift_card_event_with_removed_app(
permission_manage_users,
):
# given
- staff_api_client.user
+ assert staff_api_client.user
GiftCardEvent.objects.create(
app=removed_app,
diff --git a/saleor/graphql/menu/mutations/menu_create.py b/saleor/graphql/menu/mutations/menu_create.py
index cd362e43a9..0f92507e7e 100644
--- a/saleor/graphql/menu/mutations/menu_create.py
+++ b/saleor/graphql/menu/mutations/menu_create.py
@@ -54,9 +54,9 @@ class MenuCreate(ModelMutation):
cleaned_input = validate_slug_and_generate_if_needed(
instance, "name", cleaned_input
)
- except ValidationError as error:
- error.code = MenuErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
+ except ValidationError as e:
+ e.code = MenuErrorCode.REQUIRED.value
+ raise ValidationError({"slug": e}) from e
items = []
for item in cleaned_input.get("items", []):
diff --git a/saleor/graphql/meta/mutations/base.py b/saleor/graphql/meta/mutations/base.py
index 830837063b..47a6242e1a 100644
--- a/saleor/graphql/meta/mutations/base.py
+++ b/saleor/graphql/meta/mutations/base.py
@@ -37,10 +37,12 @@ class BaseMetadataMutation(BaseMutation):
def __init_subclass_with_meta__(
cls,
arguments=None,
- permission_map=[],
+ permission_map=None,
_meta=None,
**kwargs,
):
+ if permission_map is None:
+ permission_map = []
if not _meta:
_meta = MetadataPermissionOptions(cls)
if not arguments:
@@ -73,7 +75,7 @@ class BaseMetadataMutation(BaseMutation):
str(e), code=MetadataErrorCode.GRAPHQL_ERROR.value
)
}
- )
+ ) from e
@classmethod
def get_instance_by_token(cls, object_id, qs):
@@ -230,7 +232,7 @@ class BaseMetadataMutation(BaseMutation):
return None, None
try:
return from_global_id_or_error(object_id)
- except GraphQLError:
+ except GraphQLError as e:
if order := order_models.Order.objects.filter(id=object_id).first():
return "Order", order.pk
if checkout := checkout_models.Checkout.objects.filter(
@@ -243,7 +245,7 @@ class BaseMetadataMutation(BaseMutation):
"Couldn't resolve to a node.", code="graphql_error"
)
}
- )
+ ) from e
@classmethod
def perform_model_extra_actions(cls, root, info: ResolveInfo, type_name, **data):
diff --git a/saleor/graphql/meta/mutations/utils.py b/saleor/graphql/meta/mutations/utils.py
index 8c70697aa7..3855d168f4 100644
--- a/saleor/graphql/meta/mutations/utils.py
+++ b/saleor/graphql/meta/mutations/utils.py
@@ -27,8 +27,8 @@ def save_instance(instance, metadata_fields: list):
try:
instance.save(update_fields=metadata_fields)
- except DatabaseError:
+ except DatabaseError as e:
msg = "Cannot update metadata for instance. Updating not existing object."
raise ValidationError(
{"metadata": ValidationError(msg, code=MetadataErrorCode.NOT_FOUND.value)}
- )
+ ) from e
diff --git a/saleor/graphql/middleware.py b/saleor/graphql/middleware.py
index b8350f9095..fbf805b346 100644
--- a/saleor/graphql/middleware.py
+++ b/saleor/graphql/middleware.py
@@ -16,6 +16,6 @@ if settings.ENABLE_DEBUG_TOOLBAR:
try:
from graphiql_debug_toolbar.middleware import DebugToolbarMiddleware
except ImportError:
- warnings.warn("The graphiql debug toolbar was not installed.")
+ warnings.warn("The graphiql debug toolbar was not installed.", stacklevel=1)
else:
DebugToolbarMiddleware.process_view = process_view
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index ade25d3d4f..07ba76e79e 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -1526,7 +1526,7 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
OrderBulkTransaction(transaction=new_transaction, events=events)
)
except ValidationError as error:
- for field, err in error.error_dict.items():
+ for _field, err in error.error_dict.items():
message = str(err[0].message)
code = err[0].code
order_data.errors.append(
diff --git a/saleor/graphql/order/bulk_mutations/utils.py b/saleor/graphql/order/bulk_mutations/utils.py
index 155b2cb699..071b07b3a3 100644
--- a/saleor/graphql/order/bulk_mutations/utils.py
+++ b/saleor/graphql/order/bulk_mutations/utils.py
@@ -66,12 +66,12 @@ def get_instance(
str(input.get(data_key)), model_name, raise_error=True
)
input[data_key] = id
- except GraphQLError as err:
+ except GraphQLError as e:
raise ValidationError(
- message=err.message,
+ message=e.message,
code=error_enum.INVALID.value,
params={"path": f"{path}.{data_key}" if path else data_key},
- )
+ ) from e
lookup_key = ".".join((model_name, db_key, input[data_key]))
instance = instance_storage.get(lookup_key)
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 773e63b334..c7edc4fbaa 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -164,9 +164,9 @@ class DraftOrderComplete(BaseMutation):
site.settings
),
)
- except InsufficientStock as exc:
- errors = prepare_insufficient_stock_order_validation_errors(exc)
- raise ValidationError({"lines": errors})
+ except InsufficientStock as e:
+ errors = prepare_insufficient_stock_order_validation_errors(e)
+ raise ValidationError({"lines": errors}) from e
order_info = OrderInfo(
order=order,
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 4422a359e1..cf43fa6ccd 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -297,7 +297,7 @@ class DraftOrderCreate(
# Validate voucher when it's included in voucher usage calculation
try:
code_instance = get_active_voucher_code(voucher, channel.slug)
- except ValidationError:
+ except ValidationError as e:
raise ValidationError(
{
"voucher": ValidationError(
@@ -305,7 +305,7 @@ class DraftOrderCreate(
code=OrderErrorCode.INVALID_VOUCHER.value,
)
}
- )
+ ) from e
else:
cls.clean_voucher_listing(voucher, channel, "voucher")
if not code_instance:
@@ -326,7 +326,7 @@ class DraftOrderCreate(
# Validate voucher when it's included in voucher usage calculation
try:
code_instance = get_voucher_code_instance(voucher_code, channel.slug)
- except ValidationError:
+ except ValidationError as e:
raise ValidationError(
{
"voucher_code": ValidationError(
@@ -334,7 +334,7 @@ class DraftOrderCreate(
code=OrderErrorCode.INVALID_VOUCHER_CODE.value,
)
}
- )
+ ) from e
voucher = code_instance.voucher
else:
code_instance = VoucherCode.objects.filter(code=voucher_code).first()
@@ -454,9 +454,9 @@ class DraftOrderCreate(
def clean_redirect_url(cls, redirect_url):
try:
validate_storefront_url(redirect_url)
- except ValidationError as error:
- error.code = OrderErrorCode.INVALID.value
- raise ValidationError({"redirect_url": error})
+ except ValidationError as e:
+ e.code = OrderErrorCode.INVALID.value
+ raise ValidationError({"redirect_url": e}) from e
@staticmethod
def _save_addresses(instance: models.Order, cleaned_input):
@@ -543,11 +543,11 @@ class DraftOrderCreate(
cls._save_lines(
info, instance, cleaned_input.get("lines_data"), app, manager
)
- except TaxError as tax_error:
+ except TaxError as e:
raise ValidationError(
- f"Unable to calculate taxes - {str(tax_error)}",
+ f"Unable to calculate taxes - {str(e)}",
code=OrderErrorCode.TAX_ERROR.value,
- )
+ ) from e
if "shipping_method" in cleaned_input:
method = cleaned_input["shipping_method"]
diff --git a/saleor/graphql/order/mutations/fulfillment_approve.py b/saleor/graphql/order/mutations/fulfillment_approve.py
index a87c1cec43..ccd8abc0ad 100644
--- a/saleor/graphql/order/mutations/fulfillment_approve.py
+++ b/saleor/graphql/order/mutations/fulfillment_approve.py
@@ -101,9 +101,9 @@ class FulfillmentApprove(BaseMutation):
notify_customer=notify_customer,
allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,
)
- except InsufficientStock as exc:
- errors = prepare_insufficient_stock_order_validation_errors(exc)
- raise ValidationError({"stocks": errors})
+ except InsufficientStock as e:
+ errors = prepare_insufficient_stock_order_validation_errors(e)
+ raise ValidationError({"stocks": errors}) from e
order.refresh_from_db(fields=["status"])
return FulfillmentApprove(fulfillment=fulfillment, order=order)
diff --git a/saleor/graphql/order/mutations/order_fulfill.py b/saleor/graphql/order/mutations/order_fulfill.py
index de376b64dc..c409c76ff9 100644
--- a/saleor/graphql/order/mutations/order_fulfill.py
+++ b/saleor/graphql/order/mutations/order_fulfill.py
@@ -315,8 +315,8 @@ class OrderFulfill(BaseMutation):
approved=approved,
tracking_number=tracking_number,
)
- except InsufficientStock as exc:
- errors = prepare_insufficient_stock_order_validation_errors(exc)
- raise ValidationError({"stocks": errors})
+ except InsufficientStock as e:
+ errors = prepare_insufficient_stock_order_validation_errors(e)
+ raise ValidationError({"stocks": errors}) from e
return OrderFulfill(fulfillments=fulfillments, order=instance)
diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.py
index 808868744c..ca36c6de4d 100644
--- a/saleor/graphql/order/mutations/order_line_update.py
+++ b/saleor/graphql/order/mutations/order_line_update.py
@@ -97,11 +97,11 @@ class OrderLineUpdate(
instance.order.channel,
manager,
)
- except InsufficientStock:
+ except InsufficientStock as e:
raise ValidationError(
"Cannot set new quantity because of insufficient stock.",
code=OrderErrorCode.INSUFFICIENT_STOCK.value,
- )
+ ) from e
invalidate_order_prices(instance.order)
recalculate_order_weight(instance.order)
instance.order.save(update_fields=["should_refresh_prices", "weight"])
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index 644ecd019f..8677b9f35b 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -129,9 +129,9 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
channel = order.channel
validate_product_is_published_in_channel(variants, channel)
validate_variant_channel_listings(variants, channel)
- except ValidationError as error:
- cls.remap_error_fields(error, cls._meta.errors_mapping)
- raise ValidationError(error)
+ except ValidationError as e:
+ cls.remap_error_fields(e, cls._meta.errors_mapping)
+ raise ValidationError(e) from e
@staticmethod
def add_lines_to_order(order, lines_data, user, app, manager):
@@ -147,11 +147,11 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
allocate_stock=order.is_unconfirmed(),
)
added_lines.append(line)
- except TaxError as tax_error:
+ except TaxError as e:
raise ValidationError(
- f"Unable to calculate taxes - {str(tax_error)}",
+ f"Unable to calculate taxes - {str(e)}",
code=OrderErrorCode.TAX_ERROR.value,
- )
+ ) from e
return added_lines
@classmethod
diff --git a/saleor/graphql/order/mutations/order_mark_as_paid.py b/saleor/graphql/order/mutations/order_mark_as_paid.py
index b29fc8fb8d..7eaed91778 100644
--- a/saleor/graphql/order/mutations/order_mark_as_paid.py
+++ b/saleor/graphql/order/mutations/order_mark_as_paid.py
@@ -97,7 +97,7 @@ class OrderMarkAsPaid(BaseMutation):
message, code=OrderErrorCode.TRANSACTION_ERROR.value
)
}
- )
+ ) from e
mark_order_as_paid_with_transaction(
order=order,
request_user=request_user,
diff --git a/saleor/graphql/order/mutations/order_note_common.py b/saleor/graphql/order/mutations/order_note_common.py
index f17acdb442..b8e19fa2fe 100644
--- a/saleor/graphql/order/mutations/order_note_common.py
+++ b/saleor/graphql/order/mutations/order_note_common.py
@@ -30,7 +30,7 @@ class OrderNoteCommon(BaseMutation):
def clean_input(cls, _info, _instance, data):
try:
cleaned_input = validate_required_string_field(data, "message")
- except ValidationError:
+ except ValidationError as e:
raise ValidationError(
{
"message": ValidationError(
@@ -38,5 +38,5 @@ class OrderNoteCommon(BaseMutation):
code=OrderNoteAddErrorCode.REQUIRED.value,
)
}
- )
+ ) from e
return cleaned_input
diff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.py
index 6b25fe1801..963ad30e4e 100644
--- a/saleor/graphql/order/mutations/utils.py
+++ b/saleor/graphql/order/mutations/utils.py
@@ -174,7 +174,7 @@ def try_payment_action(order, user, app, payment, func, *args, **kwargs):
message, code=OrderErrorCode.PAYMENT_ERROR.value
)
}
- )
+ ) from e
def clean_payment(payment: Optional[payment_models.Payment]) -> payment_models.Payment:
diff --git a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py
index 1847635045..9f7e015856 100644
--- a/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py
+++ b/saleor/graphql/order/tests/mutations/test_order_bulk_cancel.py
@@ -65,7 +65,7 @@ def test_order_bulk_cancel(
]
mock_cancel_order.assert_has_calls(calls, any_order=True)
- mock_cancel_order.call_count == expected_count
+ assert mock_cancel_order.call_count == expected_count
def test_order_bulk_cancel_by_user_no_channel_access(
diff --git a/saleor/graphql/order/tests/mutations/test_order_fulfill.py b/saleor/graphql/order/tests/mutations/test_order_fulfill.py
index d3d62a0529..079e634a37 100644
--- a/saleor/graphql/order/tests/mutations/test_order_fulfill.py
+++ b/saleor/graphql/order/tests/mutations/test_order_fulfill.py
@@ -823,7 +823,7 @@ def test_order_fulfill_with_gift_cards_by_app(
assert not data["errors"]
assert GiftCard.objects.count() == quantity
- mock_send_notification.assert_not_called
+ mock_send_notification.assert_not_called()
@patch("saleor.giftcard.utils.send_gift_card_notification")
@@ -884,7 +884,7 @@ def test_order_fulfill_with_gift_cards_multiple_warehouses(
assert not data["errors"]
assert GiftCard.objects.count() == quantity_1 + quantity_2
- mock_send_notification.assert_not_called
+ mock_send_notification.assert_not_called()
@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
diff --git a/saleor/graphql/order/tests/queries/test_order_with_filter.py b/saleor/graphql/order/tests/queries/test_order_with_filter.py
index b5fb571236..5959b79a14 100644
--- a/saleor/graphql/order/tests/queries/test_order_with_filter.py
+++ b/saleor/graphql/order/tests/queries/test_order_with_filter.py
@@ -1419,7 +1419,5 @@ def test_order_query_with_filter_checkout_tokens_empty_list(
order_data = content["data"]["orders"]["edges"]
assert len(order_data) == len(orders_from_checkout + [order])
- for order in orders_from_checkout + [order]:
- assert {
- "node": {"id": graphene.Node.to_global_id("Order", order.pk)}
- } in order_data
+ for o in orders_from_checkout + [order]:
+ assert {"node": {"id": graphene.Node.to_global_id("Order", o.pk)}} in order_data
diff --git a/saleor/graphql/page/mutations/page_create.py b/saleor/graphql/page/mutations/page_create.py
index 0327ae679e..16be6ace56 100644
--- a/saleor/graphql/page/mutations/page_create.py
+++ b/saleor/graphql/page/mutations/page_create.py
@@ -83,9 +83,9 @@ class PageCreate(ModelMutation):
cleaned_input = validate_slug_and_generate_if_needed(
instance, "title", cleaned_input
)
- except ValidationError as error:
- error.code = PageErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
+ except ValidationError as e:
+ e.code = PageErrorCode.REQUIRED.value
+ raise ValidationError({"slug": e}) from e
if "publication_date" in cleaned_input and "published_at" in cleaned_input:
raise ValidationError(
@@ -116,8 +116,8 @@ class PageCreate(ModelMutation):
cleaned_input["attributes"] = cls.clean_attributes(
attributes, page_type
)
- except ValidationError as exc:
- raise ValidationError({"attributes": exc})
+ except ValidationError as e:
+ raise ValidationError({"attributes": e}) from e
clean_seo_fields(cleaned_input)
diff --git a/saleor/graphql/page/mutations/page_reorder_attribute_values.py b/saleor/graphql/page/mutations/page_reorder_attribute_values.py
index 3b6607a16a..3fbcb9abfc 100644
--- a/saleor/graphql/page/mutations/page_reorder_attribute_values.py
+++ b/saleor/graphql/page/mutations/page_reorder_attribute_values.py
@@ -66,9 +66,9 @@ class PageReorderAttributeValues(BaseReorderAttributeValuesMutation):
try:
operations = cls.prepare_operations(moves, values_m2m)
- except ValidationError as error:
- error.code = error_code_enum.NOT_FOUND.value
- raise ValidationError({"moves": error})
+ except ValidationError as e:
+ e.code = error_code_enum.NOT_FOUND.value
+ raise ValidationError({"moves": e}) from e
with traced_atomic_transaction():
perform_reordering(values_m2m, operations)
@@ -81,7 +81,7 @@ class PageReorderAttributeValues(BaseReorderAttributeValuesMutation):
try:
page = page_models.Page.objects.get(pk=pk)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"page_id": ValidationError(
@@ -89,7 +89,7 @@ class PageReorderAttributeValues(BaseReorderAttributeValuesMutation):
code=PageErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
return page
@classmethod
diff --git a/saleor/graphql/page/mutations/page_type_reorder_attributes.py b/saleor/graphql/page/mutations/page_type_reorder_attributes.py
index 3c7fd2e398..f95d3fe2a2 100644
--- a/saleor/graphql/page/mutations/page_type_reorder_attributes.py
+++ b/saleor/graphql/page/mutations/page_type_reorder_attributes.py
@@ -45,7 +45,7 @@ class PageTypeReorderAttributes(BaseReorderAttributesMutation):
page_type = page_models.PageType.objects.prefetch_related(
"attributepage"
).get(pk=pk)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"page_type_id": ValidationError(
@@ -53,16 +53,16 @@ class PageTypeReorderAttributes(BaseReorderAttributesMutation):
code=PageErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
page_attributes = page_type.attributepage.all()
moves = data["moves"]
try:
operations = cls.prepare_operations(moves, page_attributes)
- except ValidationError as error:
- error.code = PageErrorCode.NOT_FOUND.value
- raise ValidationError({"moves": error})
+ except ValidationError as e:
+ e.code = PageErrorCode.NOT_FOUND.value
+ raise ValidationError({"moves": e}) from e
with traced_atomic_transaction():
perform_reordering(page_attributes, operations)
diff --git a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
index 7e27c8b0cb..201b1c3d9c 100644
--- a/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
+++ b/saleor/graphql/payment/mutations/payment/checkout_payment_create.py
@@ -169,10 +169,10 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
return
try:
validate_storefront_url(return_url)
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
- {"redirect_url": error}, code=PaymentErrorCode.INVALID.value
- )
+ {"redirect_url": e}, code=PaymentErrorCode.INVALID.value
+ ) from e
@classmethod
def validate_metadata_keys(cls, metadata_list: list[dict]):
diff --git a/saleor/graphql/payment/mutations/payment/payment_capture.py b/saleor/graphql/payment/mutations/payment/payment_capture.py
index ab114b5a10..ee296dae09 100644
--- a/saleor/graphql/payment/mutations/payment/payment_capture.py
+++ b/saleor/graphql/payment/mutations/payment/payment_capture.py
@@ -47,5 +47,7 @@ class PaymentCapture(BaseMutation):
)
payment.refresh_from_db()
except PaymentError as e:
- raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR.value)
+ raise ValidationError(
+ str(e), code=PaymentErrorCode.PAYMENT_ERROR.value
+ ) from e
return PaymentCapture(payment=payment)
diff --git a/saleor/graphql/payment/mutations/payment/payment_check_balance.py b/saleor/graphql/payment/mutations/payment/payment_check_balance.py
index 5a4213f465..e69824018e 100644
--- a/saleor/graphql/payment/mutations/payment/payment_check_balance.py
+++ b/saleor/graphql/payment/mutations/payment/payment_check_balance.py
@@ -80,7 +80,7 @@ class PaymentCheckBalance(BaseMutation):
except PaymentError as e:
raise ValidationError(
str(e), code=PaymentErrorCode.BALANCE_CHECK_ERROR.value
- )
+ ) from e
return PaymentCheckBalance(data=data)
diff --git a/saleor/graphql/payment/mutations/payment/payment_initialize.py b/saleor/graphql/payment/mutations/payment/payment_initialize.py
index 9c1d206e8b..97c5dc5cf9 100644
--- a/saleor/graphql/payment/mutations/payment/payment_initialize.py
+++ b/saleor/graphql/payment/mutations/payment/payment_initialize.py
@@ -43,7 +43,7 @@ class PaymentInitialize(BaseMutation):
def validate_channel(cls, channel_slug):
try:
channel = Channel.objects.get(slug=channel_slug)
- except Channel.DoesNotExist:
+ except Channel.DoesNotExist as e:
raise ValidationError(
{
"channel": ValidationError(
@@ -51,7 +51,7 @@ class PaymentInitialize(BaseMutation):
code=PaymentErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
if not channel.is_active:
raise ValidationError(
{
@@ -80,5 +80,5 @@ class PaymentInitialize(BaseMutation):
str(e), code=PaymentErrorCode.INVALID.value
)
}
- )
+ ) from e
return PaymentInitialize(initialized_payment=response)
diff --git a/saleor/graphql/payment/mutations/payment/payment_refund.py b/saleor/graphql/payment/mutations/payment/payment_refund.py
index 4942af03cc..1772ce9e9a 100644
--- a/saleor/graphql/payment/mutations/payment/payment_refund.py
+++ b/saleor/graphql/payment/mutations/payment/payment_refund.py
@@ -49,7 +49,9 @@ class PaymentRefund(PaymentCapture):
)
payment.refresh_from_db()
except PaymentError as e:
- raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR.value)
+ raise ValidationError(
+ str(e), code=PaymentErrorCode.PAYMENT_ERROR.value
+ ) from e
if (
payment.order_id
and payment_transaction
diff --git a/saleor/graphql/payment/mutations/payment/payment_void.py b/saleor/graphql/payment/mutations/payment/payment_void.py
index f87513ffe0..c3a0c5fc7b 100644
--- a/saleor/graphql/payment/mutations/payment/payment_void.py
+++ b/saleor/graphql/payment/mutations/payment/payment_void.py
@@ -40,5 +40,7 @@ class PaymentVoid(BaseMutation):
gateway.void(payment, manager, channel_slug=channel_slug)
payment.refresh_from_db()
except PaymentError as e:
- raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR.value)
+ raise ValidationError(
+ str(e), code=PaymentErrorCode.PAYMENT_ERROR.value
+ ) from e
return PaymentVoid(payment=payment)
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_create.py b/saleor/graphql/payment/mutations/transaction/transaction_create.py
index ea8195f819..05c7ddc8eb 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_create.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_create.py
@@ -126,14 +126,14 @@ class TransactionCreate(BaseMutation):
validator = URLValidator()
try:
validator(external_url)
- except ValidationError:
+ except ValidationError as e:
raise ValidationError(
{
"transaction": ValidationError(
"Invalid format of `externalUrl`.", code=error_code
)
}
- )
+ ) from e
@classmethod
def validate_metadata_keys( # type: ignore[override]
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index f1a351e2c2..b15e75ac86 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -267,15 +267,15 @@ class TransactionEventReport(ModelMutation):
)
try:
amount = get_transaction_event_amount(event_type, psp_reference)
- except ValueError as error:
+ except ValueError as e:
raise ValidationError(
{
"amount": ValidationError(
- str(error),
+ str(e),
code=TransactionEventReportErrorCode.REQUIRED.value,
)
},
- )
+ ) from e
return quantize_price(amount, currency)
@classmethod
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
index ef081165e6..6706bd6869 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_initialize.py
@@ -199,7 +199,7 @@ class TransactionInitialize(TransactionSessionBase):
manager=manager,
idempotency_key=idempotency_key,
)
- except TransactionItemIdempotencyUniqueError:
+ except TransactionItemIdempotencyUniqueError as e:
if payment_ids:
activate_payments(payment_ids)
raise ValidationError(
@@ -212,7 +212,7 @@ class TransactionInitialize(TransactionSessionBase):
code=TransactionInitializeErrorCode.UNIQUE.value,
)
}
- )
+ ) from e
return cls(transaction=transaction, transaction_event=event, data=data)
@staticmethod
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
index aea7de2a9e..e973144a11 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
@@ -181,5 +181,5 @@ class TransactionRequestAction(BaseMutation):
except PaymentError as e:
error_enum = TransactionRequestActionErrorCode
code = error_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
- raise ValidationError(str(e), code=code)
+ raise ValidationError(str(e), code=code) from e
return TransactionRequestAction(transaction=transaction)
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py b/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
index 1f2482f782..157579192e 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_refund_for_granted_refund.py
@@ -196,7 +196,7 @@ class TransactionRequestRefundForGrantedRefund(BaseMutation):
except PaymentError as e:
error_enum = TransactionRequestActionErrorCode
code = error_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
- raise ValidationError(str(e), code=code)
+ raise ValidationError(str(e), code=code) from e
finally:
if assigned_granted_refund:
calculate_order_granted_refund_status(assigned_granted_refund)
diff --git a/saleor/graphql/payment/mutations/transaction/utils.py b/saleor/graphql/payment/mutations/transaction/utils.py
index eee758cc73..2ac49c805e 100644
--- a/saleor/graphql/payment/mutations/transaction/utils.py
+++ b/saleor/graphql/payment/mutations/transaction/utils.py
@@ -70,13 +70,13 @@ def clean_customer_ip_address(
raise PermissionDenied(permissions=[PaymentPermissions.HANDLE_PAYMENTS])
try:
validate_ipv46_address(customer_ip_address)
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
{
"customer_ip_address": ValidationError(
- message=error.message,
+ message=e.message,
code=error_code,
)
}
- )
+ ) from e
return customer_ip_address
diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
index bdd9bf64c4..0635c399b5 100644
--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py
+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py
@@ -697,7 +697,7 @@ class ProductBulkCreate(BaseMutation):
def create_variants(cls, info, product, variants_inputs, index, index_error_map):
variants_instances_data = []
- for variant_index, variant_data in enumerate(variants_inputs):
+ for variant_data in variants_inputs:
if variant_data:
try:
metadata_list = variant_data.pop("metadata", None)
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index eee9aa5cbb..036ac0bd58 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -267,7 +267,7 @@ class ProductAttributeAssign(BaseMutation, VariantAssignmentValidationMixin):
variant_selection=variant_selection,
)
else:
- for pk, variant_selection, _ in pks:
+ for pk, _variant_selection, _ in pks:
model.objects.create(
product_type=product_type,
attribute_id=pk,
@@ -596,7 +596,7 @@ class ProductTypeReorderAttributes(BaseReorderAttributesMutation):
product_type = models.ProductType.objects.prefetch_related(m2m_field).get(
pk=pk
)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"product_type_id": ValidationError(
@@ -604,15 +604,15 @@ class ProductTypeReorderAttributes(BaseReorderAttributesMutation):
code=ProductErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
attributes_m2m = getattr(product_type, m2m_field)
try:
operations = cls.prepare_operations(moves, attributes_m2m)
- except ValidationError as error:
- error.code = ProductErrorCode.NOT_FOUND.value
- raise ValidationError({"moves": error})
+ except ValidationError as e:
+ e.code = ProductErrorCode.NOT_FOUND.value
+ raise ValidationError({"moves": e}) from e
with traced_atomic_transaction():
perform_reordering(attributes_m2m, operations)
@@ -665,9 +665,9 @@ class ProductReorderAttributeValues(BaseReorderAttributeValuesMutation):
try:
operations = cls.prepare_operations(moves, values_m2m)
- except ValidationError as error:
- error.code = error_code_enum.NOT_FOUND.value
- raise ValidationError({"moves": error})
+ except ValidationError as e:
+ e.code = error_code_enum.NOT_FOUND.value
+ raise ValidationError({"moves": e}) from e
with traced_atomic_transaction():
perform_reordering(values_m2m, operations)
@@ -693,7 +693,7 @@ class ProductReorderAttributeValues(BaseReorderAttributeValuesMutation):
try:
product = models.Product.objects.get(pk=pk)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"product_id": ValidationError(
@@ -701,7 +701,7 @@ class ProductReorderAttributeValues(BaseReorderAttributeValuesMutation):
code=ProductErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
return product
@classmethod
@@ -777,7 +777,7 @@ class ProductVariantReorderAttributeValues(BaseReorderAttributeValuesMutation):
variant = models.ProductVariant.objects.prefetch_related("attributes").get(
pk=pk
)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"variant_id": ValidationError(
@@ -785,5 +785,5 @@ class ProductVariantReorderAttributeValues(BaseReorderAttributeValuesMutation):
code=ProductErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
return variant
diff --git a/saleor/graphql/product/mutations/category/category_create.py b/saleor/graphql/product/mutations/category/category_create.py
index c223d9e9ef..e80c35c800 100644
--- a/saleor/graphql/product/mutations/category/category_create.py
+++ b/saleor/graphql/product/mutations/category/category_create.py
@@ -82,9 +82,9 @@ class CategoryCreate(ModelMutation):
cleaned_input = validate_slug_and_generate_if_needed(
instance, "name", cleaned_input
)
- except ValidationError as error:
- error.code = ProductErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
+ except ValidationError as e:
+ e.code = ProductErrorCode.REQUIRED.value
+ raise ValidationError({"slug": e}) from e
parent_id = data["parent_id"]
if parent_id:
parent = cls.get_node_or_error(
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index f283890b19..18ddda52ca 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -296,7 +296,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
try:
ProductVariantChannelListing.objects.bulk_create(variant_channel_listings)
- except IntegrityError:
+ except IntegrityError as e:
raise ValidationError(
{
"addVariants": ValidationError(
@@ -305,7 +305,7 @@ class ProductChannelListingUpdate(BaseChannelListingMutation):
code=ProductErrorCode.ALREADY_EXISTS.value,
)
}
- )
+ ) from e
@classmethod
def remove_variants(
diff --git a/saleor/graphql/product/mutations/collection/collection_create.py b/saleor/graphql/product/mutations/collection/collection_create.py
index 0df97a8ec3..300b95da29 100644
--- a/saleor/graphql/product/mutations/collection/collection_create.py
+++ b/saleor/graphql/product/mutations/collection/collection_create.py
@@ -103,9 +103,9 @@ class CollectionCreate(ModelMutation):
cleaned_input = validate_slug_and_generate_if_needed(
instance, "name", cleaned_input
)
- except ValidationError as error:
- error.code = CollectionErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
+ except ValidationError as e:
+ e.code = CollectionErrorCode.REQUIRED.value
+ raise ValidationError({"slug": e}) from e
if data.get("background_image"):
clean_image_file(cleaned_input, "background_image", CollectionErrorCode)
is_published = cleaned_input.get("is_published")
diff --git a/saleor/graphql/product/mutations/collection/collection_reorder_products.py b/saleor/graphql/product/mutations/collection/collection_reorder_products.py
index 5972aa13a7..aa42f8dead 100644
--- a/saleor/graphql/product/mutations/collection/collection_reorder_products.py
+++ b/saleor/graphql/product/mutations/collection/collection_reorder_products.py
@@ -65,7 +65,7 @@ class CollectionReorderProducts(BaseMutation):
collection = models.Collection.objects.prefetch_related(
"collectionproduct"
).get(pk=pk)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"collection_id": ValidationError(
@@ -73,7 +73,7 @@ class CollectionReorderProducts(BaseMutation):
code=ProductErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
m2m_related_field = collection.collectionproduct
@@ -87,7 +87,7 @@ class CollectionReorderProducts(BaseMutation):
try:
m2m_info = m2m_related_field.get(product_id=int(product_pk))
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"moves": ValidationError(
@@ -95,7 +95,7 @@ class CollectionReorderProducts(BaseMutation):
code=CollectionErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
operations[m2m_info.pk] = move_info.sort_order
with traced_atomic_transaction():
diff --git a/saleor/graphql/product/mutations/product/product_create.py b/saleor/graphql/product/mutations/product/product_create.py
index 069f4d8c5a..3c6f9857d1 100644
--- a/saleor/graphql/product/mutations/product/product_create.py
+++ b/saleor/graphql/product/mutations/product/product_create.py
@@ -183,17 +183,17 @@ class ProductCreate(ModelMutation):
cleaned_input = validate_slug_and_generate_if_needed(
instance, "name", cleaned_input
)
- except ValidationError as error:
- error.code = ProductErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
+ except ValidationError as e:
+ e.code = ProductErrorCode.REQUIRED.value
+ raise ValidationError({"slug": e}) from e
if attributes and product_type:
try:
cleaned_input["attributes"] = cls.clean_attributes(
attributes, product_type
)
- except ValidationError as exc:
- raise ValidationError({"attributes": exc})
+ except ValidationError as e:
+ raise ValidationError({"attributes": e}) from e
clean_tax_code(cleaned_input)
diff --git a/saleor/graphql/product/mutations/product_type/product_type_create.py b/saleor/graphql/product/mutations/product_type/product_type_create.py
index ddd0dc1d80..2fc7b1fa49 100644
--- a/saleor/graphql/product/mutations/product_type/product_type_create.py
+++ b/saleor/graphql/product/mutations/product_type/product_type_create.py
@@ -112,9 +112,9 @@ class ProductTypeCreate(ModelMutation):
cleaned_input = validate_slug_and_generate_if_needed(
instance, "name", cleaned_input
)
- except ValidationError as error:
- error.code = ProductErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
+ except ValidationError as e:
+ e.code = ProductErrorCode.REQUIRED.value
+ raise ValidationError({"slug": e}) from e
clean_tax_code(cleaned_input)
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_create.py b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
index c39a0de826..1d96822725 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_create.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_create.py
@@ -268,8 +268,8 @@ class ProductVariantCreate(ModelMutation):
"All required attributes must take a value.",
ProductErrorCode.REQUIRED.value,
)
- except ValidationError as exc:
- raise ValidationError({"attributes": exc})
+ except ValidationError as e:
+ raise ValidationError({"attributes": e}) from e
else:
if attributes:
raise ValidationError(
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_preorder_deactivate.py b/saleor/graphql/product/mutations/product_variant/product_variant_preorder_deactivate.py
index a636478435..0c74cd7bbb 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_preorder_deactivate.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_preorder_deactivate.py
@@ -58,11 +58,11 @@ class ProductVariantPreorderDeactivate(BaseMutation):
with traced_atomic_transaction():
try:
deactivate_preorder_for_variant(variant)
- except PreorderAllocationError as error:
+ except PreorderAllocationError as e:
raise ValidationError(
- str(error),
+ str(e),
code=ProductErrorCode.PREORDER_VARIANT_CANNOT_BE_DEACTIVATED.value,
- )
+ ) from e
manager = get_plugin_manager_promise(info.context).get()
variant = ChannelContext(node=variant, channel_slug=None)
cls.call_event(manager.product_variant_updated, variant.node)
diff --git a/saleor/graphql/product/mutations/product_variant/product_variant_reorder.py b/saleor/graphql/product/mutations/product_variant/product_variant_reorder.py
index 4583d1e456..250711f964 100644
--- a/saleor/graphql/product/mutations/product_variant/product_variant_reorder.py
+++ b/saleor/graphql/product/mutations/product_variant/product_variant_reorder.py
@@ -49,7 +49,7 @@ class ProductVariantReorder(BaseMutation):
try:
product = models.Product.objects.get(pk=pk)
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"product_id": ValidationError(
@@ -57,7 +57,7 @@ class ProductVariantReorder(BaseMutation):
code=ProductErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
variants_m2m = product.variants.all()
operations = {}
@@ -69,7 +69,7 @@ class ProductVariantReorder(BaseMutation):
try:
m2m_info = variants_m2m.get(id=int(variant_pk))
- except ObjectDoesNotExist:
+ except ObjectDoesNotExist as e:
raise ValidationError(
{
"moves": ValidationError(
@@ -77,7 +77,7 @@ class ProductVariantReorder(BaseMutation):
code=ProductErrorCode.NOT_FOUND.value,
)
}
- )
+ ) from e
operations[m2m_info.pk] = move_info.sort_order
manager = get_plugin_manager_promise(info.context).get()
with traced_atomic_transaction():
diff --git a/saleor/graphql/product/mutations/product_variant/variant_media_unassign.py b/saleor/graphql/product/mutations/product_variant/variant_media_unassign.py
index 63491dfe88..1d14f389d0 100644
--- a/saleor/graphql/product/mutations/product_variant/variant_media_unassign.py
+++ b/saleor/graphql/product/mutations/product_variant/variant_media_unassign.py
@@ -47,7 +47,7 @@ class VariantMediaUnassign(BaseMutation):
variant_media = models.VariantMedia.objects.get(
media=media, variant=variant
)
- except models.VariantMedia.DoesNotExist:
+ except models.VariantMedia.DoesNotExist as e:
raise ValidationError(
{
"media_id": ValidationError(
@@ -55,7 +55,7 @@ class VariantMediaUnassign(BaseMutation):
code=ProductErrorCode.NOT_PRODUCTS_IMAGE.value,
)
}
- )
+ ) from e
else:
variant_media.delete()
diff --git a/saleor/graphql/product/tests/queries/test_product_variants_query.py b/saleor/graphql/product/tests/queries/test_product_variants_query.py
index 967628fac2..abfde0b640 100644
--- a/saleor/graphql/product/tests/queries/test_product_variants_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_variants_query.py
@@ -4,7 +4,10 @@ from .....product.models import Product, ProductVariant
from ....tests.utils import get_graphql_content, get_graphql_content_from_response
-def _fetch_all_variants(client, variables={}, permissions=None):
+def _fetch_all_variants(client, variables=None, permissions=None):
+ if variables is None:
+ variables = {}
+
query = """
query fetchAllVariants($channel: String) {
productVariants(first: 10, channel: $channel) {
diff --git a/saleor/graphql/product/tests/queries/test_variant_query.py b/saleor/graphql/product/tests/queries/test_variant_query.py
index 5a7d29b827..c590a05775 100644
--- a/saleor/graphql/product/tests/queries/test_variant_query.py
+++ b/saleor/graphql/product/tests/queries/test_variant_query.py
@@ -563,7 +563,7 @@ def test_get_variant_by_id_with_variant_selection_filter(
assert len(data["attributes"]) == 1
assert data["attributes"][0]["attribute"]["slug"] == size_attribute.slug
else:
- len(data["attributes"]) == 2
+ assert len(data["attributes"]) == 2
def test_get_variant_with_sorted_attribute_values(
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index d3f6322e42..82fde2574f 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -91,9 +91,9 @@ def create_stocks(
for stock_data, warehouse in zip(stocks_data, warehouses)
]
)
- except IntegrityError:
+ except IntegrityError as e:
msg = "Stock for one of warehouses already exists for this product variant."
- raise ValidationError(msg)
+ raise ValidationError(msg) from e
return new_stocks
diff --git a/saleor/graphql/shipping/mutations/base.py b/saleor/graphql/shipping/mutations/base.py
index ca3d18c549..3f027c84b8 100644
--- a/saleor/graphql/shipping/mutations/base.py
+++ b/saleor/graphql/shipping/mutations/base.py
@@ -424,7 +424,7 @@ class ShippingPriceMixin:
instance.postal_code_rules.create(
start=start, end=end, inclusion_type=inclusion_type
)
- except IntegrityError:
+ except IntegrityError as e:
raise ValidationError(
{
"addPostalCodeRules": ValidationError(
@@ -432,7 +432,7 @@ class ShippingPriceMixin:
code=ShippingErrorCode.ALREADY_EXISTS.value,
)
}
- )
+ ) from e
class ShippingMethodTypeMixin:
diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.py
index c3366b31c2..3dc2abb11c 100644
--- a/saleor/graphql/shop/mutations/shop_settings_update.py
+++ b/saleor/graphql/shop/mutations/shop_settings_update.py
@@ -153,11 +153,11 @@ class ShopSettingsUpdate(BaseMutation):
if data.get("customer_set_password_url"):
try:
validate_storefront_url(data["customer_set_password_url"])
- except ValidationError as error:
+ except ValidationError as e:
raise ValidationError(
- {"customer_set_password_url": error},
+ {"customer_set_password_url": e},
code=ShopErrorCode.INVALID.value,
- )
+ ) from e
if "reserve_stock_duration_anonymous_user" in data:
new_value = data["reserve_stock_duration_anonymous_user"]
diff --git a/saleor/graphql/tax/mutations/tax_configuration_update.py b/saleor/graphql/tax/mutations/tax_configuration_update.py
index 8feed0894c..339c895508 100644
--- a/saleor/graphql/tax/mutations/tax_configuration_update.py
+++ b/saleor/graphql/tax/mutations/tax_configuration_update.py
@@ -205,8 +205,10 @@ class TaxConfigurationUpdate(ModelMutation):
info: ResolveInfo,
app_identifier,
active_tax_app_identifiers,
- country_codes=[],
+ country_codes=None,
):
+ if country_codes is None:
+ country_codes = []
if app_identifier not in active_tax_app_identifiers:
message = "Did not found Tax App with provided taxAppId."
code = error_codes.TaxConfigurationUpdateErrorCode.NOT_FOUND.value
diff --git a/saleor/graphql/translations/mutations/utils.py b/saleor/graphql/translations/mutations/utils.py
index 93022f6d12..73211dc1eb 100644
--- a/saleor/graphql/translations/mutations/utils.py
+++ b/saleor/graphql/translations/mutations/utils.py
@@ -108,7 +108,7 @@ class BaseTranslateMutation(ModelMutation):
try:
node_type, node_pk = from_global_id_or_error(id)
- except GraphQLError:
+ except GraphQLError as e:
raise ValidationError(
{
"id": ValidationError(
@@ -116,7 +116,7 @@ class BaseTranslateMutation(ModelMutation):
code=TranslationErrorCode.INVALID,
)
}
- )
+ ) from e
# This mutation accepts either model IDs or translatable content IDs. Below we
# check if provided ID refers to a translatable content which matches with the
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 1d065bd85f..e62d227314 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -100,8 +100,10 @@ class GraphQLView(View):
module_path, class_name = ".".join(parts[:-1]), parts[-1]
module = importlib.import_module(module_path)
return getattr(module, class_name)
- except (ImportError, AttributeError):
- raise ImportError(f"Cannot import '{middleware_name}' graphene middleware!")
+ except (ImportError, AttributeError) as e:
+ raise ImportError(
+ f"Cannot import '{middleware_name}' graphene middleware!"
+ ) from e
@observability.report_view
def dispatch(self, request, *args, **kwargs):
diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.py
index 0261adac02..2c1b87523b 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -529,7 +529,7 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
for (
country_code,
channel_slug,
- ), variant_ids in variant_ids_by_country_and_channel_map.items():
+ ), _variant_ids in variant_ids_by_country_and_channel_map.items():
warehouses = set()
warehouses_in_country = set()
# get warehouses from shipping zones in specific country
diff --git a/saleor/graphql/warehouse/mutations/base.py b/saleor/graphql/warehouse/mutations/base.py
index cab3badbf5..8f2a77d14f 100644
--- a/saleor/graphql/warehouse/mutations/base.py
+++ b/saleor/graphql/warehouse/mutations/base.py
@@ -19,16 +19,16 @@ class WarehouseMixin:
cleaned_input = validate_slug_and_generate_if_needed(
instance, "name", cleaned_input
)
- except ValidationError as error:
- error.code = WarehouseErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
+ except ValidationError as e:
+ e.code = WarehouseErrorCode.REQUIRED.value
+ raise ValidationError({"slug": e}) from e
if "name" in cleaned_input:
try:
cleaned_input = validate_required_string_field(cleaned_input, "name")
- except ValidationError as error:
- error.code = WarehouseErrorCode.REQUIRED.value
- raise ValidationError({"name": error})
+ except ValidationError as e:
+ e.code = WarehouseErrorCode.REQUIRED.value
+ raise ValidationError({"name": e}) from e
# assigning shipping zones in the WarehouseCreate mutation is deprecated
if cleaned_input.get("shipping_zones"):
diff --git a/saleor/graphql/webhook/mutations/webhook_delete.py b/saleor/graphql/webhook/mutations/webhook_delete.py
index 62493fad84..d6d10141a6 100644
--- a/saleor/graphql/webhook/mutations/webhook_delete.py
+++ b/saleor/graphql/webhook/mutations/webhook_delete.py
@@ -63,11 +63,11 @@ class WebhookDelete(ModelDeleteMutation):
try:
response = super().perform_mutation(_root, info, **data)
- except IntegrityError:
+ except IntegrityError as e:
raise ValidationError(
"Webhook couldn't be deleted at this time due to running task."
"Webhook deactivated. Try deleting Webhook later",
code=WebhookErrorCode.DELETE_FAILED.value,
- )
+ ) from e
return response
diff --git a/saleor/order/notifications.py b/saleor/order/notifications.py
index a6508b6322..1ffdf42008 100644
--- a/saleor/order/notifications.py
+++ b/saleor/order/notifications.py
@@ -108,7 +108,7 @@ def get_default_images_payload(images: list[ProductMedia]):
first_image_payload = {"original": get_image_payload(first_image)}
images_payload = None
if images:
- images_payload = [{"original": get_image_payload(image) for image in images}]
+ images_payload = [{"original": get_image_payload(image) for image in images}] # noqa: B035
return {"first_image": first_image_payload, "images": images_payload}
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index 41d6b4e105..97a3bb097f 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -359,7 +359,7 @@ def test_handle_fully_paid_order_gift_cards_not_created(
mock_send_payment_confirmation.assert_called_once_with(order_info, manager)
assert not GiftCard.objects.exists()
- send_notification_mock.assert_not_called
+ send_notification_mock.assert_not_called()
@pytest.mark.parametrize("automatically_confirm_all_new_orders", [True, False])
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 3e75d4fc5d..43f6a49866 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -407,8 +407,10 @@ class AdyenGatewayPlugin(BasePlugin):
return previous_value
try:
payment = Payment.objects.get(pk=payment_information.payment_id)
- except ObjectDoesNotExist:
- raise PaymentError("Payment cannot be performed. Payment does not exists.")
+ except ObjectDoesNotExist as e:
+ raise PaymentError(
+ "Payment cannot be performed. Payment does not exists."
+ ) from e
checkout = payment.checkout
if checkout is None:
@@ -815,7 +817,7 @@ class AdyenGatewayPlugin(BasePlugin):
request_data=request_data,
certificate=apple_certificate,
)
- except SSLError:
+ except SSLError as e:
raise ValidationError(
{
"apple-pay-cert": ValidationError(
@@ -823,6 +825,6 @@ class AdyenGatewayPlugin(BasePlugin):
code=PluginErrorCode.INVALID.value,
)
}
- )
+ ) from e
except Exception:
pass
diff --git a/saleor/payment/gateways/adyen/utils/apple_pay.py b/saleor/payment/gateways/adyen/utils/apple_pay.py
index e7bbed3ed8..6ef1d060ff 100644
--- a/saleor/payment/gateways/adyen/utils/apple_pay.py
+++ b/saleor/payment/gateways/adyen/utils/apple_pay.py
@@ -81,12 +81,12 @@ def initialize_apple_pay_session(
response = make_request_to_initialize_apple_pay(
validation_url, request_data, certificate
)
- except requests.exceptions.RequestException:
+ except requests.exceptions.RequestException as e:
logger.warning("Failed to fetch the Apple Pay session", exc_info=True)
raise PaymentError(
"Unable to create Apple Pay payment session. Make sure that input data "
" and certificate are correct."
- )
+ ) from e
if not response.ok:
# FIXME: shouldn't we forward some details here?
raise PaymentError(
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
index 32af5d6495..5a0539b492 100644
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -88,7 +88,7 @@ def api_call(
return method(request_data, **kwargs)
except (Adyen.AdyenError, ValueError, TypeError, ConnectTimeout) as e:
logger.warning(f"Unable to process the payment: {e}")
- raise PaymentError(f"Unable to process the payment request: {e}.")
+ raise PaymentError(f"Unable to process the payment request: {e}.") from e
def prepare_address_request_data(address: Optional["AddressData"]) -> Optional[dict]:
diff --git a/saleor/payment/gateways/authorize_net/plugin.py b/saleor/payment/gateways/authorize_net/plugin.py
index d4c648a410..0d496ac6f9 100644
--- a/saleor/payment/gateways/authorize_net/plugin.py
+++ b/saleor/payment/gateways/authorize_net/plugin.py
@@ -158,8 +158,10 @@ class AuthorizeNetGatewayPlugin(BasePlugin):
return previous_value
try:
payment = Payment.objects.get(pk=payment_information.payment_id)
- except Payment.DoesNotExist:
- raise PaymentError(f"Cannot find Payment {payment_information.payment_id}.")
+ except Payment.DoesNotExist as e:
+ raise PaymentError(
+ f"Cannot find Payment {payment_information.payment_id}."
+ ) from e
return refund(
payment_information, payment.cc_last_digits, self._get_gateway_config()
)
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index 7cd28df664..3ce485985a 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -319,8 +319,8 @@ def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayRe
transaction_id=payment_information.token,
amount_or_options=str(payment_information.amount),
)
- except braintree_sdk.exceptions.NotFoundError:
- raise BraintreeException(DEFAULT_ERROR_MESSAGE)
+ except braintree_sdk.exceptions.NotFoundError as e:
+ raise BraintreeException(DEFAULT_ERROR_MESSAGE) from e
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response["errors"])
diff --git a/saleor/payment/gateways/utils.py b/saleor/payment/gateways/utils.py
index 4f928466a3..1cdee97840 100644
--- a/saleor/payment/gateways/utils.py
+++ b/saleor/payment/gateways/utils.py
@@ -16,7 +16,8 @@ def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> list
currencies: list[str] = []
warnings.warn(
f"Supported currencies not configured for {gateway_name}, "
- "please configure supported currencies for this gateway."
+ "please configure supported currencies for this gateway.",
+ stacklevel=1,
)
else:
currencies = [c.strip() for c in supp_currencies.split(",")]
diff --git a/saleor/payment/migrations/0016_auto_20200423_0314.py b/saleor/payment/migrations/0016_auto_20200423_0314.py
index 360805a5e8..e1991c3254 100644
--- a/saleor/payment/migrations/0016_auto_20200423_0314.py
+++ b/saleor/payment/migrations/0016_auto_20200423_0314.py
@@ -15,9 +15,9 @@ def get_plugins():
def change_plugin_name_to_plugin_identifier(apps, schema_editor):
plugins = get_plugins()
- payment = apps.get_model("payment", "Payment")
+ Payment = apps.get_model("payment", "Payment")
- for payment in payment.objects.iterator():
+ for payment in Payment.objects.iterator():
gateway = payment.gateway
if gateway in plugins:
payment.gateway = plugins[gateway]
diff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.py
index 9524297a9b..c9fe7bc335 100644
--- a/saleor/payment/tests/test_gateway.py
+++ b/saleor/payment/tests/test_gateway.py
@@ -1371,7 +1371,7 @@ def test_payment_refund_or_void_no_payment(refund_mock, void_mock):
def test_payment_refund_or_void_refund_called(refund_mock, payment):
"""Test that refund is called when there is no matching transaction."""
# given
- payment.transactions.count() == 0
+ assert payment.transactions.count() == 0
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.save(update_fields=["charge_status"])
@@ -1484,7 +1484,7 @@ def test_payment_refund_or_void_void_called(void_mock, payment):
# given
payment.can_void = Mock(return_value=True)
assert payment.can_void() is True
- payment.transactions.count() == 0
+ assert payment.transactions.count() == 0
# when
gateway.payment_refund_or_void(
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index e3c6422d3e..c47469218d 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -532,8 +532,8 @@ def validate_gateway_response(response: GatewayResponse):
try:
json.dumps(response.raw_response, cls=DjangoJSONEncoder)
- except (TypeError, ValueError):
- raise GatewayError("Gateway response needs to be json serializable")
+ except (TypeError, ValueError) as e:
+ raise GatewayError("Gateway response needs to be json serializable") from e
@traced_atomic_transaction()
@@ -1608,8 +1608,8 @@ def handle_transaction_initialize_session(
"idempotency_key": idempotency_key,
},
)
- except IntegrityError:
- raise TransactionItemIdempotencyUniqueError()
+ except IntegrityError as e:
+ raise TransactionItemIdempotencyUniqueError() from e
session_data = TransactionSessionData(
transaction=transaction_item,
diff --git a/saleor/plugins/apps.py b/saleor/plugins/apps.py
index 82a5478342..cbcdddec11 100644
--- a/saleor/plugins/apps.py
+++ b/saleor/plugins/apps.py
@@ -23,7 +23,7 @@ class PluginConfig(AppConfig):
try:
plugin = import_string(plugin_path)
except ImportError as e:
- raise (ImportError(f"Failed to import plugin {plugin_path}: {e}"))
+ raise ImportError(f"Failed to import plugin {plugin_path}: {e}") from e
self.check_plugin_fields(["PLUGIN_ID"], plugin)
diff --git a/saleor/plugins/email_common.py b/saleor/plugins/email_common.py
index 819c9bc264..65052f3ebe 100644
--- a/saleor/plugins/email_common.py
+++ b/saleor/plugins/email_common.py
@@ -313,7 +313,7 @@ def validate_default_email_configuration(
)
for c in asdict(config).keys()
}
- )
+ ) from e
def validate_format_of_provided_templates(
diff --git a/saleor/plugins/openid_connect/plugin.py b/saleor/plugins/openid_connect/plugin.py
index 74c0c6ede7..3ef725fae9 100644
--- a/saleor/plugins/openid_connect/plugin.py
+++ b/saleor/plugins/openid_connect/plugin.py
@@ -266,11 +266,11 @@ class OpenIDConnectPlugin(BasePlugin):
try:
state_data = signing.loads(state)
- except signing.BadSignature:
+ except signing.BadSignature as e:
msg = "Bad signature"
raise ValidationError(
{"state": ValidationError(msg, code=PluginErrorCode.INVALID.value)}
- )
+ ) from e
redirect_uri = state_data.get("redirectUri")
if not redirect_uri:
@@ -283,14 +283,14 @@ class OpenIDConnectPlugin(BasePlugin):
token_data = self.oauth.fetch_token(
self.config.token_url, code=code, redirect_uri=redirect_uri
)
- except AuthlibBaseError as error:
+ except AuthlibBaseError as e:
raise ValidationError(
{
"code": ValidationError(
- error.description, code=PluginErrorCode.INVALID.value
+ e.description, code=PluginErrorCode.INVALID.value
)
}
- )
+ ) from e
try:
parsed_id_token = get_parsed_id_token(
@@ -303,7 +303,7 @@ class OpenIDConnectPlugin(BasePlugin):
except AuthenticationError as e:
raise ValidationError(
{"code": ValidationError(str(e), code=PluginErrorCode.INVALID.value)}
- )
+ ) from e
user_permissions = []
is_staff_user_email = self.is_staff_user_email(user)
@@ -398,7 +398,7 @@ class OpenIDConnectPlugin(BasePlugin):
token_endpoint,
refresh_token=saleor_refresh_token[OAUTH_TOKEN_REFRESH_FIELD],
)
- except (AuthlibBaseError, HTTPError):
+ except (AuthlibBaseError, HTTPError) as e:
logger.warning("Unable to refresh the token.", exc_info=True)
raise ValidationError(
{
@@ -407,7 +407,7 @@ class OpenIDConnectPlugin(BasePlugin):
code=error_code,
)
}
- )
+ ) from e
try:
parsed_id_token = get_parsed_id_token(
token_data, self.config.json_web_key_set_url
@@ -429,7 +429,7 @@ class OpenIDConnectPlugin(BasePlugin):
except AuthenticationError as e:
raise ValidationError(
{"refreshToken": ValidationError(str(e), code=error_code)}
- )
+ ) from e
def get_and_update_user_permissions(
self, user: User, use_scope_permissions: bool, scope: str
@@ -481,7 +481,7 @@ class OpenIDConnectPlugin(BasePlugin):
return previous_value
user.is_staff = False
except (ExpiredSignatureError, InvalidTokenError) as e:
- raise ValidationError({"token": e})
+ raise ValidationError({"token": e}) from e
permissions = payload.get(PERMISSIONS_FIELD)
if permissions:
user.is_staff = True
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index dde3fd5f45..2872d20269 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -72,17 +72,21 @@ def fetch_jwks(jwks_url) -> Optional[dict]:
response = HTTPClient.send_request("GET", jwks_url, allow_redirects=False)
response.raise_for_status()
jwks = response.json()
- except requests.exceptions.RequestException:
+ except requests.exceptions.RequestException as e:
logger.exception("Unable to fetch jwks from %s", jwks_url)
- raise AuthenticationError("Unable to finalize the authentication process.")
- except json.JSONDecodeError:
+ raise AuthenticationError(
+ "Unable to finalize the authentication process."
+ ) from e
+ except json.JSONDecodeError as e:
content = response.content if response else "Unable to find the response"
logger.exception(
"Unable to decode the response from auth service with jwks. "
"Response: %s",
content,
)
- raise AuthenticationError("Unable to finalize the authentication process.")
+ raise AuthenticationError(
+ "Unable to finalize the authentication process."
+ ) from e
keys = jwks.get("keys", [])
if not keys:
logger.warning("List of JWKS keys is empty")
@@ -377,12 +381,12 @@ def get_parsed_id_token(token_data, jwks_url) -> CodeIDToken:
decoded_token = get_decoded_token(id_token, jwks_url, CodeIDToken)
decoded_token.validate()
return decoded_token
- except DecodeError:
+ except DecodeError as e:
logger.warning("Unable to decode provided token", exc_info=True)
- raise AuthenticationError("Unable to decode provided token")
- except (JoseError, ValueError):
+ raise AuthenticationError("Unable to decode provided token") from e
+ except (JoseError, ValueError) as e:
logger.warning("Token validation failed", exc_info=True)
- raise AuthenticationError("Token validation failed")
+ raise AuthenticationError("Token validation failed") from e
def get_or_create_user_from_payload(
@@ -589,7 +593,7 @@ def validate_refresh_token(refresh_token, data):
try:
refresh_payload = jwt_decode(refresh_token, verify_expiration=True)
- except PyJWTError:
+ except PyJWTError as e:
raise ValidationError(
{
"refreshToken": ValidationError(
@@ -597,7 +601,7 @@ def validate_refresh_token(refresh_token, data):
code=PluginErrorCode.INVALID.value,
)
}
- )
+ ) from e
if not data.get("refreshToken"):
if not refresh_payload.get(CSRF_FIELD):
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index be0542cbfa..f423f4956f 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -75,7 +75,7 @@ def test_manager_with_default_configuration_for_channel_plugins(
manager.plugins_per_channel.keys()
)
- for channel_slug, plugins in manager.plugins_per_channel.items():
+ for _channel_slug, plugins in manager.plugins_per_channel.items():
assert len(plugins) == 2
assert all(
[
diff --git a/saleor/product/migrations/0183_calculate_discounted_prices.py b/saleor/product/migrations/0183_calculate_discounted_prices.py
index 002ab73734..8cdd980e67 100644
--- a/saleor/product/migrations/0183_calculate_discounted_prices.py
+++ b/saleor/product/migrations/0183_calculate_discounted_prices.py
@@ -289,9 +289,9 @@ def _get_product_to_variant_channel_listings_per_channel_map(
}
price_data = defaultdict(lambda: defaultdict(list))
- for variant_channel_listings in variant_channel_listings:
- product_id = variant_to_product_id[variant_channel_listings.variant_id]
- price_data[product_id][variant_channel_listings.channel_id].append(
+ for variant_channel_listing in variant_channel_listings:
+ product_id = variant_to_product_id[variant_channel_listing.variant_id]
+ price_data[product_id][variant_channel_listing.channel_id].append(
variant_channel_listings
)
return price_data
diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.py
index 693694fc2b..550bb3dd8a 100644
--- a/saleor/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/product/tests/test_product_minimal_variant_price.py
@@ -482,7 +482,7 @@ def test_management_commmand_update_all_products_discounted_price(
assert mock_update_discounted_prices_for_promotion.call_count == len(product_list)
call_args_list = mock_update_discounted_prices_for_promotion.call_args_list
- for (args, kwargs), product in zip(call_args_list, product_list):
+ for (args, _kwargs), product in zip(call_args_list, product_list):
assert len(args[0]) == 1
assert args[0][0].pk == product.pk
diff --git a/saleor/settings.py b/saleor/settings.py
index 01f32eb677..9bb9d94648 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -170,7 +170,10 @@ ENABLE_SSL: bool = get_bool_from_env("ENABLE_SSL", False)
PUBLIC_URL: Optional[str] = get_url_from_env("PUBLIC_URL", schemes=["http", "https"])
if PUBLIC_URL:
if os.environ.get("ENABLE_SSL") is not None:
- warnings.warn("ENABLE_SSL is ignored on URL generation if PUBLIC_URL is set.")
+ warnings.warn(
+ "ENABLE_SSL is ignored on URL generation if PUBLIC_URL is set.",
+ stacklevel=1,
+ )
ENABLE_SSL = urlparse(PUBLIC_URL).scheme.lower() == "https"
if ENABLE_SSL:
@@ -232,7 +235,9 @@ PASSWORD_HASHERS = [
]
if not SECRET_KEY and DEBUG:
- warnings.warn("SECRET_KEY not configured, using a random temporary key.")
+ warnings.warn(
+ "SECRET_KEY not configured, using a random temporary key.", stacklevel=1
+ )
SECRET_KEY = get_random_secret_key()
RSA_PRIVATE_KEY = os.environ.get("RSA_PRIVATE_KEY", None)
@@ -318,7 +323,7 @@ if ENABLE_DEBUG_TOOLBAR:
f"{exc} -- Install the missing dependencies by "
f"running `poetry install --no-root`"
)
- warnings.warn(msg)
+ warnings.warn(msg, stacklevel=1)
else:
INSTALLED_APPS += ["django.forms", "debug_toolbar", "graphiql_debug_toolbar"]
MIDDLEWARE.append("saleor.graphql.middleware.DebugToolbarMiddleware")
@@ -727,7 +732,8 @@ if OBSERVABILITY_ACTIVE:
if OBSERVABILITY_BUFFER_TIMEOUT < OBSERVABILITY_REPORT_PERIOD * 2:
warnings.warn(
"OBSERVABILITY_REPORT_PERIOD is too big compared to "
- "OBSERVABILITY_BUFFER_TIMEOUT. That can lead to a loss of events."
+ "OBSERVABILITY_BUFFER_TIMEOUT. That can lead to a loss of events.",
+ stacklevel=1,
)
# Change this value if your application is running behind a proxy,
diff --git a/saleor/site/tests/test_site_settings.py b/saleor/site/tests/test_site_settings.py
index 723cd2d858..31ba02db35 100644
--- a/saleor/site/tests/test_site_settings.py
+++ b/saleor/site/tests/test_site_settings.py
@@ -18,4 +18,4 @@ def test_site_settings_default_from_email(settings):
assert site.settings.default_from_email == settings.DEFAULT_FROM_EMAIL
settings.DEFAULT_FROM_EMAIL = None
with pytest.raises(ImproperlyConfigured):
- site.settings.default_from_email
+ _x = site.settings.default_from_email
diff --git a/saleor/tests/e2e/channel/utils/channel_create.py b/saleor/tests/e2e/channel/utils/channel_create.py
index 343d0ebfc9..64c19348b4 100644
--- a/saleor/tests/e2e/channel/utils/channel_create.py
+++ b/saleor/tests/e2e/channel/utils/channel_create.py
@@ -59,14 +59,17 @@ def create_channel(
country="US",
shipping_zones=None,
is_active=True,
- order_settings={},
- checkout_settings={},
+ order_settings=None,
+ checkout_settings=None,
):
if not warehouse_ids:
warehouse_ids = []
-
if slug is None:
slug = f"channel_slug_{uuid.uuid4()}"
+ if order_settings is None:
+ order_settings = {}
+ if checkout_settings is None:
+ checkout_settings = {}
variables = {
"input": {
diff --git a/saleor/tests/e2e/shop/utils/preparing_shop.py b/saleor/tests/e2e/shop/utils/preparing_shop.py
index 536fa11e45..7861559a4d 100644
--- a/saleor/tests/e2e/shop/utils/preparing_shop.py
+++ b/saleor/tests/e2e/shop/utils/preparing_shop.py
@@ -96,11 +96,11 @@ def prepare_shop(
}
)
- for shipping_zone in shipping_zone["shipping_methods"]:
+ for shipping_method in shipping_zone["shipping_methods"]:
created_shipping_method = create_shipping_method(
e2e_staff_api_client,
shipping_zone_id=created_shipping_zone["id"],
- name=shipping_zone.get("name"),
+ name=shipping_method.get("name"),
)
created_channels[channel_index]["shipping_zones"][shipping_zone_index][
@@ -111,7 +111,7 @@ def prepare_shop(
e2e_staff_api_client,
shipping_method_id=created_shipping_method["id"],
channel_id=created_channel["id"],
- add_channels=shipping_zone.get("add_channels", None),
+ add_channels=shipping_method.get("add_channels", None),
)
created_tax_classes = {}
tax_rates = {}
@@ -128,7 +128,7 @@ def prepare_shop(
tax_classes_result = create_and_update_tax_classes(
e2e_staff_api_client, tax_rates.values()
)
- for tax_type, tax_rate in tax_rates.items():
+ for tax_type, _tax_rate in tax_rates.items():
tax_class_id = tax_classes_result.get(tax_type, {}).get("id")
if tax_class_id:
created_tax_classes[f"{tax_type}_tax_class_id"] = tax_class_id
diff --git a/saleor/tests/e2e/shop/utils/shop_update_settings.py b/saleor/tests/e2e/shop/utils/shop_update_settings.py
index f082a2c1f6..b919d1a9ff 100644
--- a/saleor/tests/e2e/shop/utils/shop_update_settings.py
+++ b/saleor/tests/e2e/shop/utils/shop_update_settings.py
@@ -20,13 +20,15 @@ mutation ShopSettingsUpdate($input: ShopSettingsInput!) {
def update_shop_settings(
staff_api_client,
- input_data={
- "enableAccountConfirmationByEmail": True,
- "allowLoginWithoutConfirmation": False,
- "fulfillmentAutoApprove": False,
- "fulfillmentAllowUnpaid": False,
- },
+ input_data=None,
):
+ if input_data is None:
+ input_data = {
+ "enableAccountConfirmationByEmail": True,
+ "allowLoginWithoutConfirmation": False,
+ "fulfillmentAutoApprove": False,
+ "fulfillmentAllowUnpaid": False,
+ }
variables = {"input": input_data}
response = staff_api_client.post_graphql(SHOP_SETTING_UPDATE_MUTATION, variables)
diff --git a/saleor/tests/e2e/taxes/utils/tax_configuration_update.py b/saleor/tests/e2e/taxes/utils/tax_configuration_update.py
index 2199d98ee4..6edf111e07 100644
--- a/saleor/tests/e2e/taxes/utils/tax_configuration_update.py
+++ b/saleor/tests/e2e/taxes/utils/tax_configuration_update.py
@@ -40,9 +40,13 @@ def update_tax_configuration(
tax_calculation_strategy="FLAT_RATES",
display_gross_prices=True,
prices_entered_with_tax=True,
- update_countries_configuration=[],
- remove_countries_configuration=[],
+ update_countries_configuration=None,
+ remove_countries_configuration=None,
):
+ if remove_countries_configuration is None:
+ remove_countries_configuration = []
+ if update_countries_configuration is None:
+ update_countries_configuration = []
variables = {
"id": tax_config_id,
"input": {
diff --git a/saleor/tests/e2e/taxes/utils/tax_country_configuration_update.py b/saleor/tests/e2e/taxes/utils/tax_country_configuration_update.py
index ebc5c43828..f2fefd1a6c 100644
--- a/saleor/tests/e2e/taxes/utils/tax_country_configuration_update.py
+++ b/saleor/tests/e2e/taxes/utils/tax_country_configuration_update.py
@@ -36,8 +36,10 @@ mutation TaxCountryConfigurationUpdate($countryCode: CountryCode!,
def update_country_tax_rates(
staff_api_client,
country_code,
- update_tax_class_rates=[],
+ update_tax_class_rates=None,
):
+ if update_tax_class_rates is None:
+ update_tax_class_rates = []
variables = {
"countryCode": country_code,
"updateTaxClassRates": update_tax_class_rates,
diff --git a/saleor/tests/e2e/warehouse/utils/create_warehouse.py b/saleor/tests/e2e/warehouse/utils/create_warehouse.py
index ef9942f4cf..1fde92cc3f 100644
--- a/saleor/tests/e2e/warehouse/utils/create_warehouse.py
+++ b/saleor/tests/e2e/warehouse/utils/create_warehouse.py
@@ -36,9 +36,11 @@ mutation createWarehouse($input: WarehouseCreateInput!) {
def create_warehouse(
staff_api_client,
name="Test warehouse",
- slug=f"warehouse_slug_{uuid.uuid4()}",
+ slug=None,
address=DEFAULT_ADDRESS,
):
+ if slug is None:
+ slug = f"warehouse_slug_{uuid.uuid4()}"
variables = {
"input": {
"name": name,
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 1043c61458..572f688df5 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1433,12 +1433,16 @@ def order_generator(customer_user, channel_USD):
user=customer_user,
origin=OrderOrigin.CHECKOUT,
should_refresh_prices=False,
- metadata={"key": "value"},
- private_metadata={"secret_key": "secret_value"},
+ metadata=None,
+ private_metadata=None,
checkout_token="",
status=OrderStatus.UNFULFILLED,
search_vector_class=None,
):
+ if metadata is None:
+ metadata = {"key": "value"}
+ if private_metadata is None:
+ private_metadata = {"secret_key": "secret_value"}
order = Order.objects.create(
billing_address=billing_address,
channel=channel,
diff --git a/saleor/thumbnail/validators.py b/saleor/thumbnail/validators.py
index 42bc5f8e09..4894c2d9c0 100644
--- a/saleor/thumbnail/validators.py
+++ b/saleor/thumbnail/validators.py
@@ -31,7 +31,7 @@ def validate_image_exif(img: Image.Image, error_code: str):
"Invalid file. The following error was raised during the attempt "
f"of getting the exchangeable image file data: {str(e)}.",
code=error_code,
- )
+ ) from e
def validate_image_size(
@@ -68,6 +68,6 @@ def validate_icon_image(image_file, error_code: str):
"Invalid file. The following error was raised during the attempt "
f"of opening the file: {str(e)}",
code=error_code,
- )
+ ) from e
finally:
image_file.seek(file_pos)
diff --git a/saleor/urls.py b/saleor/urls.py
index 8cf6c64e51..eb01f36e46 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -63,7 +63,8 @@ if settings.DEBUG:
except ImportError:
warnings.warn(
"The debug toolbar was not installed. Ignore the error. \
- settings.py should already have warned the user about it."
+ settings.py should already have warned the user about it.",
+ stacklevel=1,
)
else:
urlpatterns += [
diff --git a/saleor/webhook/observability/buffers.py b/saleor/webhook/observability/buffers.py
index 5c22885137..4ed1d070bc 100644
--- a/saleor/webhook/observability/buffers.py
+++ b/saleor/webhook/observability/buffers.py
@@ -157,7 +157,7 @@ class RedisBuffer(BaseBuffer):
events = []
with self.client.pipeline(transaction=False) as pipe:
pipe.llen(key)
- for i in range(max(1, batch_size)):
+ for _i in range(max(1, batch_size)):
pipe.rpop(key)
result = pipe.execute()
size = result.pop(0)
diff --git a/saleor/webhook/observability/tests/test_buffer.py b/saleor/webhook/observability/tests/test_buffer.py
index 3c27d475f0..51bcd95681 100644
--- a/saleor/webhook/observability/tests/test_buffer.py
+++ b/saleor/webhook/observability/tests/test_buffer.py
@@ -51,7 +51,7 @@ def test_put_event(buffer, event_data):
def test_buffer_put_events_max_size(buffer, event_data):
- for i in range(MAX_SIZE * 2):
+ for _i in range(MAX_SIZE * 2):
buffer.put_event(event_data)
assert buffer.size() == MAX_SIZE
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index 12b9705271..c90f953e84 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -235,7 +235,7 @@ def send_webhook_using_aws_sqs(
with catch_duration_time() as duration:
try:
response = json.dumps(client.send_message(**message_kwargs))
- except (ClientError,) as e:
+ except ClientError as e:
return WebhookResponse(
content=str(e), status=EventDeliveryStatus.FAILED, duration=duration()
)