Skip to content

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

Fix risk of updating the already deleted checkout line (#16997)

Maciej Korycinskifb2614e245b8
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 395805448d..1e33713b81 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -16,7 +16,7 @@ from prices import Money
from ..account.models import User
from ..checkout.fetch import update_delivery_method_lists_for_checkout_info
from ..core.db.connection import allow_writer
-from ..core.exceptions import ProductNotPublished
+from ..core.exceptions import NonExistingCheckoutLines, ProductNotPublished
from ..core.taxes import zero_taxed_money
from ..core.utils.promo_code import (
InvalidPromoCode,
@@ -117,14 +117,17 @@ def invalidate_checkout_prices(
return updated_fields
+def checkout_lines_qs_select_for_update():
+ return CheckoutLine.objects.order_by("id").select_for_update(of=(["self"]))
+
+
def checkout_lines_bulk_update(
lines_to_update: list["CheckoutLine"], fields_to_update: list[str]
):
"""Bulk update on CheckoutLines with lock applied on them."""
with transaction.atomic():
_locked_lines = list(
- CheckoutLine.objects.order_by("id")
- .select_for_update()
+ checkout_lines_qs_select_for_update()
.filter(id__in=[line.id for line in lines_to_update])
.values_list("id", flat=True)
)
@@ -135,8 +138,7 @@ def checkout_lines_bulk_delete(line_pks_to_delete: list[UUID]):
"""Delete CheckoutLines with lock applied on them."""
with transaction.atomic():
CheckoutLine.objects.filter(
- id__in=CheckoutLine.objects.order_by("id")
- .select_for_update()
+ id__in=checkout_lines_qs_select_for_update()
.filter(pk__in=line_pks_to_delete)
.values_list("id", flat=True)
).delete()
@@ -286,78 +288,92 @@ def add_variants_to_checkout(
replace=False,
replace_reservations=False,
reservation_length: Optional[int] = None,
+ raise_error_for_missing_lines=False,
):
"""Add variants to checkout.
If a variant is not placed in checkout, a new checkout line will be created.
If quantity is set to 0, checkout line will be deleted.
Otherwise, quantity will be added or replaced (if replace argument is True).
+ When `raise_error_for_missing_lines` is set to True, raise error when any line from
+ the input is not assigned to provided checkout.
"""
country_code = checkout.get_country()
-
- checkout_lines = checkout.lines.select_related("variant")
- lines_by_id = {str(line.pk): line for line in checkout_lines}
- variants_map = {str(variant.pk): variant for variant in variants}
-
- new_variant_ids = set()
- for line_data in checkout_lines_data:
- if not line_data.line_id and line_data.variant_id:
- new_variant_ids.add(line_data.variant_id)
-
- new_variant_listing_map = {
- listing.variant_id: listing
- for listing in product_models.ProductVariantChannelListing.objects.filter(
- channel_id=channel.id, variant_id__in=new_variant_ids
+ with transaction.atomic():
+ checkout_lines = list(
+ checkout_lines_qs_select_for_update()
+ .select_related("variant")
+ .filter(checkout_id=checkout.pk)
)
- }
+ lines_by_id = {str(line.pk): line for line in checkout_lines}
+ variants_map = {str(variant.pk): variant for variant in variants}
+
+ new_variant_ids = set()
+ non_existing_line_ids = set()
+ for line_data in checkout_lines_data:
+ if line_data.line_id and line_data.line_id not in lines_by_id:
+ non_existing_line_ids.add(line_data.line_id)
+ new_variant_ids.add(line_data.variant_id)
+ elif not line_data.line_id and line_data.variant_id:
+ new_variant_ids.add(line_data.variant_id)
+
+ if raise_error_for_missing_lines and non_existing_line_ids:
+ raise NonExistingCheckoutLines(non_existing_line_ids)
+
+ new_variant_listing_map = {
+ listing.variant_id: listing
+ for listing in product_models.ProductVariantChannelListing.objects.filter(
+ channel_id=channel.id, variant_id__in=new_variant_ids
+ )
+ }
- to_create: list[CheckoutLine] = []
- to_update: list[CheckoutLine] = []
- to_delete: list[CheckoutLine] = []
+ to_create: list[CheckoutLine] = []
+ to_update: list[CheckoutLine] = []
+ to_delete: list[CheckoutLine] = []
- for line_data in checkout_lines_data:
- line = lines_by_id.get(line_data.line_id) if line_data.line_id else None
- if line:
- _append_line_to_update(to_update, to_delete, line_data, replace, line)
- _append_line_to_delete(to_delete, line_data, line)
- else:
- variant = variants_map[line_data.variant_id]
- _append_line_to_create(
- to_create, checkout, variant, line_data, line, new_variant_listing_map
- )
+ for line_data in checkout_lines_data:
+ line = lines_by_id.get(line_data.line_id) if line_data.line_id else None
+ if line:
+ _append_line_to_update(to_update, to_delete, line_data, replace, line)
+ _append_line_to_delete(to_delete, line_data, line)
+ else:
+ variant = variants_map[line_data.variant_id]
+ _append_line_to_create(
+ to_create, checkout, variant, line_data, new_variant_listing_map
+ )
- if to_delete:
- checkout_lines_bulk_delete([line.pk for line in to_delete])
+ if to_delete:
+ checkout_lines_bulk_delete([line.pk for line in to_delete])
- if to_update:
- checkout_lines_bulk_update(
- to_update, ["quantity", "price_override", "metadata"]
- )
+ if to_update:
+ checkout_lines_bulk_update(
+ to_update, ["quantity", "price_override", "metadata"]
+ )
- if to_create:
- CheckoutLine.objects.bulk_create(to_create)
-
- to_reserve = to_create + to_update
-
- if reservation_length and to_reserve:
- updated_lines_ids = [line.pk for line in to_reserve + to_delete]
-
- # Validation for stock reservation should be performed on new and updated lines.
- # For already existing lines only reserved_until should be updated.
- lines_to_update_reservation_time = []
- for line in checkout_lines:
- if line.pk not in updated_lines_ids:
- lines_to_update_reservation_time.append(line)
-
- reserve_stocks_and_preorders(
- to_reserve,
- lines_to_update_reservation_time,
- variants,
- country_code,
- channel,
- reservation_length,
- replace=replace_reservations,
- )
+ if to_create:
+ CheckoutLine.objects.bulk_create(to_create)
+
+ to_reserve = to_create + to_update
+
+ if reservation_length and to_reserve:
+ updated_lines_ids = [line.pk for line in to_reserve + to_delete]
+
+ # Validation for stock reservation should be performed on new and updated lines.
+ # For already existing lines only reserved_until should be updated.
+ lines_to_update_reservation_time = []
+ for line in checkout_lines:
+ if line.pk not in updated_lines_ids:
+ lines_to_update_reservation_time.append(line)
+
+ reserve_stocks_and_preorders(
+ to_reserve,
+ lines_to_update_reservation_time,
+ variants,
+ country_code,
+ channel,
+ reservation_length,
+ replace=replace_reservations,
+ )
return checkout
@@ -399,27 +415,25 @@ def _append_line_to_create(
checkout,
variant,
line_data,
- line,
new_variant_listing_map: dict[int, "product_models.ProductVariantChannelListing"],
):
- if line is None:
- if line_data.quantity > 0:
- variant_price_amount = variant.get_base_price(
- new_variant_listing_map.get(variant.id), line_data.custom_price
- ).amount
- checkout_line = CheckoutLine(
- checkout=checkout,
- variant=variant,
- quantity=line_data.quantity,
- currency=checkout.currency,
- price_override=line_data.custom_price,
- undiscounted_unit_price_amount=variant_price_amount,
+ if line_data.quantity > 0:
+ variant_price_amount = variant.get_base_price(
+ new_variant_listing_map.get(variant.id), line_data.custom_price
+ ).amount
+ checkout_line = CheckoutLine(
+ checkout=checkout,
+ variant=variant,
+ quantity=line_data.quantity,
+ currency=checkout.currency,
+ price_override=line_data.custom_price,
+ undiscounted_unit_price_amount=variant_price_amount,
+ )
+ if line_data.metadata_list:
+ checkout_line.store_value_in_metadata(
+ {data.key: data.value for data in line_data.metadata_list}
)
- if line_data.metadata_list:
- checkout_line.store_value_in_metadata(
- {data.key: data.value for data in line_data.metadata_list}
- )
- to_create.append(checkout_line)
+ to_create.append(checkout_line)
def _check_new_checkout_address(checkout, address, address_type):
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.py
index 849d15c557..d77b4a2bbf 100644
--- a/saleor/core/exceptions.py
+++ b/saleor/core/exceptions.py
@@ -23,6 +23,12 @@ class InsufficientStockData:
warehouse_pk: Union[UUID, None] = None
+class NonExistingCheckoutLines(Exception):
+ def __init__(self, line_pks: set[UUID]):
+ self.line_pks = line_pks
+ super().__init__("Checkout lines don't exist.")
+
+
class InsufficientStock(Exception):
def __init__(self, items: list[InsufficientStockData]):
details = [str(item.variant or item.order_line) for item in items]
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.py
index e92b553720..3d4828c15d 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py
@@ -105,6 +105,44 @@ class CheckoutLinesAdd(BaseMutation):
check_reservations=is_reservation_enabled(site.settings),
)
+ @classmethod
+ def process_lines_input(
+ cls,
+ info,
+ checkout,
+ variants,
+ checkout_lines_data,
+ checkout_info,
+ replace=False,
+ raise_error_for_missing_lines=False,
+ ):
+ if variants and checkout_lines_data:
+ site = get_site_promise(info.context).get()
+ checkout = add_variants_to_checkout(
+ checkout,
+ variants,
+ checkout_lines_data,
+ checkout_info.channel,
+ replace=replace,
+ replace_reservations=True,
+ reservation_length=get_reservation_length(
+ site=site, user=info.context.user
+ ),
+ raise_error_for_missing_lines=raise_error_for_missing_lines,
+ )
+
+ lines, _ = fetch_checkout_lines(checkout)
+ shipping_channel_listings = checkout.channel.shipping_method_listings.all()
+ update_delivery_method_lists_for_checkout_info(
+ checkout_info=checkout_info,
+ shipping_method=checkout_info.checkout.shipping_method,
+ collection_point=checkout_info.checkout.collection_point,
+ shipping_address=checkout_info.shipping_address,
+ lines=lines,
+ shipping_channel_listings=shipping_channel_listings,
+ )
+ return lines
+
@classmethod
def clean_input(
cls,
@@ -114,8 +152,6 @@ class CheckoutLinesAdd(BaseMutation):
checkout_lines_data,
checkout_info,
lines,
- manager,
- replace,
):
channel_slug = checkout_info.channel.slug
@@ -134,7 +170,6 @@ class CheckoutLinesAdd(BaseMutation):
for variant, line_data in zip(variants, checkout_lines_data)
if line_data.quantity_to_update and line_data.quantity != 0
}
-
# validate variant only when line quantity is bigger than 0
if variants_ids_to_validate:
validate_variants_available_for_purchase(
@@ -149,32 +184,6 @@ class CheckoutLinesAdd(BaseMutation):
variants_ids_to_validate, checkout.channel_id
)
- if variants and checkout_lines_data:
- site = get_site_promise(info.context).get()
- checkout = add_variants_to_checkout(
- checkout,
- variants,
- checkout_lines_data,
- checkout_info.channel,
- replace=replace,
- replace_reservations=True,
- reservation_length=get_reservation_length(
- site=site, user=info.context.user
- ),
- )
-
- lines, _ = fetch_checkout_lines(checkout)
- shipping_channel_listings = checkout.channel.shipping_method_listings.all()
- update_delivery_method_lists_for_checkout_info(
- checkout_info=checkout_info,
- shipping_method=checkout_info.checkout.shipping_method,
- collection_point=checkout_info.checkout.collection_point,
- shipping_address=checkout_info.shipping_address,
- lines=lines,
- shipping_channel_listings=shipping_channel_listings,
- )
- return lines
-
@classmethod
def perform_mutation( # type: ignore[override]
cls,
@@ -186,7 +195,6 @@ class CheckoutLinesAdd(BaseMutation):
checkout_id=None,
token=None,
id=None,
- replace=False,
):
app = get_app_promise(info.context).get()
check_permissions_for_custom_prices(app, lines)
@@ -202,15 +210,20 @@ class CheckoutLinesAdd(BaseMutation):
checkout, skip_lines_with_unavailable_variants=False
)
input_lines_data = cls._get_grouped_lines_data(lines, existing_lines_info)
- lines = cls.clean_input(
+ cls.clean_input(
info,
checkout,
variants,
input_lines_data,
checkout_info,
existing_lines_info,
- manager,
- replace,
+ )
+ lines = cls.process_lines_input(
+ info,
+ checkout,
+ variants,
+ input_lines_data,
+ checkout_info,
)
update_checkout_external_shipping_method_if_invalid(checkout_info, lines)
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.py
index 063bf1c65c..b12363bc94 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py
@@ -3,14 +3,13 @@ from django.forms import ValidationError
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import CheckoutLineInfo
+from ....core.exceptions import NonExistingCheckoutLines
from ....warehouse.reservations import is_reservation_enabled
from ....webhook.event_types import WebhookEventAsyncType
from ...app.dataloaders import get_app_promise
from ...checkout.types import CheckoutLine
from ...core import ResolveInfo
-from ...core.descriptions import (
- DEPRECATED_IN_3X_INPUT,
-)
+from ...core.descriptions import DEPRECATED_IN_3X_INPUT
from ...core.doc_category import DOC_CATEGORY_CHECKOUT
from ...core.scalars import UUID, PositiveDecimal
from ...core.types import BaseInputObjectType, CheckoutError, NonNullList
@@ -18,6 +17,7 @@ from ...core.utils import WebhookEventInfo
from ...core.validators import validate_one_of_args_is_in_mutation
from ...product.types import ProductVariant
from ...site.dataloaders import get_site_promise
+from ...utils import ERROR_COULD_NO_RESOLVE_GLOBAL_ID
from ..types import Checkout
from .checkout_lines_add import CheckoutLinesAdd
from .utils import (
@@ -135,8 +135,6 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):
checkout_lines_data,
checkout_info,
lines_info,
- manager,
- replace,
):
app = get_app_promise(info.context).get()
# if the requestor is not app, the quantity is required for all lines
@@ -162,10 +160,47 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):
checkout_lines_data,
checkout_info,
lines_info,
- manager,
- replace,
)
+ @classmethod
+ def process_lines_input(
+ cls,
+ info,
+ checkout,
+ variants,
+ checkout_lines_data,
+ checkout_info,
+ replace=False,
+ raise_error_for_missing_lines=False,
+ ):
+ try:
+ return super().process_lines_input(
+ info,
+ checkout,
+ variants,
+ checkout_lines_data,
+ checkout_info,
+ replace=True,
+ # set to true, as during the update we want to be sure that any deleted line
+ # in the meantime will raise an exception instead of creating the new line.
+ raise_error_for_missing_lines=True,
+ )
+ except NonExistingCheckoutLines as e:
+ graphql_ids = [
+ graphene.Node.to_global_id("CheckoutLine", line_id)
+ for line_id in e.line_pks
+ ]
+ raise ValidationError(
+ {
+ "line_id": ValidationError(
+ ERROR_COULD_NO_RESOLVE_GLOBAL_ID % graphql_ids,
+ # keep the same code as we return when fetching the lines from the
+ # input.
+ code=CheckoutErrorCode.GRAPHQL_ERROR.value,
+ )
+ }
+ ) from e
+
@classmethod
def perform_mutation( # type: ignore[override]
cls, root, info: ResolveInfo, /, *, lines, checkout_id=None, token=None, id=None
@@ -185,7 +220,6 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):
checkout_id=checkout_id,
token=token,
id=id,
- replace=True,
)
@classmethod
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 7e09914716..ad5b2e9df0 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -417,7 +417,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(80):
+ with django_assert_num_queries(82):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -435,7 +435,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(80):
+ with django_assert_num_queries(82):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -567,7 +567,7 @@ def test_create_checkout_with_order_promotion(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(85):
+ with django_assert_num_queries(87):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
@@ -823,7 +823,7 @@ def test_update_checkout_lines_with_reservations(
)
user_api_client.ensure_access_token()
- with django_assert_num_queries(103):
+ with django_assert_num_queries(105):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -837,7 +837,7 @@ def test_update_checkout_lines_with_reservations(
assert not data["errors"]
# Updating multiple lines in checkout has same query count as updating one
- with django_assert_num_queries(103):
+ with django_assert_num_queries(105):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -1083,7 +1083,7 @@ def test_add_checkout_lines_with_reservations(
user_api_client.ensure_access_token()
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(100):
+ with django_assert_num_queries(102):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -1096,7 +1096,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(100):
+ with django_assert_num_queries(102):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
@@ -1147,7 +1147,7 @@ def test_add_checkout_lines_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(92):
+ with django_assert_num_queries(94):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1233,7 +1233,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(92):
+ with django_assert_num_queries(94):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1269,7 +1269,7 @@ def test_add_checkout_lines_order_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(95):
+ with django_assert_num_queries(97):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1304,7 +1304,7 @@ def test_add_checkout_lines_gift_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(121):
+ with django_assert_num_queries(123):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index af045450ba..ea3b6c46be 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -12,9 +12,10 @@ from prices import Money
from .....checkout.actions import call_checkout_info_event
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.models import Checkout
+from .....checkout.models import Checkout, CheckoutLine
from .....checkout.utils import (
PRIVATE_META_APP_SHIPPING_ID,
+ add_variants_to_checkout,
calculate_checkout_quantity,
invalidate_checkout,
recalculate_checkout_discount,
@@ -1932,3 +1933,42 @@ def test_checkout_lines_add_triggers_webhooks(
assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
assert tax_delivery.webhook_id == tax_webhook.id
+
+
+def test_checkout_lines_add_when_line_deleted(user_api_client, checkout_with_item):
+ # given
+ checkout = checkout_with_item
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ assert calculate_checkout_quantity(lines) == 3
+ line = checkout.lines.first()
+
+ db_variant_id = line.variant_id
+ variant_id = graphene.Node.to_global_id("ProductVariant", db_variant_id)
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "lines": [{"variantId": variant_id, "quantity": 2}],
+ }
+
+ def add_variants_to_checkout_wrapper(*args, **kwargs):
+ CheckoutLine.objects.filter(id=line.pk).delete()
+ return add_variants_to_checkout(*args, **kwargs)
+
+ # when
+ with mock.patch(
+ "saleor.graphql.checkout.mutations.checkout_lines_add.add_variants_to_checkout",
+ wraps=add_variants_to_checkout_wrapper,
+ ):
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ newly_created_checkout_line = checkout.lines.filter(
+ variant_id=db_variant_id
+ ).first()
+ assert newly_created_checkout_line
+ assert newly_created_checkout_line.id != line.id
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index 6d24ad2b12..fef400301d 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -14,6 +14,7 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
from .....checkout.utils import (
add_variant_to_checkout,
+ add_variants_to_checkout,
calculate_checkout_quantity,
invalidate_checkout,
)
@@ -1540,3 +1541,41 @@ def test_checkout_lines_update_triggers_webhooks(
assert WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES in sync_deliveries
tax_delivery = sync_deliveries[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES]
assert tax_delivery.webhook_id == tax_webhook.id
+
+
+def test_checkout_lines_update_when_line_deleted(user_api_client, checkout_with_item):
+ # given
+ checkout = checkout_with_item
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ assert calculate_checkout_quantity(lines) == 3
+ line = checkout.lines.first()
+
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "lines": [{"lineId": line_id, "quantity": 1}],
+ }
+
+ def add_variants_to_checkout_wrapper(*args, **kwargs):
+ CheckoutLine.objects.filter(id=line.pk).delete()
+ return add_variants_to_checkout(*args, **kwargs)
+
+ # when
+ with mock.patch(
+ "saleor.graphql.checkout.mutations.checkout_lines_add.add_variants_to_checkout",
+ wraps=add_variants_to_checkout_wrapper,
+ ):
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_UPDATE, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesUpdate"]
+ assert data["errors"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "lineId"
+ assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name