Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Handle invalid provider exception for media url in product bulk mutations (#18291)
Filip Owczarekbb2e88c7af0d
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.pyindex 0862246fc9..6a6052ac54 100644--- a/saleor/core/exceptions.py+++ b/saleor/core/exceptions.py@@ -23,6 +23,12 @@ class InsufficientStockData:warehouse_pk: UUID | None = None+class UnsupportedMediaProviderException(Exception):+ def __init__(self, message: str = "Unsupported media provider or incorrect URL."):+ self.message = message+ super().__init__(message)++class NonExistingCheckoutLines(Exception):def __init__(self, line_pks: set[UUID]):self.line_pks = line_pksdiff --git a/saleor/core/utils/validators.py b/saleor/core/utils/validators.pyindex d0ad766a7b..c2d3d5b604 100644--- a/saleor/core/utils/validators.py+++ b/saleor/core/utils/validators.py@@ -2,10 +2,9 @@ import datetimefrom typing import Anyimport micawber-from django.core.exceptions import ValidationErrorfrom ...product import ProductMediaTypes-from ...product.error_codes import ProductErrorCode+from ..exceptions import UnsupportedMediaProviderExceptionSUPPORTED_MEDIA_TYPES = {"photo": ProductMediaTypes.IMAGE,@@ -15,7 +14,7 @@ MEDIA_MAX_WIDTH = 1920MEDIA_MAX_HEIGHT = 1080-def get_oembed_data(url: str, field_name: str) -> tuple[dict[str, Any], str]:+def get_oembed_data(url: str) -> tuple[dict[str, Any], str]:"""Get the oembed data from URL or raise an ValidationError."""providers = micawber.bootstrap_basic()@@ -25,14 +24,7 @@ def get_oembed_data(url: str, field_name: str) -> tuple[dict[str, Any], str]:)return oembed_data, SUPPORTED_MEDIA_TYPES[oembed_data["type"]]except (micawber.exceptions.ProviderException, KeyError) as e:- raise ValidationError(- {- field_name: ValidationError(- "Unsupported media provider or incorrect URL.",- code=ProductErrorCode.UNSUPPORTED_MEDIA_PROVIDER.value,- )- }- ) from e+ raise UnsupportedMediaProviderException() from edef is_date_in_future(given_date):diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.pyindex be81782717..c401897aec 100644--- a/saleor/graphql/core/tests/test_core.py+++ b/saleor/graphql/core/tests/test_core.py@@ -10,6 +10,7 @@ from django.utils import timezonefrom graphene import InputFieldfrom micawber import ProviderException, ProviderRegistry+from ....core.exceptions import UnsupportedMediaProviderExceptionfrom ....core.utils.validators import get_oembed_datafrom ....product import ProductMediaTypesfrom ....product.models import Product, ProductChannelListing@@ -269,7 +270,7 @@ def test_requestor_is_superuser_for_app(app):],)def test_get_oembed_data(url, expected_media_type):- oembed_data, media_type = get_oembed_data(url, "media_url")+ oembed_data, media_type = get_oembed_data(url)assert oembed_data != {}assert media_type == expected_media_type@@ -289,9 +290,10 @@ def test_get_oembed_data(url, expected_media_type):def test_get_oembed_data_unsupported_media_provider(mocked_provider, url):mocked_provider.side_effect = ProviderException()with pytest.raises(- ValidationError, match="Unsupported media provider or incorrect URL."+ UnsupportedMediaProviderException,+ match="Unsupported media provider or incorrect URL.",):- get_oembed_data(url, "media_url")+ get_oembed_data(url)def test_add_hash_to_file_name(image, media_root):diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.pyindex 8d688a2c34..805613bd37 100644--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py@@ -9,6 +9,7 @@ from django.utils.text import slugifyfrom graphene.utils.str_converters import to_camel_casefrom text_unidecode import unidecode+from ....core.exceptions import UnsupportedMediaProviderExceptionfrom ....core.http_client import HTTPClientfrom ....core.tracing import traced_atomic_transactionfrom ....core.utils import prepare_unique_slug@@ -478,22 +479,46 @@ class ProductBulkCreate(BaseMutation):product_index, exc, index_error_map, f"media.{index}")continue- elif media_url and is_image_url(media_url):- try:- validate_image_url(- media_url, "media_url", ProductBulkCreateErrorCode.INVALID.value- )- except ValidationError as exc:- cls.add_indexes_to_errors(- product_index, exc, index_error_map, f"media.{index}"+ elif media_url:+ if is_image_url(media_url):+ try:+ validate_image_url(+ media_url,+ "media_url",+ ProductBulkCreateErrorCode.INVALID.value,+ )+ except ValidationError as exc:+ cls.add_indexes_to_errors(+ product_index, exc, index_error_map, f"media.{index}"+ )+ continue+ filename = get_filename_from_url(media_url)+ image_data = HTTPClient.send_request(+ "GET", media_url, stream=True, timeout=30, allow_redirects=False)- continue- filename = get_filename_from_url(media_url)- image_data = HTTPClient.send_request(- "GET", media_url, stream=True, timeout=30, allow_redirects=False- )- image_data = File(image_data.raw, filename)- media_input["image"] = image_data+ image_data = File(image_data.raw, filename)+ media_input["image"] = image_data+ else:+ try:+ oembed_data, supported_media_type = get_oembed_data(media_url)+ oembed_data["supported_media_type"] = supported_media_type+ except UnsupportedMediaProviderException as exc:+ validation_error = ValidationError(+ {+ "media_url": ValidationError(+ exc.message,+ code=ProductBulkCreateErrorCode.UNSUPPORTED_MEDIA_PROVIDER.value,+ )+ }+ )+ cls.add_indexes_to_errors(+ product_index,+ validation_error,+ index_error_map,+ f"media.{index}",+ )+ continue+ media_input["oembed_data"] = oembed_datamedia_to_create.append(media_input)@@ -881,7 +906,7 @@ class ProductBulkCreate(BaseMutation):def prepare_media(cls, info, product, media_inputs, media_to_create):for media_input in media_inputs:alt = media_input.get("alt", "")- media_url = media_input.get("media_url")+if img_data := media_input.get("image"):media_to_create.append(models.ProductMedia(@@ -891,18 +916,16 @@ class ProductBulkCreate(BaseMutation):type=ProductMediaTypes.IMAGE,))- if media_url:- if not is_image_url(media_url):- oembed_data, media_type = get_oembed_data(media_url, "media_url")- media_to_create.append(- models.ProductMedia(- external_url=oembed_data["url"],- alt=oembed_data.get("title", alt),- product=product,- type=media_type,- oembed_data=oembed_data,- )+ if oembed_data := media_input.get("oembed_data"):+ media_to_create.append(+ models.ProductMedia(+ external_url=oembed_data["url"],+ alt=oembed_data.get("title", alt),+ product=product,+ type=oembed_data["supported_media_type"],+ oembed_data=oembed_data,)+ )@classmethoddef post_save_actions(cls, info, products, variants, channels):diff --git a/saleor/graphql/product/mutations/product/product_media_create.py b/saleor/graphql/product/mutations/product/product_media_create.pyindex 0f9df07e26..afb3eaffa0 100644--- a/saleor/graphql/product/mutations/product/product_media_create.py+++ b/saleor/graphql/product/mutations/product/product_media_create.py@@ -2,6 +2,7 @@ import graphenefrom django.core.exceptions import ValidationErrorfrom django.core.files import File+from .....core.exceptions import UnsupportedMediaProviderExceptionfrom .....core.http_client import HTTPClientfrom .....core.utils.validators import get_oembed_datafrom .....permission.enums import ProductPermissions@@ -132,7 +133,19 @@ class ProductMediaCreate(BaseMutation):type=ProductMediaTypes.IMAGE,)else:- oembed_data, media_type = get_oembed_data(media_url, "media_url")+ try:+ oembed_data, media_type = get_oembed_data(+ media_url,+ )+ except UnsupportedMediaProviderException as exc:+ raise ValidationError(+ {+ "media_url": ValidationError(+ exc.message,+ code=ProductErrorCode.UNSUPPORTED_MEDIA_PROVIDER.value,+ )+ }+ ) from excmedia = product.media.create(external_url=oembed_data["url"],alt=oembed_data.get("title", alt),diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex a351f1d2e6..bcb4fcfddb 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -12,6 +12,7 @@ from .....attribute.tests.model_helpers import (get_product_attribute_values,get_product_attributes,)+from .....core.exceptions import UnsupportedMediaProviderExceptionfrom .....discount.utils.promotion import get_active_catalogue_promotion_rulesfrom .....product.error_codes import ProductBulkCreateErrorCodefrom .....product.models import Product@@ -1076,6 +1077,69 @@ def test_product_bulk_create_with_media_with_media_url()+@patch(+ "saleor.graphql.product.bulk_mutations.product_bulk_create.is_image_url",+ return_value=False,+)+@patch(+ "saleor.graphql.product.bulk_mutations.product_bulk_create.get_oembed_data",+)+def test_product_bulk_create_with_media_with_media_url_invalid_provider(+ mocked_get_oembed_data,+ _mocked_is_image_url,+ staff_api_client,+ product_type,+ permission_manage_products,+):+ # given+ mocked_get_oembed_data.side_effect = UnsupportedMediaProviderException()++ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)+ product_name_1 = "test name 1"+ product_name_2 = "test name 2"++ alt = "Invalid_image"+ url = "https://www.example.com/image.webp"++ media = {+ "alt": alt,+ "mediaUrl": url,+ }++ products = [+ {+ "productType": product_type_id,+ "name": product_name_1,+ },+ {+ "productType": product_type_id,+ "name": product_name_2,+ "media": [media],+ },+ ]++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(+ PRODUCT_BULK_CREATE_MUTATION,+ {"products": products, "errorPolicy": ErrorPolicyEnum.REJECT_FAILED_ROWS.name},+ )+ content = get_graphql_content(response)+ data = content["data"]["productBulkCreate"]++ # then+ # Only first product should be created to respect REJECT_FAILED_ROWS policy+ assert data["count"] == 1+ # Second product should have error related to unsupported media provider+ errors = data["results"][1]["errors"]+ assert (+ errors[0]["code"] == ProductBulkCreateErrorCode.UNSUPPORTED_MEDIA_PROVIDER.name+ )+ assert errors[0]["path"] == "media.0.mediaUrl"+ assert errors[0]["message"] == "Unsupported media provider or incorrect URL."+ assert len(errors) == 1++@patch("saleor.graphql.core.validators.file.is_supported_image_mimetype",return_value=False,