Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Separate checkout mutations per file (#10085)
Maciej Korycinski3af968e77782
diff --git a/saleor/graphql/checkout/tests/mutations/checkout_email_update.py b/saleor/graphql/checkout/tests/mutations/checkout_email_update.pynew file mode 100644index 0000000000..fb2face4f1--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/checkout_email_update.py@@ -0,0 +1,58 @@+from .....checkout.error_codes import CheckoutErrorCode+from ....core.utils import to_global_id_or_none+from ....tests.utils import get_graphql_content++CHECKOUT_EMAIL_UPDATE_MUTATION = """+ mutation checkoutEmailUpdate($id: ID, $email: String!) {+ checkoutEmailUpdate(id: $id, email: $email) {+ checkout {+ id,+ },+ errors {+ field,+ message+ }+ errors {+ field,+ message+ code+ }+ }+ }+"""+++def test_checkout_email_update(user_api_client, checkout_with_item):+ checkout = checkout_with_item+ checkout.email = None+ checkout.save(update_fields=["email"])+ previous_last_change = checkout.last_change++ email = "[email protected]"+ variables = {"id": to_global_id_or_none(checkout), "email": email}++ response = user_api_client.post_graphql(CHECKOUT_EMAIL_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutEmailUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.email == email+ assert checkout.last_change != previous_last_change+++def test_checkout_email_update_validation(user_api_client, checkout_with_item):+ variables = {"id": to_global_id_or_none(checkout_with_item), "email": ""}++ response = user_api_client.post_graphql(CHECKOUT_EMAIL_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ previous_last_change = checkout_with_item.last_change++ errors = content["data"]["checkoutEmailUpdate"]["errors"]+ assert errors+ assert errors[0]["field"] == "email"+ assert errors[0]["message"] == "This field cannot be blank."++ checkout_errors = content["data"]["checkoutEmailUpdate"]["errors"]+ assert checkout_errors[0]["code"] == CheckoutErrorCode.REQUIRED.name+ assert checkout_with_item.last_change == previous_last_changediff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.pynew file mode 100644index 0000000000..630ae89d81--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py@@ -0,0 +1,974 @@+from datetime import date, timedelta+from decimal import Decimal+from unittest import mock++import graphene+import pytest+from prices import Money++from .....checkout import calculations+from .....checkout.error_codes import CheckoutErrorCode+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from .....checkout.utils import add_variant_to_checkout, set_external_shipping_id+from .....core.taxes import TaxedMoney+from .....discount import VoucherType+from .....plugins.manager import get_plugins_manager+from .....warehouse.models import Stock+from ....core.utils import to_global_id_or_none+from ....tests.utils import get_graphql_content++MUTATION_CHECKOUT_ADD_PROMO_CODE = """+ mutation($id: ID, $promoCode: String!) {+ checkoutAddPromoCode(+ id: $id, promoCode: $promoCode) {+ errors {+ field+ message+ code+ }+ checkout {+ id+ token+ voucherCode+ discount {+ amount+ }+ giftCards {+ id+ last4CodeChars+ }+ totalPrice {+ gross {+ amount+ }+ }+ availableShippingMethods {+ id+ price {+ amount+ }+ }+ shippingMethod {+ id+ price {+ amount+ }+ }+ }+ }+ }+"""+++def _mutate_checkout_add_promo_code(client, variables):+ response = client.post_graphql(MUTATION_CHECKOUT_ADD_PROMO_CODE, variables)+ content = get_graphql_content(response)+ return content["data"]["checkoutAddPromoCode"]+++def test_checkout_add_voucher_for_entire_order(api_client, checkout_with_item, voucher):+ # given+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }+ assert voucher.type == VoucherType.ENTIRE_ORDER+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)+ taxed_total = calculations.checkout_total(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout_with_item.shipping_address,+ discounts=[],+ )++ # when+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # then+ checkout_with_item.refresh_from_db()+ assert not data["errors"]+ checkout_data = data["checkout"]+ total_price_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]+ assert (+ total_price_gross_amount+ == taxed_total.gross.amount - checkout_with_item.discount_amount+ )+++def test_checkout_add_voucher_code_by_token(api_client, checkout_with_item, voucher):+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert data["checkout"]["voucherCode"] == voucher.code+++def test_checkout_add_already_applied_voucher_for_entire_order(+ api_client, checkout_with_item, voucher+):+ # given+ variant = checkout_with_item.lines.first().variant+ channel = checkout_with_item.channel+ channel_listing = variant.channel_listings.get(channel=channel)+ net = (+ variant.get_price(+ variant.product, [], checkout_with_item.channel, channel_listing+ )+ * checkout_with_item.lines.first().quantity+ )++ voucher_channel_listing = voucher.channel_listings.get(channel=channel)+ voucher_channel_listing.discount_value = net.amount+ voucher_channel_listing.save(update_fields=["discount_value"])++ checkout_with_item.voucher_code = voucher.code+ checkout_with_item.discount_amount = net.amount+ checkout_with_item.save()++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }+ assert voucher.type == VoucherType.ENTIRE_ORDER++ # when+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # then+ checkout_with_item.refresh_from_db()+ assert not data["errors"]+ checkout_data = data["checkout"]+ total_price_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]+ assert total_price_gross_amount == 0+ assert checkout_data["discount"]["amount"] == net.amount++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_checkout_add_voucher_code_by_token_with_external_shipment(+ mock_send_request,+ api_client,+ checkout_with_item,+ voucher,+ shipping_app,+ address,+ settings,+):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ response_method_id = "abcd"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ mock_send_request.return_value = mock_json_response++ external_shipping_method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ checkout = checkout_with_item+ checkout.shipping_address = address+ set_external_shipping_id(checkout, external_shipping_method_id)+ checkout.save(update_fields=["shipping_address", "private_metadata"])++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert data["checkout"]["voucherCode"] == voucher.code+ assert data["checkout"]["shippingMethod"]["id"] == external_shipping_method_id+++def test_checkout_add_voucher_code_with_display_gross_prices(+ api_client, checkout_with_item, voucher, site_settings, monkeypatch+):+ site_settings.display_gross_prices = True+ site_settings.save()++ previous_checkout_last_change = checkout_with_item.last_change++ voucher = voucher+ voucher_channel_listing = voucher.channel_listings.first()+ voucher_channel_listing.min_spent_amount = 100+ voucher_channel_listing.save()++ monkeypatch.setattr(+ "saleor.checkout.utils.base_calculations.base_checkout_lines_total",+ lambda checkout_lines, channel, currency, discounts: TaxedMoney(+ Money(95, "USD"), Money(100, "USD")+ ),+ )++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert data["checkout"]["voucherCode"] == voucher.code+ checkout_with_item.refresh_from_db()+ assert checkout_with_item.last_change != previous_checkout_last_change+++def test_checkout_add_voucher_code_without_display_gross_prices(+ api_client, checkout_with_item, voucher, site_settings, monkeypatch+):+ site_settings.display_gross_prices = False+ site_settings.save()++ previous_checkout_last_change = checkout_with_item.last_change++ voucher = voucher+ voucher_channel_listing = voucher.channel_listings.first()+ voucher_channel_listing.min_spent_amount = 100+ voucher_channel_listing.save()++ monkeypatch.setattr(+ "saleor.checkout.utils.base_calculations.base_checkout_lines_total",+ lambda checkout_lines, channel, currency, discounts: TaxedMoney(+ Money(95, "USD"), Money(100, "USD")+ ),+ )++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert data["errors"][0]["code"] == CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.name+ assert data["errors"][0]["field"] == "promoCode"++ checkout_with_item.refresh_from_db()+ assert checkout_with_item.last_change == previous_checkout_last_change+++def test_checkout_add_voucher_code_variant_unavailable(+ api_client, checkout_with_item, voucher+):+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }+ checkout_with_item.lines.first().variant.channel_listings.filter(+ channel=checkout_with_item.channel+ ).delete()+ data = _mutate_checkout_add_promo_code(api_client, variables)++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name+ assert errors[0]["field"] == "lines"+++def test_checkout_add_voucher_code_checkout_with_sale(+ api_client, checkout_with_item, voucher_percentage, discount_info+):+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)+ address = checkout_with_item.shipping_address+ subtotal = calculations.checkout_subtotal(+ manager=manager, checkout_info=checkout_info, lines=lines, address=address+ )+ subtotal_discounted = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=address,+ discounts=[discount_info],+ )+ assert subtotal > subtotal_discounted+ previous_checkout_last_change = checkout_with_item.last_change++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher_percentage.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ checkout_with_item.refresh_from_db()+ assert not data["errors"]+ assert checkout_with_item.voucher_code == voucher_percentage.code+ assert checkout_with_item.discount_amount == Decimal(1.5)+ assert checkout_with_item.last_change != previous_checkout_last_change+++def test_checkout_add_specific_product_voucher_code_checkout_with_sale(+ api_client, checkout_with_item, voucher_specific_product_type, discount_info+):+ # given+ voucher = voucher_specific_product_type+ checkout = checkout_with_item+ expected_discount = Decimal(1.5)+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)++ subtotal = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)+ subtotal_discounted = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ discounts=[discount_info],+ )++ assert subtotal > subtotal_discounted+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # then+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ subtotal_with_voucher = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ discounts=[discount_info],+ )+ assert not data["errors"]+ assert subtotal_discounted == subtotal_with_voucher + Money(+ expected_discount, "USD"+ )+ assert checkout.voucher_code == voucher.code+ assert checkout.discount_amount == Decimal(0)+++def test_checkout_add_products_voucher_code_checkout_with_sale(+ api_client, checkout_with_item, voucher_percentage, discount_info+):+ # given+ checkout = checkout_with_item+ product = checkout.lines.first().variant.product+ voucher = voucher_percentage+ voucher.type = VoucherType.SPECIFIC_PRODUCT+ voucher.save()+ voucher.products.add(product)+ expected_discount = Money(Decimal(1.5), checkout.currency)++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)++ subtotal = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )++ checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)+ subtotal_discounted = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ discounts=[discount_info],+ )+ assert subtotal > subtotal_discounted+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # then+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ subtotal_with_voucher = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ discounts=[discount_info],+ )+ assert not data["errors"]+ assert subtotal_discounted == subtotal_with_voucher + expected_discount+ assert checkout.voucher_code == voucher.code+ assert checkout.discount_amount == Decimal(0)+++def test_checkout_add_collection_voucher_code_checkout_with_sale(+ api_client, checkout_with_item, voucher_percentage, discount_info, collection+):+ # given+ checkout = checkout_with_item+ voucher = voucher_percentage+ product = checkout.lines.first().variant.product+ product.collections.add(collection)+ voucher.type = VoucherType.SPECIFIC_PRODUCT+ voucher.save()+ voucher.collections.add(collection)+ expected_voucher_discount = Money(Decimal(1.5), checkout.currency)++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ subtotal = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)+ subtotal_discounted = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ discounts=[discount_info],+ )+ assert subtotal > subtotal_discounted+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # then+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ subtotal_with_voucher = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ discounts=[discount_info],+ )++ assert not data["errors"]+ assert subtotal_discounted == subtotal_with_voucher + expected_voucher_discount+ assert checkout.voucher_code == voucher.code+ assert checkout.discount_amount == Decimal(0)+++def test_checkout_add_category_code_checkout_with_sale(+ api_client, checkout_with_item, voucher_percentage, discount_info+):+ # given+ checkout = checkout_with_item+ category = checkout.lines.first().variant.product.category+ voucher = voucher_percentage+ voucher.type = VoucherType.SPECIFIC_PRODUCT+ voucher.save()+ voucher.categories.add(category)+ expected_discount = Money(Decimal(1.5), checkout.currency)++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)++ subtotal = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)+ subtotal_discounted = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ discounts=[discount_info],+ )+ assert subtotal > subtotal_discounted+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # then+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ subtotal_with_voucher = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ discounts=[discount_info],+ )+ assert not data["errors"]+ assert subtotal_discounted == subtotal_with_voucher + expected_discount+ assert checkout.voucher_code == voucher.code+ assert checkout.discount_amount == Decimal(0)+++def test_checkout_add_voucher_code_not_applicable_voucher(+ api_client, checkout_with_item, voucher_with_high_min_spent_amount+):+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher_with_high_min_spent_amount.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["field"] == "promoCode"+++def test_checkout_add_voucher_code_not_assigned_to_channel(+ api_client, checkout_with_item, voucher_without_channel+):+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher_without_channel.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["field"] == "promoCode"+++def test_checkout_add_gift_card_code(api_client, checkout_with_item, gift_card):+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert data["checkout"]["giftCards"][0]["id"] == gift_card_id+ assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_code+++def test_checkout_add_many_gift_card_code(+ api_client, checkout_with_gift_card, gift_card_created_by_staff+):+ assert checkout_with_gift_card.gift_cards.count() > 0+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card_created_by_staff.pk)+ variables = {+ "id": to_global_id_or_none(checkout_with_gift_card),+ "promoCode": gift_card_created_by_staff.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_gift_card.token)+ gift_card_data = data["checkout"]["giftCards"]+ assert gift_card_id in {gift_card["id"] for gift_card in gift_card_data}+++def test_checkout_add_inactive_gift_card_code(+ staff_api_client, checkout_with_item, gift_card+):+ # given+ gift_card.is_active = False+ gift_card.save(update_fields=["is_active"])++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(staff_api_client, variables)++ # then+ assert not data["checkout"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID.name+ assert data["errors"][0]["field"] == "promoCode"+++def test_checkout_add_expired_gift_card_code(+ staff_api_client, checkout_with_item, gift_card+):+ # given+ gift_card.expiry_date = date.today() - timedelta(days=10)+ gift_card.save(update_fields=["expiry_date"])++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(staff_api_client, variables)++ # then+ assert not data["checkout"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID.name+ assert data["errors"][0]["field"] == "promoCode"+++def test_checkout_add_used_gift_card_code(+ staff_api_client, checkout_with_item, gift_card_used, customer_user+):+ # given+ checkout_with_item.email = gift_card_used.used_by_email+ checkout_with_item.save(update_fields=["email"])++ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card_used.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card_used.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(staff_api_client, variables)++ # then+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert data["checkout"]["giftCards"][0]["id"] == gift_card_id+ assert (+ data["checkout"]["giftCards"][0]["last4CodeChars"]+ == gift_card_used.display_code+ )+++def test_checkout_add_used_gift_card_code_invalid_user(+ staff_api_client, checkout_with_item, gift_card_used, staff_user+):+ # given+ checkout_with_item.user = staff_user+ assert gift_card_used.used_by_email != checkout_with_item.user.email++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card_used.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(staff_api_client, variables)++ # then+ assert not data["checkout"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID.name+ assert data["errors"][0]["field"] == "promoCode"+++def test_checkout_get_total_with_gift_card(api_client, checkout_with_item, gift_card):+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)+ taxed_total = calculations.checkout_total(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout_with_item.shipping_address,+ )+ total_with_gift_card = taxed_total.gross.amount - gift_card.current_balance_amount++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert not data["checkout"]["giftCards"] == []+ assert data["checkout"]["totalPrice"]["gross"]["amount"] == total_with_gift_card+++def test_checkout_get_total_with_many_gift_card(+ api_client, checkout_with_gift_card, gift_card_created_by_staff+):+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout_with_gift_card)+ checkout_info = fetch_checkout_info(checkout_with_gift_card, lines, [], manager)+ taxed_total = calculations.checkout_total(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout_with_gift_card.shipping_address,+ )+ taxed_total.gross -= checkout_with_gift_card.get_total_gift_cards_balance()+ taxed_total.net -= checkout_with_gift_card.get_total_gift_cards_balance()+ total_with_gift_card = (+ taxed_total.gross.amount - gift_card_created_by_staff.current_balance_amount+ )++ assert checkout_with_gift_card.gift_cards.count() > 0+ variables = {+ "id": to_global_id_or_none(checkout_with_gift_card),+ "promoCode": gift_card_created_by_staff.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_gift_card.token)+ assert data["checkout"]["totalPrice"]["gross"]["amount"] == total_with_gift_card+++def test_checkout_get_total_with_more_money_on_gift_card(+ api_client, checkout_with_item, gift_card_used, customer_user+):+ checkout_with_item.email = gift_card_used.used_by_email+ checkout_with_item.save(update_fields=["email"])++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card_used.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert not data["checkout"]["giftCards"] == []+ assert data["checkout"]["totalPrice"]["gross"]["amount"] == 0+++def test_checkout_add_same_gift_card_code(api_client, checkout_with_gift_card):+ gift_card = checkout_with_gift_card.gift_cards.first()+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)+ gift_card_count = checkout_with_gift_card.gift_cards.count()+ variables = {+ "id": to_global_id_or_none(checkout_with_gift_card),+ "promoCode": gift_card.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_gift_card.token)+ assert data["checkout"]["giftCards"][0]["id"] == gift_card_id+ assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_code+ assert len(data["checkout"]["giftCards"]) == gift_card_count+++def test_checkout_add_gift_card_code_in_active_gift_card(+ api_client, checkout_with_item, gift_card+):+ gift_card.is_active = False+ gift_card.save()++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["field"] == "promoCode"+++def test_checkout_add_gift_card_code_in_expired_gift_card(+ api_client, checkout_with_item, gift_card+):+ gift_card.expiry_date = date.today() - timedelta(days=1)+ gift_card.save()++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": gift_card.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["field"] == "promoCode"+++def test_checkout_add_promo_code_invalid_checkout(api_client, voucher, checkout):+ variables = {"id": to_global_id_or_none(checkout), "promoCode": voucher.code}+ checkout.delete()+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["field"] == "id"+++def test_checkout_add_promo_code_invalid_promo_code(api_client, checkout_with_item):+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": "unexisting_code",+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["field"] == "promoCode"+++def test_checkout_add_promo_code_invalidate_shipping_method(+ api_client,+ checkout,+ variant_with_many_stocks_different_shipping_zones,+ gift_card_created_by_staff,+ address_usa,+ shipping_method,+ channel_USD,+ voucher,+):+ Stock.objects.update(quantity=5)++ # Free shipping for 50 USD+ shipping_channel_listing = shipping_method.channel_listings.first()+ shipping_channel_listing.minimum_order_price = Money(50, "USD")+ shipping_channel_listing.price = Money(0, "USD")+ shipping_channel_listing.save()++ # Setup checkout with items worth $50+ checkout.shipping_address = address_usa+ checkout.shipping_method = shipping_method+ checkout.billing_address = address_usa+ checkout.save()++ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())+ variant = variant_with_many_stocks_different_shipping_zones+ add_variant_to_checkout(checkout_info, variant, 5)++ # Apply voucher+ variables = {"id": to_global_id_or_none(checkout), "promoCode": voucher.code}+ data = _mutate_checkout_add_promo_code(api_client, variables)++ shipping_method_id = graphene.Node.to_global_id(+ "ShippingMethodType", shipping_method.pk+ )+ assert data["checkout"]["shippingMethod"] is None+ assert shipping_method_id not in data["checkout"]["availableShippingMethods"]+++def test_checkout_add_promo_code_no_checkout_email(+ api_client, checkout_with_item, voucher+):+ checkout_with_item.email = None+ checkout_with_item.save(update_fields=["email"])++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.EMAIL_NOT_SET.name++[email protected]("shipping_price", [12, 10, 5])+def test_checkout_add_free_shipping_voucher_do_not_invalidate_shipping_method(+ shipping_price,+ api_client,+ checkout_with_item,+ voucher_free_shipping,+ shipping_method,+ address_usa,+):+ """Ensure that adding free shipping voucher do not invalidate+ current shipping method.+ """+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.shipping_address = address_usa+ checkout_with_item.save(update_fields=["shipping_method", "shipping_address"])++ channel = checkout_with_item.channel++ line = checkout_with_item.lines.first()+ line.quantity = 1+ line.save(update_fields=["quantity"])++ variant_listing = line.variant.channel_listings.get(channel=channel)+ variant_listing.price = Money(10, "USD")+ variant_listing.save(update_fields=["price_amount"])++ # set minimal price similar to order subtotal price;+ # set shipping price so big, that in case the discount will be applied+ # substracted from subtotal the shipping method will be not valid anymore+ shipping_listing = shipping_method.channel_listings.get(channel=channel)+ shipping_listing.price = Money(shipping_price, "USD")+ shipping_listing.minimum_order_price = Money(8, "USD")+ shipping_listing.save(update_fields=["price_amount", "minimum_order_price_amount"])++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher_free_shipping.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # ensure that shipping method wasn't invalidate+ assert data["checkout"]["shippingMethod"]["id"] == graphene.Node.to_global_id(+ "ShippingMethod", shipping_method.id+ )++[email protected]("shipping_discount", [12, 10, 5])+def test_checkout_add_shipping_voucher_do_not_invalidate_shipping_method(+ shipping_discount,+ api_client,+ checkout_with_item,+ voucher_shipping_type,+ shipping_method,+ address_usa,+):+ """Ensure that adding shipping voucher do not invalidate current shipping method."""+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.shipping_address = address_usa+ checkout_with_item.save(update_fields=["shipping_method", "shipping_address"])++ channel = checkout_with_item.channel++ line = checkout_with_item.lines.first()+ line.quantity = 1+ line.save(update_fields=["quantity"])++ variant_listing = line.variant.channel_listings.get(channel=channel)+ variant_listing.price = Money(10, "USD")+ variant_listing.save(update_fields=["price_amount"])++ # set minimal price similar to order subtotal price;+ shipping_listing = shipping_method.channel_listings.get(channel=channel)+ shipping_listing.price = Money(20, "USD")+ shipping_listing.minimum_order_price = Money(8, "USD")+ shipping_listing.save(update_fields=["price_amount", "minimum_order_price_amount"])++ # set shipping voucher price so big, that in case the discount will be+ # substracted from subtotal price the shipping method will be not valid anymore+ voucher_listing = voucher_shipping_type.channel_listings.get(channel=channel)+ voucher_listing.discount = Money(shipping_discount, "USD")+ voucher_listing.save(update_fields=["discount_value"])++ voucher_shipping_type.countries = []+ voucher_shipping_type.save(update_fields=["countries"])++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": voucher_shipping_type.code,+ }+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # ensure that shipping method wasn't invalidate+ assert data["checkout"]["shippingMethod"]["id"] == graphene.Node.to_global_id(+ "ShippingMethod", shipping_method.id+ )diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.pyindex dde5c9b951..6dc90ce14b 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py@@ -8,6 +8,7 @@ import pytzfrom django.test import override_settingsfrom django.utils import timezone+from .....account.models import Addressfrom .....channel.utils import DEPRECATION_WARNING_MESSAGEfrom .....checkout import AddressTypefrom .....checkout.error_codes import CheckoutErrorCode@@ -1583,3 +1584,45 @@ def test_create_checkout_with_unpublished_product(response = get_graphql_content(user_api_client.post_graphql(query, variables))error = response["data"]["checkoutCreate"]["errors"][0]assert error["code"] == CheckoutErrorCode.PRODUCT_NOT_PUBLISHED.name++[email protected]("with_shipping_address", (True, False))+def test_create_checkout_with_digital(+ api_client,+ digital_content,+ graphql_address_data,+ with_shipping_address,+ channel_USD,+):+ """Test creating a checkout with a shipping address gets the address ignored."""++ address_count = Address.objects.count()++ variant = digital_content.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ checkout_input = {+ "channel": channel_USD.slug,+ "lines": [{"quantity": 1, "variantId": variant_id}],+ "email": "[email protected]",+ }++ if with_shipping_address:+ checkout_input["shippingAddress"] = graphql_address_data++ get_graphql_content(+ api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE, {"checkoutInput": checkout_input}+ )+ )["data"]["checkoutCreate"]++ # Retrieve the created checkout+ checkout = Checkout.objects.get()++ # Check that the shipping address was ignored, thus not created+ assert (+ checkout.shipping_address is None+ ), "The address shouldn't have been associated"+ assert (+ Address.objects.count() == address_count+ ), "No address should have been created"diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.pynew file mode 100644index 0000000000..1919809b5b--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_attach.py@@ -0,0 +1,183 @@+import graphene++from .....account.models import User+from .....checkout.error_codes import CheckoutErrorCode+from ....core.utils import to_global_id_or_none+from ....tests.utils import assert_no_permission, get_graphql_content++MUTATION_CHECKOUT_CUSTOMER_ATTACH = """+ mutation checkoutCustomerAttach($id: ID, $customerId: ID) {+ checkoutCustomerAttach(id: $id, customerId: $customerId) {+ checkout {+ token+ }+ errors {+ code+ field+ message+ }+ }+ }+"""+++def test_checkout_customer_attach(+ user_api_client, checkout_with_item, customer_user, permission_impersonate_user+):+ checkout = checkout_with_item+ checkout.email = "[email protected]"+ checkout.save()+ assert checkout.user is None+ previous_last_change = checkout.last_change++ query = MUTATION_CHECKOUT_CUSTOMER_ATTACH+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)+ variables = {"id": to_global_id_or_none(checkout), "customerId": customer_id}++ response = user_api_client.post_graphql(+ query, variables, permissions=[permission_impersonate_user]+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutCustomerAttach"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.user == customer_user+ assert checkout.email == customer_user.email+ assert checkout.last_change != previous_last_change+++def test_checkout_customer_attach_no_customer_id(+ api_client, user_api_client, checkout_with_item, customer_user+):+ checkout = checkout_with_item+ checkout.email = "[email protected]"+ checkout.save()+ assert checkout.user is None+ previous_last_change = checkout.last_change++ query = MUTATION_CHECKOUT_CUSTOMER_ATTACH+ variables = {"id": to_global_id_or_none(checkout)}++ # Mutation should fail for unauthenticated customers+ response = api_client.post_graphql(query, variables)+ assert_no_permission(response)++ # Mutation should succeed for authenticated customer+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutCustomerAttach"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.user == customer_user+ assert checkout.email == customer_user.email+ assert checkout.last_change != previous_last_change+++def test_checkout_customer_attach_by_app(+ app_api_client, checkout_with_item, customer_user, permission_impersonate_user+):+ checkout = checkout_with_item+ checkout.email = "[email protected]"+ checkout.save()+ assert checkout.user is None+ previous_last_change = checkout.last_change++ query = MUTATION_CHECKOUT_CUSTOMER_ATTACH+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)+ variables = {"id": to_global_id_or_none(checkout), "customerId": customer_id}++ # Mutation should succeed for authenticated customer+ response = app_api_client.post_graphql(+ query, variables, permissions=[permission_impersonate_user]+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutCustomerAttach"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.user == customer_user+ assert checkout.email == customer_user.email+ assert checkout.last_change != previous_last_change+++def test_checkout_customer_attach_by_app_no_customer_id(+ app_api_client, checkout_with_item, permission_impersonate_user+):+ checkout = checkout_with_item+ checkout.email = "[email protected]"+ checkout.save()+ assert checkout.user is None++ query = MUTATION_CHECKOUT_CUSTOMER_ATTACH+ variables = {"id": to_global_id_or_none(checkout)}++ # Mutation should succeed for authenticated customer+ response = app_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_impersonate_user],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutCustomerAttach"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == CheckoutErrorCode.REQUIRED.name+ assert data["errors"][0]["field"] == "customerId"+++def test_checkout_customer_attach_by_app_without_permission(+ app_api_client, checkout_with_item, customer_user+):+ checkout = checkout_with_item+ checkout.email = "[email protected]"+ checkout.save()+ assert checkout.user is None++ query = MUTATION_CHECKOUT_CUSTOMER_ATTACH+ customer_id = graphene.Node.to_global_id("User", customer_user.pk)+ variables = {"id": to_global_id_or_none(checkout), "customerId": customer_id}++ # Mutation should succeed for authenticated customer+ response = app_api_client.post_graphql(+ query,+ variables,+ )++ assert_no_permission(response)+++def test_checkout_customer_attach_user_to_checkout_with_user(+ user_api_client, customer_user, user_checkout, address+):+ checkout = user_checkout++ query = """+ mutation checkoutCustomerAttach($id: ID) {+ checkoutCustomerAttach(id: $id) {+ checkout {+ token+ }+ errors {+ field+ message+ code+ }+ }+ }+"""++ default_address = address.get_copy()+ second_user = User.objects.create_user(+ "[email protected]",+ "password",+ default_billing_address=default_address,+ default_shipping_address=default_address,+ first_name="Test2",+ last_name="Tested",+ )++ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ customer_id = graphene.Node.to_global_id("User", second_user.pk)+ variables = {"id": checkout_id, "customerId": customer_id}+ response = user_api_client.post_graphql(query, variables)+ assert_no_permission(response)diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.pynew file mode 100644index 0000000000..d785c8a6b5--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py@@ -0,0 +1,88 @@+from .....account.models import User+from ....core.utils import to_global_id_or_none+from ....tests.utils import assert_no_permission, get_graphql_content++MUTATION_CHECKOUT_CUSTOMER_DETACH = """+ mutation checkoutCustomerDetach($id: ID) {+ checkoutCustomerDetach(id: $id) {+ checkout {+ token+ }+ errors {+ field+ message+ }+ }+ }+ """+++def test_checkout_customer_detach(user_api_client, checkout_with_item, customer_user):+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.save(update_fields=["user"])+ previous_last_change = checkout.last_change++ variables = {"id": to_global_id_or_none(checkout)}++ # Mutation should succeed if the user owns this checkout.+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CUSTOMER_DETACH, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutCustomerDetach"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.user is None+ assert checkout.last_change != previous_last_change++ # Mutation should fail when user calling it doesn't own the checkout.+ other_user = User.objects.create_user("[email protected]", "password")+ checkout.user = other_user+ checkout.save()+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CUSTOMER_DETACH, variables+ )+ assert_no_permission(response)+++def test_checkout_customer_detach_by_app(+ app_api_client, checkout_with_item, customer_user, permission_impersonate_user+):+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.save(update_fields=["user"])+ previous_last_change = checkout.last_change++ variables = {"id": to_global_id_or_none(checkout)}++ # Mutation should succeed if the user owns this checkout.+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_CUSTOMER_DETACH,+ variables,+ permissions=[permission_impersonate_user],+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutCustomerDetach"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.user is None+ assert checkout.last_change != previous_last_change+++def test_checkout_customer_detach_by_app_without_permissions(+ app_api_client, checkout_with_item, customer_user+):+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.save(update_fields=["user"])+ previous_last_change = checkout.last_change++ variables = {"id": to_global_id_or_none(checkout)}++ # Mutation should succeed if the user owns this checkout.+ response = app_api_client.post_graphql(MUTATION_CHECKOUT_CUSTOMER_DETACH, variables)++ assert_no_permission(response)+ checkout.refresh_from_db()+ assert checkout.last_change == previous_last_changediff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.pynew file mode 100644index 0000000000..7332bf585f--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py@@ -0,0 +1,358 @@+from unittest import mock+from unittest.mock import patch++import graphene+import pytest++from .....checkout.error_codes import CheckoutErrorCode+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID+from .....plugins.manager import get_plugins_manager+from .....shipping import models as shipping_models+from .....shipping.utils import convert_to_shipping_method_data+from ....core.utils import to_global_id_or_none+from ....tests.utils import get_graphql_content++MUTATION_UPDATE_DELIVERY_METHOD = """+ mutation checkoutDeliveryMethodUpdate(+ $id: ID, $deliveryMethodId: ID) {+ checkoutDeliveryMethodUpdate(+ id: $id,+ deliveryMethodId: $deliveryMethodId) {+ checkout {+ id+ deliveryMethod {+ __typename+ ... on ShippingMethod {+ name+ id+ translation(languageCode: EN_US) {+ name+ }+ }+ ... on Warehouse {+ name+ id+ }+ }+ }+ errors {+ field+ message+ code+ }+ }+}+"""++[email protected]("is_valid_delivery_method", (True, False))+ "delivery_method, node_name, attribute_name",+ [+ ("warehouse", "Warehouse", "collection_point"),+ ("shipping_method", "ShippingMethod", "shipping_method"),+ ],+ indirect=("delivery_method",),+)+@patch(+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."+ "clean_delivery_method"+)+def test_checkout_delivery_method_update(+ mock_clean_delivery,+ api_client,+ delivery_method,+ node_name,+ attribute_name,+ checkout_with_item_for_cc,+ is_valid_delivery_method,+):+ # given+ mock_clean_delivery.return_value = is_valid_delivery_method++ checkout = checkout_with_item_for_cc+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)++ shipping_method_data = delivery_method+ if attribute_name == "shipping_method":+ shipping_method_data = convert_to_shipping_method_data(+ delivery_method,+ delivery_method.channel_listings.get(),+ )+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_clean_delivery.return_value = is_valid_delivery_method++ method_id = graphene.Node.to_global_id(node_name, delivery_method.id)++ response = api_client.post_graphql(+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]+ checkout.refresh_from_db()++ mock_clean_delivery.assert_called_once_with(+ checkout_info=checkout_info, lines=lines, method=shipping_method_data+ )+ errors = data["errors"]+ if is_valid_delivery_method:+ assert not errors+ assert getattr(checkout, attribute_name) == delivery_method+ else:+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert (+ errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name+ )+ assert checkout.shipping_method is None+ assert checkout.collection_point is None++[email protected]("is_valid_delivery_method", (True, False))[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+@patch(+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."+ "clean_delivery_method"+)+def test_checkout_delivery_method_update_external_shipping(+ mock_clean_delivery,+ mock_send_request,+ api_client,+ checkout_with_item_for_cc,+ is_valid_delivery_method,+ settings,+ shipping_app,+ channel_USD,+):+ checkout = checkout_with_item_for_cc+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_clean_delivery.return_value = is_valid_delivery_method++ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ response_method_id = "abcd"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ mock_send_request.return_value = mock_json_response++ method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ response = api_client.post_graphql(+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]+ checkout.refresh_from_db()++ errors = data["errors"]+ if is_valid_delivery_method:+ assert not errors+ assert PRIVATE_META_APP_SHIPPING_ID in checkout.private_metadata+ assert data["checkout"]["deliveryMethod"]["id"] == method_id+ else:+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert (+ errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name+ )+ assert PRIVATE_META_APP_SHIPPING_ID not in checkout.private_metadata+++@patch(+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update."+ "clean_delivery_method"+)+def test_checkout_delivery_method_update_with_id_of_different_type_causes_and_error(+ mock_clean_delivery,+ api_client,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_clean_delivery.return_value = True+ invalid_method_id = graphene.Node.to_global_id("Address", address.id)++ response = api_client.post_graphql(+ query,+ {+ "id": to_global_id_or_none(checkout),+ "deliveryMethodId": invalid_method_id,+ },+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]+ checkout.refresh_from_db()++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert errors[0]["code"] == CheckoutErrorCode.INVALID.name+ assert checkout.shipping_method is None+ assert checkout.collection_point is None+++@patch(+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update."+ "clean_delivery_method"+)+def test_checkout_delivery_method_with_nonexistant_id_results_not_found(+ mock_clean_delivery,+ api_client,+ warehouse_for_cc,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_clean_delivery.return_value = True++ nonexistant_id = "YXBwOjEyMzQ6c29tZS1pZA=="+ response = api_client.post_graphql(+ query,+ {+ "id": to_global_id_or_none(checkout),+ "deliveryMethodId": nonexistant_id,+ },+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]+ checkout.refresh_from_db()++ assert not data["checkout"]+ assert data["errors"][0]["field"] == "deliveryMethodId"+ assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name+ assert checkout.shipping_method is None+ assert checkout.collection_point is None+++@patch(+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update."+ "clean_delivery_method"+)+def test_checkout_delivery_method_with_empty_fields_results_None(+ mock_clean_delivery,+ api_client,+ warehouse_for_cc,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_clean_delivery.return_value = True++ response = api_client.post_graphql(+ query,+ {+ "id": to_global_id_or_none(checkout),+ },+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]+ checkout.refresh_from_db()++ assert not data["errors"]+ assert data["checkout"]["deliveryMethod"] is None+ assert checkout.shipping_method is None+ assert checkout.collection_point is None+++@patch("saleor.shipping.postal_codes.is_shipping_method_applicable_for_postal_code")+def test_checkout_delivery_method_update_excluded_postal_code(+ mock_is_shipping_method_available,+ staff_api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD+ mock_is_shipping_method_available.return_value = False++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]++ checkout.refresh_from_db()++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name+ assert checkout.shipping_method is None+ assert (+ mock_is_shipping_method_available.call_count+ == shipping_models.ShippingMethod.objects.count()+ )+++def test_checkout_delivery_method_update_shipping_zone_without_channel(+ api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ shipping_method.shipping_zone.channels.clear()+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = api_client.post_graphql(+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]++ checkout.refresh_from_db()++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "deliveryMethodId"+ assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name+ assert checkout.shipping_method is None+++def test_checkout_delivery_method_update_shipping_zone_with_channel(+ staff_api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_DELIVERY_METHOD++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]++ checkout.refresh_from_db()++ checkout.refresh_from_db()+ errors = data["errors"]+ assert not errors++ assert checkout.shipping_method == shipping_methoddiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.pynew file mode 100644index 0000000000..7b935a375c--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py@@ -0,0 +1,133 @@+from unittest import mock++import graphene++from .....checkout import calculations+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from .....checkout.utils import (+ add_variant_to_checkout,+ add_voucher_to_checkout,+ calculate_checkout_quantity,+)+from .....plugins.manager import get_plugins_manager+from .....warehouse.models import Reservation+from ....core.utils import to_global_id_or_none+from ....tests.utils import get_graphql_content+from ...mutations.utils import update_checkout_shipping_method_if_invalid++MUTATION_CHECKOUT_LINE_DELETE = """+ mutation checkoutLineDelete($id: ID, $lineId: ID!) {+ checkoutLineDelete(id: $id, lineId: $lineId) {+ checkout {+ token+ lines {+ quantity+ variant {+ id+ }+ }+ }+ errors {+ field+ message+ }+ }+ }+"""+++ "saleor.graphql.checkout.mutations.checkout_line_delete."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_line_delete(+ mocked_update_shipping_method,+ user_api_client,+ checkout_line_with_reservation_in_many_stocks,+):+ assert Reservation.objects.count() == 2+ checkout = checkout_line_with_reservation_in_many_stocks.checkout+ previous_last_change = checkout.last_change+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 3+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.quantity == 3++ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)++ variables = {"id": to_global_id_or_none(checkout), "lineId": line_id}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLineDelete"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 0+ assert calculate_checkout_quantity(lines) == 0+ assert Reservation.objects.count() == 0+ manager = get_plugins_manager()+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)+ assert checkout.last_change != previous_last_change+++def test_checkout_lines_delete_with_not_applicable_voucher(+ user_api_client, checkout_with_item, voucher, channel_USD+):+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)+ subtotal = calculations.checkout_subtotal(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout_with_item.shipping_address,+ )+ voucher.channel_listings.filter(channel=channel_USD).update(+ min_spent_amount=subtotal.gross.amount+ )+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)++ add_voucher_to_checkout(manager, checkout_info, lines, voucher)+ assert checkout_with_item.voucher_code == voucher.code++ line = checkout_with_item.lines.first()++ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)+ variables = {"id": to_global_id_or_none(checkout_with_item), "lineId": line_id}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLineDelete"]+ assert not data["errors"]+ checkout_with_item.refresh_from_db()+ assert checkout_with_item.lines.count() == 0+ assert checkout_with_item.voucher_code is None+++def test_checkout_line_delete_remove_shipping_if_removed_product_with_shipping(+ user_api_client, checkout_with_item, digital_content, address, shipping_method+):+ checkout = checkout_with_item+ digital_variant = digital_content.product_variant+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.save()+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())+ add_variant_to_checkout(checkout_info, digital_variant, 1)+ line = checkout.lines.first()++ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)++ variables = {"id": to_global_id_or_none(checkout), "lineId": line_id}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLineDelete"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ assert not checkout.shipping_methoddiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pynew file mode 100644index 0000000000..5b27d7fe4d--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -0,0 +1,740 @@+import datetime+from decimal import Decimal+from unittest import mock++import graphene+import pytest+import pytz+from django.utils import timezone++from .....checkout.error_codes import CheckoutErrorCode+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from .....checkout.models import Checkout+from .....checkout.utils import calculate_checkout_quantity+from .....plugins.manager import get_plugins_manager+from .....product.models import ProductChannelListing+from .....warehouse import WarehouseClickAndCollectOption+from .....warehouse.models import Reservation, Stock+from .....warehouse.tests.utils import get_available_quantity_for_stock+from ....core.utils import to_global_id_or_none+from ....tests.utils import assert_no_permission, get_graphql_content+from ...mutations.utils import update_checkout_shipping_method_if_invalid++MUTATION_CHECKOUT_LINES_ADD = """+ mutation checkoutLinesAdd(+ $id: ID, $lines: [CheckoutLineInput!]!) {+ checkoutLinesAdd(id: $id, lines: $lines) {+ checkout {+ token+ quantity+ lines {+ quantity+ variant {+ id+ }+ }+ }+ errors {+ field+ code+ message+ variants+ }+ }+ }"""+++ "saleor.graphql.checkout.mutations.checkout_lines_add."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_lines_add(+ mocked_update_shipping_method, user_api_client, checkout_with_item, stock+):+ variant = stock.product_variant+ checkout = checkout_with_item+ line = checkout.lines.first()+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 3+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ previous_last_change = checkout.last_change++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ line = checkout.lines.last()+ assert line.variant == variant+ assert line.quantity == 1+ assert calculate_checkout_quantity(lines) == 4+ assert not Reservation.objects.exists()++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)+ assert checkout.last_change != previous_last_change+++def test_checkout_lines_add_with_reservations(+ site_settings_with_reservations, user_api_client, checkout_with_item, stock+):+ variant = stock.product_variant+ checkout = checkout_with_item+ line = checkout.lines.first()+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 3+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ line = checkout.lines.last()+ assert line.variant == variant+ assert line.quantity == 1+ assert calculate_checkout_quantity(lines) == 4++ reservation = line.reservations.get()+ assert reservation+ assert reservation.checkout_line == line+ assert reservation.quantity_reserved == line.quantity+++def test_checkout_lines_add_updates_reservation(+ site_settings_with_reservations,+ user_api_client,+ checkout_line_with_one_reservation,+ stock,+):+ variant = checkout_line_with_one_reservation.variant+ checkout = checkout_line_with_one_reservation.checkout+ line = checkout_line_with_one_reservation+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 2+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ line = checkout.lines.last()+ assert line.variant == variant+ assert line.quantity == 3+ assert calculate_checkout_quantity(lines) == 3++ reservation = line.reservations.get()+ assert reservation+ assert reservation.checkout_line == line+ assert reservation.quantity_reserved == line.quantity+++def test_checkout_lines_add_new_variant_updates_other_lines_reservations_expirations(+ site_settings_with_reservations,+ user_api_client,+ checkout_line_with_one_reservation,+ product,+ warehouse,+):+ variant = checkout_line_with_one_reservation.variant+ checkout = checkout_line_with_one_reservation.checkout+ line = checkout_line_with_one_reservation+ reservation = line.reservations.get()+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 2++ variant_other = product.variants.create(sku="SKU_B")+ variant_other.channel_listings.create(+ channel=checkout.channel,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=checkout.channel.currency_code,+ )+ Stock.objects.create(+ product_variant=variant_other, warehouse=warehouse, quantity=15+ )+ variant_other_id = graphene.Node.to_global_id("ProductVariant", variant_other.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_other_id, "quantity": 3}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ line.refresh_from_db()+ assert line.variant == variant+ assert line.quantity == 2+ new_line = checkout.lines.get(variant=variant_other)+ assert new_line.variant == variant_other+ assert new_line.quantity == 3+ assert calculate_checkout_quantity(lines) == 5++ updated_reservation = Reservation.objects.get(checkout_line__variant=variant)+ assert updated_reservation.checkout_line == line+ assert updated_reservation.quantity_reserved == line.quantity+ assert updated_reservation.reserved_until > reservation.reserved_until++ other_reservation = Reservation.objects.get(checkout_line__variant=variant_other)+ assert other_reservation.checkout_line == new_line+ assert other_reservation.quantity_reserved == new_line.quantity+ assert other_reservation.reserved_until > reservation.reserved_until++ assert updated_reservation.reserved_until == other_reservation.reserved_until++ with pytest.raises(Reservation.DoesNotExist):+ reservation.refresh_from_db()+++def test_checkout_lines_add_existing_variant(user_api_client, checkout_with_item):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ previous_last_change = checkout.last_change++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 7}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ line = checkout.lines.last()+ assert line.quantity == 10+ assert checkout.last_change != previous_last_change+++def test_checkout_lines_add_custom_price(+ app_api_client, checkout, stock, permission_handle_checkouts+):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ line = checkout.lines.last()+ assert line.variant == variant+ assert line.quantity == 1+ assert line.price_override == price+++def test_checkout_lines_add_existing_variant_with_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ price = Decimal("13.11")++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 7, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ line = checkout.lines.last()+ assert line.quantity == 10+ assert line.price_override == price+++def test_checkout_lines_add_existing_variant_override_previous_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ line.price_override = 8.22+ line.save(update_fields=["price_override"])++ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ price = Decimal("13.11")++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 7, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ line = checkout.lines.last()+ assert line.quantity == 10+ assert line.price_override == price+++def test_checkout_lines_add_custom_price_app_no_perm(app_api_client, checkout, stock):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = app_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ assert_no_permission(response)+++def test_checkout_lines_add_custom_price_permission_denied_for_staff_user(+ staff_api_client, checkout, stock, permission_handle_checkouts+):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = staff_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ permissions=[permission_handle_checkouts],+ )+ assert_no_permission(response)+++def test_checkout_lines_add_existing_variant_over_allowed_stock(+ user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ current_stock = line.variant.stocks.first()++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": current_stock.quantity - 1}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesAdd"]["errors"]+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+++def test_checkout_lines_add_with_unavailable_variant(+ user_api_client, checkout_with_item, stock+):+ variant = stock.product_variant+ variant.channel_listings.filter(channel=checkout_with_item.channel).update(+ price_amount=None+ )+ checkout = checkout_with_item+ line = checkout.lines.first()+ assert line.quantity == 3+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesAdd"]["errors"]+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name+ assert errors[0]["field"] == "lines"+ assert errors[0]["variants"] == [variant_id]+++def test_checkout_lines_add_with_insufficient_stock(+ user_api_client, checkout_with_item, stock+):+ variant = stock.product_variant+ checkout = checkout_with_item+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 49}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesAdd"]["errors"]+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"+++def test_checkout_lines_add_with_reserved_insufficient_stock(+ site_settings_with_reservations,+ user_api_client,+ checkout_with_item,+ stock,+ channel_USD,+):+ variant = stock.product_variant+ checkout = checkout_with_item+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ quantity_available = get_available_quantity_for_stock(stock)++ other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")+ other_checkout_line = other_checkout.lines.create(+ variant=variant,+ quantity=quantity_available - 1,+ )+ Reservation.objects.create(+ checkout_line=other_checkout_line,+ stock=stock,+ quantity_reserved=quantity_available - 1,+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),+ )++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 2}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesAdd"]["errors"]+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"+++ "cc_option",+ [+ WarehouseClickAndCollectOption.ALL_WAREHOUSES,+ WarehouseClickAndCollectOption.LOCAL_STOCK,+ ],+)+def test_checkout_lines_for_click_and_collect_insufficient_stock(+ user_api_client, checkout_with_item_for_cc, warehouse_for_cc, cc_option+):+ checkout = checkout_with_item_for_cc+ checkout.collection_point = warehouse_for_cc++ warehouse_for_cc.click_and_collect_option = cc_option+ warehouse_for_cc.save(update_fields=["click_and_collect_option"])+ checkout.refresh_from_db()++ variant = checkout.lines.last().variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 42}],+ "channelSlug": checkout.channel.slug,+ }++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesAdd"]["errors"]++ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"+++def test_checkout_lines_add_with_zero_quantity(+ user_api_client, checkout_with_item, stock+):+ variant = stock.product_variant+ checkout = checkout_with_item+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 0}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesAdd"]["errors"]+ assert errors[0]["code"] == CheckoutErrorCode.ZERO_QUANTITY.name+ assert errors[0]["field"] == "quantity"+++def test_checkout_lines_add_no_channel_shipping_zones(+ user_api_client, checkout_with_item, stock+):+ variant = stock.product_variant+ checkout = checkout_with_item+ checkout.channel.shipping_zones.clear()+ line = checkout.lines.first()+ assert line.quantity == 3+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesAdd"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"+++def test_checkout_lines_add_with_unpublished_product(+ user_api_client, checkout_with_item, stock, channel_USD+):+ variant = stock.product_variant+ product = variant.product+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(+ is_published=False+ )++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout_with_item.channel.slug,+ }++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ content = get_graphql_content(response)+ error = content["data"]["checkoutLinesAdd"]["errors"][0]+ assert error["code"] == CheckoutErrorCode.PRODUCT_NOT_PUBLISHED.name+++def test_checkout_lines_add_with_unavailable_for_purchase_product(+ user_api_client, checkout_with_item, stock+):+ # given+ variant = stock.product_variant+ product = stock.product_variant.product+ product.channel_listings.update(available_for_purchase_at=None)++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # then+ content = get_graphql_content(response)+ error = content["data"]["checkoutLinesAdd"]["errors"][0]+ assert error["field"] == "lines"+ assert error["code"] == CheckoutErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name+ assert error["variants"] == [variant_id]+++def test_checkout_lines_add_with_available_for_purchase_from_tomorrow_product(+ user_api_client, checkout_with_item, stock+):+ # given+ variant = stock.product_variant+ product = stock.product_variant.product+ product.channel_listings.update(+ available_for_purchase_at=datetime.datetime.now(pytz.UTC)+ + datetime.timedelta(days=1)+ )++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # then+ content = get_graphql_content(response)+ error = content["data"]["checkoutLinesAdd"]["errors"][0]+ assert error["field"] == "lines"+ assert error["code"] == CheckoutErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name+ assert error["variants"] == [variant_id]+++def test_checkout_lines_add_too_many(user_api_client, checkout_with_item, stock):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 51}],+ "channelSlug": checkout_with_item.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)["data"]["checkoutLinesAdd"]++ assert content["errors"]+ assert content["errors"] == [+ {+ "field": "quantity",+ "message": "Cannot add more than 50 times this item: SKU_A.",+ "code": "QUANTITY_GREATER_THAN_LIMIT",+ "variants": None,+ }+ ]++[email protected]("is_preorder", [True, False])+def test_checkout_lines_add_too_many_after_two_trials(+ user_api_client, checkout_with_item, stock, is_preorder+):+ variant = stock.product_variant+ variant.is_preorder = is_preorder+ variant.preorder_end_date = timezone.now() + datetime.timedelta(days=1)+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stock.quantity = 200+ stock.save(update_fields=["quantity"])+ variant.save(update_fields=["is_preorder", "preorder_end_date"])++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 26}],+ "channelSlug": checkout_with_item.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)["data"]["checkoutLinesAdd"]++ assert not content["errors"]++ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)["data"]["checkoutLinesAdd"]++ assert content["errors"] == [+ {+ "field": "quantity",+ "message": "Cannot add more than 50 times this item: SKU_A.",+ "code": "QUANTITY_GREATER_THAN_LIMIT",+ "variants": None,+ }+ ]+++def test_checkout_lines_add_empty_checkout(user_api_client, checkout, stock):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+++def test_checkout_lines_add_variant_without_inventory_tracking(+ user_api_client, checkout, variant_without_inventory_tracking+):+ variant = variant_without_inventory_tracking+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+++def test_checkout_lines_add_check_lines_quantity(user_api_client, checkout, stock):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 16}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert data["errors"][0]["message"] == (+ "Could not add items SKU_A. Only 15 remaining in stock."+ )+ assert data["errors"][0]["field"] == "quantity"+++def test_checkout_lines_invalid_variant_id(user_api_client, checkout, stock):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ invalid_variant_id = "InvalidId"++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [+ {"variantId": variant_id, "quantity": 1},+ {"variantId": invalid_variant_id, "quantity": 3},+ ],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ error_msg = "Could not resolve to a node with the global id list of '%s'."+ assert data["errors"][0]["message"] == error_msg % [invalid_variant_id]+ assert data["errors"][0]["field"] == "variantId"diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.pynew file mode 100644index 0000000000..4426159c53--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py@@ -0,0 +1,107 @@+from unittest import mock++import graphene++from .....checkout.error_codes import CheckoutErrorCode+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from .....plugins.manager import get_plugins_manager+from ....core.utils import to_global_id_or_none+from ....tests.utils import get_graphql_content+from ...mutations.utils import update_checkout_shipping_method_if_invalid++MUTATION_CHECKOUT_LINES_DELETE = """+ mutation checkoutLinesDelete($id: ID, $linesIds: [ID!]!) {+ checkoutLinesDelete(id: $id, linesIds: $linesIds) {+ checkout {+ token+ lines {+ id+ quantity+ variant {+ id+ }+ }+ }+ errors {+ message+ code+ field+ lines+ }+ }+ }+"""+++ "saleor.graphql.checkout.mutations.checkout_lines_delete."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_lines_delete(+ mocked_update_shipping_method, user_api_client, checkout_with_items+):+ checkout = checkout_with_items+ checkout_lines_count = checkout.lines.count()+ previous_last_change = checkout.last_change+ line = checkout.lines.first()+ second_line = checkout.lines.last()++ first_line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)+ second_line_id = graphene.Node.to_global_id("CheckoutLine", second_line.pk)+ lines_list = [first_line_id, second_line_id]++ variables = {"id": to_global_id_or_none(checkout), "linesIds": lines_list}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesDelete"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() + len(lines_list) == checkout_lines_count+ remaining_lines = data["checkout"]["lines"]+ lines_ids = [line["id"] for line in remaining_lines]+ assert lines_list not in lines_ids+ manager = get_plugins_manager()+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)+ assert checkout.last_change != previous_last_change+++def test_checkout_lines_delete_invalid_checkout_id(+ user_api_client, checkout_with_items+):+ checkout = checkout_with_items+ line = checkout.lines.first()+ second_line = checkout.lines.last()++ first_line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)+ second_line_id = graphene.Node.to_global_id("CheckoutLine", second_line.pk)+ lines_list = [first_line_id, second_line_id]++ variables = {+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),+ "linesIds": lines_list,+ }+ checkout.delete()+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)+ content = get_graphql_content(response)+ errors = content["data"]["checkoutLinesDelete"]["errors"][0]+ assert errors["code"] == CheckoutErrorCode.NOT_FOUND.name+++def tests_checkout_lines_delete_invalid_lines_ids(user_api_client, checkout_with_items):+ checkout = checkout_with_items+ previous_last_change = checkout.last_change+ line = checkout.lines.first()++ first_line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)+ lines_list = [first_line_id, "Q2hlY2tvdXRMaW5lOjE8"]++ variables = {"id": to_global_id_or_none(checkout), "linesIds": lines_list}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)+ content = get_graphql_content(response, ignore_errors=True)+ errors = content["errors"][0]+ assert errors["extensions"]["exception"]["code"] == "GraphQLError"+ assert checkout.last_change == previous_last_changediff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.pynew file mode 100644index 0000000000..1202338080--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py@@ -0,0 +1,882 @@+import datetime+from decimal import Decimal+from unittest import mock++import graphene+import pytest+from django.utils import timezone++from .....checkout.error_codes import CheckoutErrorCode+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from .....checkout.models import Checkout, CheckoutLine+from .....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity+from .....plugins.manager import get_plugins_manager+from .....product.models import ProductChannelListing+from .....warehouse.models import Reservation, Stock+from ....core.utils import to_global_id_or_none+from ....tests.utils import assert_no_permission, get_graphql_content+from ...mutations.utils import update_checkout_shipping_method_if_invalid++MUTATION_CHECKOUT_LINES_UPDATE = """+ mutation checkoutLinesUpdate(+ $id: ID, $lines: [CheckoutLineUpdateInput!]!) {+ checkoutLinesUpdate(id: $id, lines: $lines) {+ checkout {+ id+ token+ quantity+ lines {+ quantity+ variant {+ id+ }+ }+ totalPrice {+ gross {+ amount+ }+ net {+ amount+ }+ }+ discount {+ amount+ }+ }+ errors {+ field+ code+ message+ variants+ }+ }+ }+ """+++ "saleor.graphql.checkout.mutations.checkout_lines_add."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_lines_update(+ mocked_update_shipping_method, user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3+ previous_last_change = checkout.last_change++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+ assert calculate_checkout_quantity(lines) == 1++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)+ assert checkout.last_change != previous_last_change+++def test_checkout_lines_update_checkout_with_voucher(+ user_api_client, checkout_with_item, voucher_percentage+):+ """Ensure that discount is correct calculated when updating the checkout with+ already applied discount."""+ # given+ channel = checkout_with_item.channel+ line = checkout_with_item.lines.first()+ variant = line.variant++ channel_listing = variant.channel_listings.get(channel=channel)+ unit_price = variant.get_price(+ variant.product, [], checkout_with_item.channel, channel_listing+ )++ voucher_channel_listing = voucher_percentage.channel_listings.get(channel=channel)+ voucher_channel_listing.discount_value = 100+ voucher_channel_listing.save(update_fields=["discount_value"])++ checkout_with_item.voucher_code = voucher_percentage.code+ checkout_with_item.discount_amount = (unit_price * line.quantity).amount+ checkout_with_item.save()++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)++ # then+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout_data = data["checkout"]+ total_price_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]+ assert total_price_gross_amount == 0+ assert checkout_data["discount"]["amount"] == unit_price.amount++ checkout_with_item.refresh_from_db()+ assert checkout_with_item.discount_amount == unit_price.amount+++def test_checkout_lines_update_with_new_reservations(+ site_settings_with_reservations,+ user_api_client,+ checkout_line_with_reservation_in_many_stocks,+):+ assert Reservation.objects.count() == 2+ checkout = checkout_line_with_reservation_in_many_stocks.checkout+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3++ Stock.objects.filter(+ warehouse__shipping_zones__countries__contains="US", product_variant=variant+ ).update(quantity=3)++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+ assert calculate_checkout_quantity(lines) == 1++ reservation = checkout_line_with_reservation_in_many_stocks.reservations.first()+ assert reservation.quantity_reserved == line.quantity++ assert Reservation.objects.count() == 1+++def test_checkout_lines_update_against_reserved_stock(+ site_settings_with_reservations,+ user_api_client,+ checkout_line,+ stock,+ channel_USD,+):+ assert Reservation.objects.count() == 0+ checkout = checkout_line.checkout+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ variant = checkout_line.variant+ assert checkout_line.quantity == 3++ other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")+ other_checkout_line = other_checkout.lines.create(+ variant=variant,+ quantity=7,+ )+ reservation = Reservation.objects.create(+ checkout_line=other_checkout_line,+ stock=variant.stocks.first(),+ quantity_reserved=7,+ reserved_until=timezone.now() + datetime.timedelta(minutes=5),+ )++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 5}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert data["errors"]+ assert data["errors"][0]["message"] == (+ "Could not add items 123. Only 3 remaining in stock."+ )+ assert data["errors"][0]["field"] == "quantity"++ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 3+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 3+ reservation.refresh_from_db()+ assert Reservation.objects.count() == 1+++def test_checkout_lines_update_other_lines_reservations_expirations(+ site_settings_with_reservations,+ user_api_client,+ checkout_line_with_one_reservation,+ product,+ warehouse,+):+ variant = checkout_line_with_one_reservation.variant+ checkout = checkout_line_with_one_reservation.checkout+ line = checkout_line_with_one_reservation+ reservation = line.reservations.get()+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 2++ variant_other = product.variants.create(sku="SKU_B")+ variant_other.channel_listings.create(+ channel=checkout.channel,+ price_amount=Decimal(10),+ cost_price_amount=Decimal(1),+ currency=checkout.channel.currency_code,+ )+ Stock.objects.create(+ product_variant=variant_other, warehouse=warehouse, quantity=15+ )+ add_variant_to_checkout(checkout_info, variant_other, 2)+ variant_other_id = graphene.Node.to_global_id("ProductVariant", variant_other.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_other_id, "quantity": 3}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ line.refresh_from_db()+ assert line.variant == variant+ assert line.quantity == 2+ new_line = checkout.lines.get(variant=variant_other)+ assert new_line.variant == variant_other+ assert new_line.quantity == 3+ assert calculate_checkout_quantity(lines) == 5++ updated_reservation = Reservation.objects.get(checkout_line__variant=variant)+ assert updated_reservation.checkout_line == line+ assert updated_reservation.quantity_reserved == line.quantity+ assert updated_reservation.reserved_until > reservation.reserved_until++ other_reservation = Reservation.objects.get(checkout_line__variant=variant_other)+ assert other_reservation.checkout_line == new_line+ assert other_reservation.quantity_reserved == new_line.quantity++ assert updated_reservation.reserved_until == other_reservation.reserved_until++ with pytest.raises(Reservation.DoesNotExist):+ reservation.refresh_from_db()+++def test_checkout_lines_update_quantity_and_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.22")++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+ assert line.price_override == price+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 1+++def test_checkout_lines_update_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ variant = line.variant+ previous_quantity = line.quantity++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.22")++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "price": price}],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == previous_quantity+ assert line.price_override == price+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 3+++def test_checkout_lines_update_with_custom_price_override_existing_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ 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.price_override = Decimal("10.12")+ line.save(update_fields=["price_override"])+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.10")++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+ assert line.price_override == price+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 1+++def test_checkout_lines_update_clear_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ 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.price_override = Decimal("10.12")+ line.save(update_fields=["price_override"])+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": None}],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+ assert line.price_override is None+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 1+++def test_checkout_lines_update_set_quantity_to_0_then_update_customer_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ """Ensure an error is not raised and the line is deleted when the line quantity+ is set to 0 firstly and then the custom price is changed."""++ 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.price_override = Decimal("10.12")+ line.save(update_fields=["price_override"])+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [+ {"variantId": variant_id, "quantity": 0},+ {"variantId": variant_id, "price": 10},+ ],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 0+ with pytest.raises(CheckoutLine.DoesNotExist):+ line.refresh_from_db()+++def test_checkout_lines_update_with_custom_price_by_app_no_perm(+ app_api_client, checkout_with_item+):+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.22")++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ }+ response = app_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ assert_no_permission(response)+++def test_checkout_lines_update_with_custom_price_raise_permission_denied_for_staff(+ staff_api_client, checkout_with_item, permission_handle_checkouts+):+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.22")++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ }+ response = staff_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ assert_no_permission(response)+++def test_checkout_lines_update_no_quantity_provided(+ user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "lines": [{"variantId": variant_id}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == CheckoutErrorCode.REQUIRED.name+ assert errors[0]["field"] == "quantity"+++def test_checkout_lines_update_with_unavailable_variant(+ user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ previous_last_change = checkout.last_change+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ variant = line.variant+ variant.channel_listings.filter(channel=checkout_with_item.channel).update(+ price_amount=None+ )+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ errors = content["data"]["checkoutLinesUpdate"]["errors"]+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name+ assert errors[0]["field"] == "lines"+ assert errors[0]["variants"] == [variant_id]+ checkout.refresh_from_db()+ assert checkout.last_change == previous_last_change+++def test_checkout_lines_update_channel_without_shipping_zones(+ user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ checkout.channel.shipping_zones.clear()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesUpdate"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+ assert errors[0]["field"] == "quantity"+++def test_checkout_lines_update_variant_quantity_over_avability_stock(+ user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ current_stock = line.variant.stocks.first()+ line.quantity = current_stock.quantity - 1+ line.save()++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": current_stock.quantity - 2}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesUpdate"]+ assert data["checkout"]["lines"][0]["quantity"] == variables["lines"][0]["quantity"]+++def test_checkout_lines_delete_with_by_zero_quantity_when_variant_out_of_stock(+ user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ stock = line.variant.stocks.first()+ stock.quantity = 0+ stock.save(update_fields=["quantity"])+ previous_last_change = checkout.last_change++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 0}],+ "channelSlug": checkout.channel.slug,+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesUpdate"]+ assert not data["checkout"]["lines"]+ checkout.refresh_from_db()+ assert checkout.last_change != previous_last_change+++ "saleor.graphql.checkout.mutations.checkout_lines_add."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_line_delete_by_zero_quantity(+ mocked_update_shipping_method, user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3+ previous_last_change = checkout.last_change++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 0}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 0+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)+ assert checkout.last_change != previous_last_change+++ "saleor.graphql.checkout.mutations.checkout_lines_add."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_line_delete_by_zero_quantity_when_variant_unavailable_for_purchase(+ mocked_update_shipping_method, user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ variant = line.variant+ assert line.quantity == 3+ variant.channel_listings.all().delete()+ variant.product.channel_listings.all().delete()++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 0}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 0+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)+++ "saleor.graphql.checkout.mutations.checkout_lines_add."+ "update_checkout_shipping_method_if_invalid",+ wraps=update_checkout_shipping_method_if_invalid,+)+def test_checkout_line_update_by_zero_quantity_dont_create_new_lines(+ mocked_update_shipping_method,+ user_api_client,+ checkout_with_item,+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant = line.variant+ checkout.lines.all().delete()+ assert checkout.lines.count() == 0+ previous_last_change = checkout.last_change++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 0}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 0+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)+ assert checkout.last_change != previous_last_change+++def test_checkout_lines_update_with_unpublished_product(+ user_api_client, checkout_with_item, channel_USD+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant = line.variant+ product = variant.product+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(+ is_published=False+ )++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)++ content = get_graphql_content(response)+ error = content["data"]["checkoutLinesUpdate"]["errors"][0]+ assert error["code"] == CheckoutErrorCode.PRODUCT_NOT_PUBLISHED.name+++def test_checkout_lines_update_invalid_checkout_id(user_api_client):+ variables = {"id": "1234", "lines": []}+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesUpdate"]+ assert data["errors"][0]["field"] == "id"+++def test_checkout_lines_update_check_lines_quantity(+ user_api_client, checkout_with_item+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant = line.variant++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 11}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert data["errors"][0]["message"] == (+ "Could not add items 123. Only 10 remaining in stock."+ )+ assert data["errors"][0]["field"] == "quantity"+++def test_checkout_lines_update_with_chosen_shipping(+ user_api_client, checkout, stock, address, shipping_method+):+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.save()++ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 1+++def test_checkout_lines_update_remove_shipping_if_removed_product_with_shipping(+ user_api_client, checkout_with_item, digital_content, address, shipping_method+):+ checkout = checkout_with_item+ digital_variant = digital_content.product_variant+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.save()+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())+ add_variant_to_checkout(checkout_info, digital_variant, 1)+ line = checkout.lines.first()+ variant = line.variant++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 0}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ assert not checkout.shipping_methoddiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.pynew file mode 100644index 0000000000..6fc796ca25--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py@@ -0,0 +1,251 @@+import graphene++from .....checkout.error_codes import CheckoutErrorCode+from ....core.utils import to_global_id_or_none+from ....tests.utils import get_graphql_content++MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """+ mutation($id: ID, $promoCode: String, $promoCodeId: ID) {+ checkoutRemovePromoCode(+ id: $id, promoCode: $promoCode, promoCodeId: $promoCodeId) {+ errors {+ field+ code+ message+ }+ checkout {+ token,+ voucherCode+ giftCards {+ id+ last4CodeChars+ }+ }+ }+ }+"""+++def _mutate_checkout_remove_promo_code(client, variables):+ response = client.post_graphql(MUTATION_CHECKOUT_REMOVE_PROMO_CODE, variables)+ content = get_graphql_content(response)+ return content["data"]["checkoutRemovePromoCode"]+++def test_checkout_remove_voucher_code(api_client, checkout_with_voucher):+ assert checkout_with_voucher.voucher_code is not None+ previous_checkout_last_change = checkout_with_voucher.last_change++ variables = {+ "id": to_global_id_or_none(checkout_with_voucher),+ "promoCode": checkout_with_voucher.voucher_code,+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ checkout_with_voucher.refresh_from_db()+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_voucher.token)+ assert data["checkout"]["voucherCode"] is None+ assert checkout_with_voucher.voucher_code is None+ assert checkout_with_voucher.last_change != previous_checkout_last_change+++def test_checkout_remove_voucher_code_with_inactive_channel(+ api_client, checkout_with_voucher+):+ channel = checkout_with_voucher.channel+ channel.is_active = False+ channel.save()+ previous_checkout_last_change = checkout_with_voucher.last_change++ variables = {+ "id": to_global_id_or_none(checkout_with_voucher),+ "promoCode": checkout_with_voucher.voucher_code,+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ checkout_with_voucher.refresh_from_db()+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_voucher.token)+ assert data["checkout"]["voucherCode"] == checkout_with_voucher.voucher_code+ assert checkout_with_voucher.last_change == previous_checkout_last_change+++def test_checkout_remove_gift_card_code(api_client, checkout_with_gift_card):+ assert checkout_with_gift_card.gift_cards.count() == 1+ previous_checkout_last_change = checkout_with_gift_card.last_change++ variables = {+ "id": to_global_id_or_none(checkout_with_gift_card),+ "promoCode": checkout_with_gift_card.gift_cards.first().code,+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["checkout"]["token"] == str(checkout_with_gift_card.token)+ assert data["checkout"]["giftCards"] == []+ assert not checkout_with_gift_card.gift_cards.all().exists()+ checkout_with_gift_card.refresh_from_db()+ assert checkout_with_gift_card.last_change != previous_checkout_last_change+++def test_checkout_remove_one_of_gift_cards(+ api_client, checkout_with_gift_card, gift_card_created_by_staff+):+ checkout_with_gift_card.gift_cards.add(gift_card_created_by_staff)+ checkout_with_gift_card.save()+ previous_checkout_last_change = checkout_with_gift_card.last_change+ gift_card_first = checkout_with_gift_card.gift_cards.first()+ gift_card_last = checkout_with_gift_card.gift_cards.last()++ variables = {+ "id": to_global_id_or_none(checkout_with_gift_card),+ "promoCode": gift_card_first.code,+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ checkout_gift_cards = checkout_with_gift_card.gift_cards+ assert data["checkout"]["token"] == str(checkout_with_gift_card.token)+ assert checkout_gift_cards.filter(code=gift_card_last.code).exists()+ assert not checkout_gift_cards.filter(code=gift_card_first.code).exists()+ checkout_with_gift_card.refresh_from_db()+ assert checkout_with_gift_card.last_change != previous_checkout_last_change+++def test_checkout_remove_promo_code_invalid_promo_code(api_client, checkout_with_item):+ previous_checkout_last_change = checkout_with_item.last_change+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "promoCode": "unexisting_code",+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ checkout_with_item.refresh_from_db()+ assert checkout_with_item.last_change == previous_checkout_last_change+++def test_checkout_remove_promo_code_invalid_checkout(api_client, voucher, checkout):+ variables = {"id": to_global_id_or_none(checkout), "promoCode": voucher.code}+ checkout.delete()++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["field"] == "id"+++def test_checkout_remove_voucher_code_by_id(+ api_client, checkout_with_voucher, voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None+ checkout_with_voucher.gift_cards.add(gift_card)++ variables = {+ "id": to_global_id_or_none(checkout_with_voucher),+ "promoCodeId": graphene.Node.to_global_id("Voucher", voucher.id),+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ checkout_with_voucher.refresh_from_db()+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_voucher.token)+ assert data["checkout"]["voucherCode"] is None+ assert len(data["checkout"]["giftCards"]) == 1+ assert checkout_with_voucher.voucher_code is None+++def test_checkout_remove_gift_card_by_id(+ api_client, checkout_with_voucher, gift_card, gift_card_expiry_date+):+ assert checkout_with_voucher.voucher_code is not None+ checkout_with_voucher.gift_cards.add(gift_card, gift_card_expiry_date)++ variables = {+ "id": to_global_id_or_none(checkout_with_voucher),+ "promoCodeId": graphene.Node.to_global_id("GiftCard", gift_card.id),+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ checkout_with_voucher.refresh_from_db()+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout_with_voucher.token)+ assert data["checkout"]["voucherCode"] is not None+ gift_cards = data["checkout"]["giftCards"]+ assert len(gift_cards) == 1+ assert gift_cards[0]["id"] == graphene.Node.to_global_id(+ "GiftCard", gift_card_expiry_date.pk+ )+++def test_checkout_remove_promo_code_id_and_code_given(+ api_client, checkout_with_voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None++ variables = {+ "token": checkout_with_voucher.token,+ "promoCode": checkout_with_voucher.voucher_code,+ "promoCodeId": graphene.Node.to_global_id("GiftCard", gift_card.id),+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name+++def test_checkout_remove_promo_code_no_id_and_code_given(+ api_client, checkout_with_voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None++ variables = {+ "token": checkout_with_voucher.token,+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name+++def test_checkout_remove_promo_code_id_does_not_exist(+ api_client, checkout_with_voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None++ variables = {+ "token": checkout_with_voucher.token,+ "promoCodeId": "Abc",+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name+ assert data["errors"][0]["field"] == "promoCodeId"+++def test_checkout_remove_promo_code_invalid_object_type(+ api_client, checkout_with_voucher, gift_card+):+ assert checkout_with_voucher.voucher_code is not None++ variables = {+ "token": checkout_with_voucher.token,+ "promoCodeId": graphene.Node.to_global_id("Product", gift_card.id),+ }++ data = _mutate_checkout_remove_promo_code(api_client, variables)++ assert data["errors"]+ assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name+ assert data["errors"][0]["field"] == "promoCodeId"diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.pyindex 19aeff40d8..42bfd934fa 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py@@ -8,7 +8,7 @@ from django.utils import timezonefrom .....checkout.error_codes import CheckoutErrorCodefrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.models import Checkout-from .....checkout.utils import add_variant_to_checkout+from .....checkout.utils import add_variant_to_checkout, add_voucher_to_checkoutfrom .....plugins.base_plugin import ExcludedShippingMethodfrom .....plugins.manager import get_plugins_managerfrom .....warehouse.models import Reservation, Stock@@ -427,3 +427,77 @@ def test_checkout_shipping_address_update_exclude_shipping_method(user_api_client.post_graphql(MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables)checkout.refresh_from_db()assert checkout.shipping_method is None+++def test_checkout_update_shipping_address_with_digital(+ api_client, checkout_with_digital_item, graphql_address_data+):+ """Test updating the shipping address of a digital order throws an error."""++ checkout = checkout_with_digital_item+ variables = {+ "id": to_global_id_or_none(checkout),+ "shippingAddress": graphql_address_data,+ }++ response = api_client.post_graphql(+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutShippingAddressUpdate"]++ assert data["errors"] == [+ {+ "field": "shippingAddress",+ "message": "This checkout doesn't need shipping",+ "code": CheckoutErrorCode.SHIPPING_NOT_REQUIRED.name,+ }+ ]++ # Ensure the address was unchanged+ checkout.refresh_from_db(fields=["shipping_address"])+ assert checkout.shipping_address is None+++def test_checkout_shipping_address_update_with_not_applicable_voucher(+ user_api_client,+ checkout_with_item,+ voucher_shipping_type,+ graphql_address_data,+ address_other_country,+ shipping_method,+):+ assert checkout_with_item.shipping_address is None+ assert checkout_with_item.voucher_code is None++ checkout_with_item.shipping_address = address_other_country+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])+ assert checkout_with_item.shipping_address.country == address_other_country.country++ voucher = voucher_shipping_type+ assert voucher.countries[0].code == address_other_country.country++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)+ add_voucher_to_checkout(manager, checkout_info, lines, voucher)+ assert checkout_with_item.voucher_code == voucher.code++ new_address = graphql_address_data+ variables = {+ "id": to_global_id_or_none(checkout_with_item),+ "shippingAddress": new_address,+ }+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutShippingAddressUpdate"]+ assert not data["errors"]++ checkout_with_item.refresh_from_db()+ checkout_with_item.shipping_address.refresh_from_db()++ assert checkout_with_item.shipping_address.country == new_address["country"]+ assert checkout_with_item.voucher_code is Nonediff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.pynew file mode 100644index 0000000000..00923b50e7--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py@@ -0,0 +1,386 @@+from unittest import mock+from unittest.mock import patch++import graphene+import pytest++from .....checkout.error_codes import CheckoutErrorCode+from .....checkout.fetch import (+ fetch_checkout_info,+ fetch_checkout_lines,+ get_delivery_method_info,+)+from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID+from .....plugins.base_plugin import ExcludedShippingMethod+from .....plugins.manager import get_plugins_manager+from .....shipping import models as shipping_models+from .....shipping.utils import convert_to_shipping_method_data+from ....core.utils import to_global_id_or_none+from ....tests.utils import get_graphql_content++MUTATION_UPDATE_SHIPPING_METHOD = """+ mutation checkoutShippingMethodUpdate(+ $id: ID, $shippingMethodId: ID!){+ checkoutShippingMethodUpdate(+ id: $id, shippingMethodId: $shippingMethodId) {+ errors {+ field+ message+ code+ }+ checkout {+ token+ }+ }+ }+"""+++# TODO: Deprecated[email protected]("is_valid_shipping_method", (True, False))+@patch(+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update."+ "clean_delivery_method"+)+def test_checkout_shipping_method_update(+ mock_clean_shipping,+ staff_api_client,+ shipping_method,+ checkout_with_item_and_shipping_method,+ is_valid_shipping_method,+):+ checkout = checkout_with_item_and_shipping_method+ old_shipping_method = checkout.shipping_method+ query = MUTATION_UPDATE_SHIPPING_METHOD+ mock_clean_shipping.return_value = is_valid_shipping_method+ previous_last_change = checkout.last_change++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query, {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id}+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]+ checkout.refresh_from_db()++ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)+ checkout_info.delivery_method_info = get_delivery_method_info(+ convert_to_shipping_method_data(+ old_shipping_method, old_shipping_method.channel_listings.first()+ ),+ None,+ )+ mock_clean_shipping.assert_called_once_with(+ checkout_info=checkout_info,+ lines=lines,+ method=convert_to_shipping_method_data(+ shipping_method, shipping_method.channel_listings.first()+ ),+ )+ errors = data["errors"]+ if is_valid_shipping_method:+ assert not errors+ assert data["checkout"]["token"] == str(checkout.token)+ assert checkout.shipping_method == shipping_method+ assert checkout.last_change != previous_last_change+ else:+ assert len(errors) == 1+ assert errors[0]["field"] == "shippingMethod"+ assert (+ errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name+ )+ assert checkout.shipping_method == old_shipping_method+ assert checkout.last_change == previous_last_change++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_checkout_shipping_method_update_external_shipping_method(+ mock_send_request,+ staff_api_client,+ address,+ checkout_with_item,+ shipping_app,+ channel_USD,+ settings,+):+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ response_method_id = "abcd"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ mock_send_request.return_value = mock_json_response++ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])++ method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_SHIPPING_METHOD,+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]+ checkout.refresh_from_db()++ errors = data["errors"]+ assert not errors+ assert data["checkout"]["token"] == str(checkout_with_item.token)+ assert PRIVATE_META_APP_SHIPPING_ID in checkout.private_metadata++[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_checkout_shipping_method_update_external_shipping_method_with_tax_plugin(+ mock_send_request,+ staff_api_client,+ address,+ checkout_with_item,+ shipping_app,+ channel_USD,+ settings,+):+ settings.PLUGINS = [+ "saleor.plugins.tests.sample_plugins.PluginSample",+ "saleor.plugins.webhook.plugin.WebhookPlugin",+ ]+ response_method_id = "abcd"+ mock_json_response = [+ {+ "id": response_method_id,+ "name": "Provider - Economy",+ "amount": "10",+ "currency": "USD",+ "maximum_delivery_days": "7",+ }+ ]+ mock_send_request.return_value = mock_json_response++ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save()++ method_id = graphene.Node.to_global_id(+ "app", f"{shipping_app.id}:{response_method_id}"+ )++ # Set external shipping method for first time+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_SHIPPING_METHOD,+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]+ assert not data["errors"]++ # Set external shipping for second time+ # Without a fix this request results in infinite recursion+ # between Avalara and Webhooks plugins+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_SHIPPING_METHOD,+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]+ assert not data["errors"]+++ "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"+)+def test_checkout_shipping_method_update_excluded_webhook(+ mocked_webhook,+ staff_api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ # given+ webhook_reason = "spanish-inquisition"+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_SHIPPING_METHOD+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)+ mocked_webhook.return_value = [+ ExcludedShippingMethod(shipping_method.id, webhook_reason)+ ]++ # when+ response = staff_api_client.post_graphql(+ query,+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]++ checkout.refresh_from_db()++ # then+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "shippingMethod"+ assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name+ assert checkout.shipping_method is None+++# Deprecated+@patch("saleor.shipping.postal_codes.is_shipping_method_applicable_for_postal_code")+def test_checkout_shipping_method_update_excluded_postal_code(+ mock_is_shipping_method_available,+ staff_api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_SHIPPING_METHOD+ mock_is_shipping_method_available.return_value = False++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query,+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]++ checkout.refresh_from_db()++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "shippingMethod"+ assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name+ assert checkout.shipping_method is None+ assert (+ mock_is_shipping_method_available.call_count+ == shipping_models.ShippingMethod.objects.count()+ )+++def test_checkout_delivery_method_update_unavailable_variant(+ staff_api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ checkout_with_item.lines.first().variant.channel_listings.filter(+ channel=checkout_with_item.channel+ ).delete()+ query = MUTATION_UPDATE_SHIPPING_METHOD++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query,+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]++ checkout.refresh_from_db()++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "lines"+ assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name+++# Deprecated+def test_checkout_shipping_method_update_shipping_zone_without_channel(+ staff_api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ shipping_method.shipping_zone.channels.clear()+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_SHIPPING_METHOD++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query,+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]++ checkout.refresh_from_db()++ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "shippingMethod"+ assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name+ assert checkout.shipping_method is None+++# Deprecated+def test_checkout_shipping_method_update_shipping_zone_with_channel(+ staff_api_client,+ shipping_method,+ checkout_with_item,+ address,+):+ checkout = checkout_with_item+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])+ query = MUTATION_UPDATE_SHIPPING_METHOD++ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)++ response = staff_api_client.post_graphql(+ query,+ {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},+ )+ data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]++ checkout.refresh_from_db()++ checkout.refresh_from_db()+ errors = data["errors"]+ assert not errors+ assert data["checkout"]["token"] == str(checkout_with_item.token)++ assert checkout.shipping_method == shipping_method+++def test_checkout_update_shipping_method_with_digital(+ api_client, checkout_with_digital_item, address, shipping_method+):+ """Test updating the shipping method of a digital order throws an error."""++ checkout = checkout_with_digital_item+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.pk)+ variables = {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id}++ # Put a shipping address, to ensure it is still handled properly+ checkout.shipping_address = address+ checkout.save(update_fields=["shipping_address"])++ response = api_client.post_graphql(MUTATION_UPDATE_SHIPPING_METHOD, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkoutShippingMethodUpdate"]++ assert data["errors"] == [+ {+ "field": "shippingMethod",+ "message": "This checkout doesn't need shipping",+ "code": CheckoutErrorCode.SHIPPING_NOT_REQUIRED.name,+ }+ ]++ # Ensure the shipping method was unchanged+ checkout.refresh_from_db(fields=["shipping_method"])+ assert checkout.shipping_method is Nonediff --git a/saleor/graphql/checkout/tests/mutations/test_utils.py b/saleor/graphql/checkout/tests/mutations/test_utils.pynew file mode 100644index 0000000000..046ea2c76d--- /dev/null+++ b/saleor/graphql/checkout/tests/mutations/test_utils.py@@ -0,0 +1,80 @@+import pytest++from ...mutations.utils import (+ CheckoutLineData,+ group_quantity_and_custom_prices_by_variants,+)+++ "lines, expected",+ [+ (+ [+ {"quantity": 6, "variant_id": "abc", "price": 1.22},+ {"quantity": 6, "variant_id": "abc"},+ {"quantity": 1, "variant_id": "def", "price": 33.2},+ {"quantity": 1, "variant_id": "def", "price": 10},+ ],+ [+ CheckoutLineData(+ quantity=12,+ quantity_to_update=True,+ custom_price=1.22,+ custom_price_to_update=True,+ ),+ CheckoutLineData(+ quantity=2,+ quantity_to_update=True,+ custom_price=10,+ custom_price_to_update=True,+ ),+ ],+ ),+ (+ [+ {"quantity": 8, "variant_id": "ghi"},+ {"quantity": 2, "variant_id": "ghi"},+ {"quantity": 6, "variant_id": "abc"},+ {"quantity": 1, "variant_id": "def"},+ {"quantity": 6, "variant_id": "abc"},+ {"quantity": 1, "variant_id": "def"},+ {"quantity": 8, "variant_id": "ghi"},+ {"quantity": 2, "variant_id": "ghi"},+ {"quantity": 922, "variant_id": "xyz"},+ {"quantity": 6, "variant_id": "abc"},+ {"quantity": 1, "variant_id": "def"},+ {"quantity": 6, "variant_id": "abc"},+ {"quantity": 1, "variant_id": "def"},+ {"quantity": 1000, "variant_id": "jkl"},+ {"quantity": 999, "variant_id": "zzz"},+ ],+ [+ CheckoutLineData(+ quantity=quantity,+ quantity_to_update=True,+ custom_price=None,+ custom_price_to_update=False,+ )+ for quantity in [20, 24, 4, 922, 1000, 999]+ ],+ ),+ (+ [+ {"quantity": 100, "variant_id": name}+ for name in (l1 + l2 for l1 in "abcdef" for l2 in "ghijkl")+ ],+ [+ CheckoutLineData(+ quantity=100,+ quantity_to_update=True,+ custom_price=None,+ custom_price_to_update=False,+ )+ ]+ * 36,+ ),+ ],+)+def test_group_by_variants(lines, expected):+ assert expected == group_quantity_and_custom_prices_by_variants(lines)diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 102f4cff40..5ea28746c0 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -1,7 +1,6 @@import datetimefrom decimal import Decimalfrom unittest import mock-from unittest.mock import patchimport grapheneimport pytest@@ -14,28 +13,18 @@ from django_countries.fields import Countryfrom measurement.measures import Weightfrom prices import Money-from ....account.models import Userfrom ....checkout import base_calculations, calculationsfrom ....checkout.checkout_cleaner import (clean_checkout_payment,clean_checkout_shipping,)from ....checkout.error_codes import CheckoutErrorCode-from ....checkout.fetch import (- fetch_checkout_info,- fetch_checkout_lines,- get_delivery_method_info,-)-from ....checkout.utils import PRIVATE_META_APP_SHIPPING_ID-from ....core.payments import PaymentInterface+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....core.prices import quantize_price-from ....payment import TransactionAction, TransactionKind-from ....payment.interface import GatewayResponse-from ....plugins.base_plugin import ExcludedShippingMethod+from ....payment import TransactionActionfrom ....plugins.manager import get_plugins_managerfrom ....plugins.tests.sample_plugins import ActiveDummyPaymentGatewayfrom ....product.models import ProductVariant-from ....shipping import models as shipping_modelsfrom ....shipping.models import ShippingMethodTranslationfrom ....shipping.utils import convert_to_shipping_method_datafrom ....tests.utils import dummy_editorjs@@ -878,184 +867,6 @@ def test_checkout_avail_collect_fallbacks_to_channel_country_when_no_shipping_ad]-MUTATION_CHECKOUT_CUSTOMER_ATTACH = """- mutation checkoutCustomerAttach($id: ID, $customerId: ID) {- checkoutCustomerAttach(id: $id, customerId: $customerId) {- checkout {- token- }- errors {- code- field- message- }- }- }-"""---def test_checkout_customer_attach(- user_api_client, checkout_with_item, customer_user, permission_impersonate_user-):- checkout = checkout_with_item- checkout.email = "[email protected]"- checkout.save()- assert checkout.user is None- previous_last_change = checkout.last_change-- query = MUTATION_CHECKOUT_CUSTOMER_ATTACH- customer_id = graphene.Node.to_global_id("User", customer_user.pk)- variables = {"id": to_global_id_or_none(checkout), "customerId": customer_id}-- response = user_api_client.post_graphql(- query, variables, permissions=[permission_impersonate_user]- )- content = get_graphql_content(response)-- data = content["data"]["checkoutCustomerAttach"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.user == customer_user- assert checkout.email == customer_user.email- assert checkout.last_change != previous_last_change---def test_checkout_customer_attach_no_customer_id(- api_client, user_api_client, checkout_with_item, customer_user-):- checkout = checkout_with_item- checkout.email = "[email protected]"- checkout.save()- assert checkout.user is None- previous_last_change = checkout.last_change-- query = MUTATION_CHECKOUT_CUSTOMER_ATTACH- variables = {"id": to_global_id_or_none(checkout)}-- # Mutation should fail for unauthenticated customers- response = api_client.post_graphql(query, variables)- assert_no_permission(response)-- # Mutation should succeed for authenticated customer- response = user_api_client.post_graphql(query, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutCustomerAttach"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.user == customer_user- assert checkout.email == customer_user.email- assert checkout.last_change != previous_last_change---def test_checkout_customer_attach_by_app(- app_api_client, checkout_with_item, customer_user, permission_impersonate_user-):- checkout = checkout_with_item- checkout.email = "[email protected]"- checkout.save()- assert checkout.user is None- previous_last_change = checkout.last_change-- query = MUTATION_CHECKOUT_CUSTOMER_ATTACH- customer_id = graphene.Node.to_global_id("User", customer_user.pk)- variables = {"id": to_global_id_or_none(checkout), "customerId": customer_id}-- # Mutation should succeed for authenticated customer- response = app_api_client.post_graphql(- query, variables, permissions=[permission_impersonate_user]- )- content = get_graphql_content(response)- data = content["data"]["checkoutCustomerAttach"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.user == customer_user- assert checkout.email == customer_user.email- assert checkout.last_change != previous_last_change---def test_checkout_customer_attach_by_app_no_customer_id(- app_api_client, checkout_with_item, permission_impersonate_user-):- checkout = checkout_with_item- checkout.email = "[email protected]"- checkout.save()- assert checkout.user is None-- query = MUTATION_CHECKOUT_CUSTOMER_ATTACH- variables = {"id": to_global_id_or_none(checkout)}-- # Mutation should succeed for authenticated customer- response = app_api_client.post_graphql(- query,- variables,- permissions=[permission_impersonate_user],- check_no_permissions=False,- )- content = get_graphql_content(response)- data = content["data"]["checkoutCustomerAttach"]- assert len(data["errors"]) == 1- assert data["errors"][0]["code"] == CheckoutErrorCode.REQUIRED.name- assert data["errors"][0]["field"] == "customerId"---def test_checkout_customer_attach_by_app_without_permission(- app_api_client, checkout_with_item, customer_user-):- checkout = checkout_with_item- checkout.email = "[email protected]"- checkout.save()- assert checkout.user is None-- query = MUTATION_CHECKOUT_CUSTOMER_ATTACH- customer_id = graphene.Node.to_global_id("User", customer_user.pk)- variables = {"id": to_global_id_or_none(checkout), "customerId": customer_id}-- # Mutation should succeed for authenticated customer- response = app_api_client.post_graphql(- query,- variables,- )-- assert_no_permission(response)---def test_checkout_customer_attach_user_to_checkout_with_user(- user_api_client, customer_user, user_checkout, address-):- checkout = user_checkout-- query = """- mutation checkoutCustomerAttach($id: ID) {- checkoutCustomerAttach(id: $id) {- checkout {- token- }- errors {- field- message- code- }- }- }-"""-- default_address = address.get_copy()- second_user = User.objects.create_user(- "[email protected]",- "password",- default_billing_address=default_address,- default_shipping_address=default_address,- first_name="Test2",- last_name="Tested",- )-- checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)- customer_id = graphene.Node.to_global_id("User", second_user.pk)- variables = {"id": checkout_id, "customerId": customer_id}- response = user_api_client.post_graphql(query, variables)- assert_no_permission(response)--GET_CHECKOUT_STOCK_RESERVATION_EXPIRES_QUERY = """query getCheckoutStockReservationExpiration($id: ID) {checkout(id: $id) {@@ -1195,173 +1006,21 @@ def test_checkout_reservation_date_for_disabled_reservations(assert content["data"]["checkout"]["stockReservationExpires"] is None-MUTATION_CHECKOUT_CUSTOMER_DETACH = """- mutation checkoutCustomerDetach($id: ID) {- checkoutCustomerDetach(id: $id) {- checkout {- token- }- errors {- field- message- }- }- }- """---def test_checkout_customer_detach(user_api_client, checkout_with_item, customer_user):- checkout = checkout_with_item- checkout.user = customer_user- checkout.save(update_fields=["user"])- previous_last_change = checkout.last_change-- variables = {"id": to_global_id_or_none(checkout)}-- # Mutation should succeed if the user owns this checkout.- response = user_api_client.post_graphql(- MUTATION_CHECKOUT_CUSTOMER_DETACH, variables- )- content = get_graphql_content(response)- data = content["data"]["checkoutCustomerDetach"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.user is None- assert checkout.last_change != previous_last_change-- # Mutation should fail when user calling it doesn't own the checkout.- other_user = User.objects.create_user("[email protected]", "password")- checkout.user = other_user- checkout.save()- response = user_api_client.post_graphql(- MUTATION_CHECKOUT_CUSTOMER_DETACH, variables- )- assert_no_permission(response)---def test_checkout_customer_detach_by_app(- app_api_client, checkout_with_item, customer_user, permission_impersonate_user-):- checkout = checkout_with_item- checkout.user = customer_user- checkout.save(update_fields=["user"])- previous_last_change = checkout.last_change-- variables = {"id": to_global_id_or_none(checkout)}-- # Mutation should succeed if the user owns this checkout.- response = app_api_client.post_graphql(- MUTATION_CHECKOUT_CUSTOMER_DETACH,- variables,- permissions=[permission_impersonate_user],- )- content = get_graphql_content(response)- data = content["data"]["checkoutCustomerDetach"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.user is None- assert checkout.last_change != previous_last_change---def test_checkout_customer_detach_by_app_without_permissions(- app_api_client, checkout_with_item, customer_user-):- checkout = checkout_with_item- checkout.user = customer_user- checkout.save(update_fields=["user"])- previous_last_change = checkout.last_change-- variables = {"id": to_global_id_or_none(checkout)}-- # Mutation should succeed if the user owns this checkout.- response = app_api_client.post_graphql(MUTATION_CHECKOUT_CUSTOMER_DETACH, variables)-- assert_no_permission(response)- checkout.refresh_from_db()- assert checkout.last_change == previous_last_change---CHECKOUT_EMAIL_UPDATE_MUTATION = """- mutation checkoutEmailUpdate($id: ID, $email: String!) {- checkoutEmailUpdate(id: $id, email: $email) {- checkout {- id,- },- errors {- field,- message- }- errors {- field,- message- code- }- }- }-"""---def test_checkout_email_update(user_api_client, checkout_with_item):- checkout = checkout_with_item- checkout.email = None- checkout.save(update_fields=["email"])- previous_last_change = checkout.last_change-- email = "[email protected]"- variables = {"id": to_global_id_or_none(checkout), "email": email}-- response = user_api_client.post_graphql(CHECKOUT_EMAIL_UPDATE_MUTATION, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutEmailUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.email == email- assert checkout.last_change != previous_last_change---def test_checkout_email_update_validation(user_api_client, checkout_with_item):- variables = {"id": to_global_id_or_none(checkout_with_item), "email": ""}-- response = user_api_client.post_graphql(CHECKOUT_EMAIL_UPDATE_MUTATION, variables)- content = get_graphql_content(response)- previous_last_change = checkout_with_item.last_change-- errors = content["data"]["checkoutEmailUpdate"]["errors"]- assert errors- assert errors[0]["field"] == "email"- assert errors[0]["message"] == "This field cannot be blank."-- checkout_errors = content["data"]["checkoutEmailUpdate"]["errors"]- assert checkout_errors[0]["code"] == CheckoutErrorCode.REQUIRED.name- assert checkout_with_item.last_change == previous_last_change-+# @pytest.fixture+# def fake_manager(mocker):+# return mocker.Mock(spec=PaymentInterface)-def fake_manager(mocker):- return mocker.Mock(spec=PaymentInterface)+# @pytest.fixture+# def mock_get_manager(mocker, fake_manager):+# manager = mocker.patch(+# "saleor.payment.gateway.get_plugins_manager",+# autospec=True,+# return_value=fake_manager,+# )+# yield fake_manager+# manager.assert_called_once()-def mock_get_manager(mocker, fake_manager):- manager = mocker.patch(- "saleor.payment.gateway.get_plugins_manager",- autospec=True,- return_value=fake_manager,- )- yield fake_manager- manager.assert_called_once()---TRANSACTION_CONFIRM_GATEWAY_RESPONSE = GatewayResponse(- is_success=False,- action_required=False,- kind=TransactionKind.CONFIRM,- amount=Decimal(3.0),- currency="usd",- transaction_id="1234",- error=None,-)QUERY_CHECKOUT_USER_ID = """query getCheckout($id: ID) {@@ -2013,688 +1672,6 @@ def test_checkout_prices_with_voucher_once_per_order()-MUTATION_UPDATE_SHIPPING_METHOD = """- mutation checkoutShippingMethodUpdate(- $id: ID, $shippingMethodId: ID!){- checkoutShippingMethodUpdate(- id: $id, shippingMethodId: $shippingMethodId) {- errors {- field- message- code- }- checkout {- token- }- }- }-"""--MUTATION_UPDATE_DELIVERY_METHOD = """- mutation checkoutDeliveryMethodUpdate(- $id: ID, $deliveryMethodId: ID) {- checkoutDeliveryMethodUpdate(- id: $id,- deliveryMethodId: $deliveryMethodId) {- checkout {- id- deliveryMethod {- __typename- ... on ShippingMethod {- name- id- translation(languageCode: EN_US) {- name- }- }- ... on Warehouse {- name- id- }- }- }- errors {- field- message- code- }- }-}-"""---# TODO: Deprecated[email protected]("is_valid_shipping_method", (True, False))-@patch(- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."- "clean_delivery_method"-)-def test_checkout_shipping_method_update(- mock_clean_shipping,- staff_api_client,- shipping_method,- checkout_with_item_and_shipping_method,- is_valid_shipping_method,-):- checkout = checkout_with_item_and_shipping_method- old_shipping_method = checkout.shipping_method- query = MUTATION_UPDATE_SHIPPING_METHOD- mock_clean_shipping.return_value = is_valid_shipping_method- previous_last_change = checkout.last_change-- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)-- response = staff_api_client.post_graphql(- query, {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id}- )- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]- checkout.refresh_from_db()-- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- checkout_info.delivery_method_info = get_delivery_method_info(- convert_to_shipping_method_data(- old_shipping_method, old_shipping_method.channel_listings.first()- ),- None,- )- mock_clean_shipping.assert_called_once_with(- checkout_info=checkout_info,- lines=lines,- method=convert_to_shipping_method_data(- shipping_method, shipping_method.channel_listings.first()- ),- )- errors = data["errors"]- if is_valid_shipping_method:- assert not errors- assert data["checkout"]["token"] == str(checkout.token)- assert checkout.shipping_method == shipping_method- assert checkout.last_change != previous_last_change- else:- assert len(errors) == 1- assert errors[0]["field"] == "shippingMethod"- assert (- errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name- )- assert checkout.shipping_method == old_shipping_method- assert checkout.last_change == previous_last_change--[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")-def test_checkout_shipping_method_update_external_shipping_method(- mock_send_request,- staff_api_client,- address,- checkout_with_item,- shipping_app,- channel_USD,- settings,-):- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- response_method_id = "abcd"- mock_json_response = [- {- "id": response_method_id,- "name": "Provider - Economy",- "amount": "10",- "currency": "USD",- "maximum_delivery_days": "7",- }- ]- mock_send_request.return_value = mock_json_response-- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])-- method_id = graphene.Node.to_global_id(- "app", f"{shipping_app.id}:{response_method_id}"- )-- response = staff_api_client.post_graphql(- MUTATION_UPDATE_SHIPPING_METHOD,- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},- )- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]- checkout.refresh_from_db()-- errors = data["errors"]- assert not errors- assert data["checkout"]["token"] == str(checkout_with_item.token)- assert PRIVATE_META_APP_SHIPPING_ID in checkout.private_metadata--[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")-def test_checkout_shipping_method_update_external_shipping_method_with_tax_plugin(- mock_send_request,- staff_api_client,- address,- checkout_with_item,- shipping_app,- channel_USD,- settings,-):- settings.PLUGINS = [- "saleor.plugins.tests.sample_plugins.PluginSample",- "saleor.plugins.webhook.plugin.WebhookPlugin",- ]- response_method_id = "abcd"- mock_json_response = [- {- "id": response_method_id,- "name": "Provider - Economy",- "amount": "10",- "currency": "USD",- "maximum_delivery_days": "7",- }- ]- mock_send_request.return_value = mock_json_response-- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save()-- method_id = graphene.Node.to_global_id(- "app", f"{shipping_app.id}:{response_method_id}"- )-- # Set external shipping method for first time- response = staff_api_client.post_graphql(- MUTATION_UPDATE_SHIPPING_METHOD,- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},- )- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]- assert not data["errors"]-- # Set external shipping for second time- # Without a fix this request results in infinite recursion- # between Avalara and Webhooks plugins- response = staff_api_client.post_graphql(- MUTATION_UPDATE_SHIPPING_METHOD,- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},- )- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]- assert not data["errors"]--[email protected]("is_valid_delivery_method", (True, False))- "delivery_method, node_name, attribute_name",- [- ("warehouse", "Warehouse", "collection_point"),- ("shipping_method", "ShippingMethod", "shipping_method"),- ],- indirect=("delivery_method",),-)-@patch(- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."- "clean_delivery_method"-)-def test_checkout_delivery_method_update(- mock_clean_delivery,- api_client,- delivery_method,- node_name,- attribute_name,- checkout_with_item_for_cc,- is_valid_delivery_method,-):- # given- mock_clean_delivery.return_value = is_valid_delivery_method-- checkout = checkout_with_item_for_cc- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)-- shipping_method_data = delivery_method- if attribute_name == "shipping_method":- shipping_method_data = convert_to_shipping_method_data(- delivery_method,- delivery_method.channel_listings.get(),- )- query = MUTATION_UPDATE_DELIVERY_METHOD- mock_clean_delivery.return_value = is_valid_delivery_method-- method_id = graphene.Node.to_global_id(node_name, delivery_method.id)-- response = api_client.post_graphql(- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}- )- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]- checkout.refresh_from_db()-- mock_clean_delivery.assert_called_once_with(- checkout_info=checkout_info, lines=lines, method=shipping_method_data- )- errors = data["errors"]- if is_valid_delivery_method:- assert not errors- assert getattr(checkout, attribute_name) == delivery_method- else:- assert len(errors) == 1- assert errors[0]["field"] == "deliveryMethodId"- assert (- errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name- )- assert checkout.shipping_method is None- assert checkout.collection_point is None--[email protected]("is_valid_delivery_method", (True, False))[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")-@patch(- "saleor.graphql.checkout.mutations.checkout_delivery_method_update."- "clean_delivery_method"-)-def test_checkout_delivery_method_update_external_shipping(- mock_clean_delivery,- mock_send_request,- api_client,- checkout_with_item_for_cc,- is_valid_delivery_method,- settings,- shipping_app,- channel_USD,-):- checkout = checkout_with_item_for_cc- query = MUTATION_UPDATE_DELIVERY_METHOD- mock_clean_delivery.return_value = is_valid_delivery_method-- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- response_method_id = "abcd"- mock_json_response = [- {- "id": response_method_id,- "name": "Provider - Economy",- "amount": "10",- "currency": "USD",- "maximum_delivery_days": "7",- }- ]- mock_send_request.return_value = mock_json_response-- method_id = graphene.Node.to_global_id(- "app", f"{shipping_app.id}:{response_method_id}"- )-- response = api_client.post_graphql(- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}- )- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]- checkout.refresh_from_db()-- errors = data["errors"]- if is_valid_delivery_method:- assert not errors- assert PRIVATE_META_APP_SHIPPING_ID in checkout.private_metadata- assert data["checkout"]["deliveryMethod"]["id"] == method_id- else:- assert len(errors) == 1- assert errors[0]["field"] == "deliveryMethodId"- assert (- errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name- )- assert PRIVATE_META_APP_SHIPPING_ID not in checkout.private_metadata---@patch(- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."- "clean_delivery_method"-)-def test_checkout_delivery_method_update_with_id_of_different_type_causes_and_error(- mock_clean_delivery,- api_client,- checkout_with_item,- address,-):- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_DELIVERY_METHOD- mock_clean_delivery.return_value = True- invalid_method_id = graphene.Node.to_global_id("Address", address.id)-- response = api_client.post_graphql(- query,- {- "id": to_global_id_or_none(checkout),- "deliveryMethodId": invalid_method_id,- },- )- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]- checkout.refresh_from_db()-- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["field"] == "deliveryMethodId"- assert errors[0]["code"] == CheckoutErrorCode.INVALID.name- assert checkout.shipping_method is None- assert checkout.collection_point is None---@patch(- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."- "clean_delivery_method"-)-def test_checkout_delivery_method_with_nonexistant_id_results_not_found(- mock_clean_delivery,- api_client,- warehouse_for_cc,- checkout_with_item,- address,-):- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_DELIVERY_METHOD- mock_clean_delivery.return_value = True-- nonexistant_id = "YXBwOjEyMzQ6c29tZS1pZA=="- response = api_client.post_graphql(- query,- {- "id": to_global_id_or_none(checkout),- "deliveryMethodId": nonexistant_id,- },- )- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]- checkout.refresh_from_db()-- assert not data["checkout"]- assert data["errors"][0]["field"] == "deliveryMethodId"- assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name- assert checkout.shipping_method is None- assert checkout.collection_point is None---@patch(- "saleor.graphql.checkout.mutations.checkout_shipping_method_update."- "clean_delivery_method"-)-def test_checkout_delivery_method_with_empty_fields_results_None(- mock_clean_delivery,- api_client,- warehouse_for_cc,- checkout_with_item,- address,-):- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_DELIVERY_METHOD- mock_clean_delivery.return_value = True-- response = api_client.post_graphql(- query,- {- "id": to_global_id_or_none(checkout),- },- )- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]- checkout.refresh_from_db()-- assert not data["errors"]- assert data["checkout"]["deliveryMethod"] is None- assert checkout.shipping_method is None- assert checkout.collection_point is None--- "saleor.plugins.manager.PluginsManager.excluded_shipping_methods_for_checkout"-)-def test_checkout_shipping_method_update_excluded_webhook(- mocked_webhook,- staff_api_client,- shipping_method,- checkout_with_item,- address,-):- # given- webhook_reason = "spanish-inquisition"- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_SHIPPING_METHOD- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)- mocked_webhook.return_value = [- ExcludedShippingMethod(shipping_method.id, webhook_reason)- ]-- # when- response = staff_api_client.post_graphql(- query,- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},- )- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]-- checkout.refresh_from_db()-- # then- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["field"] == "shippingMethod"- assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name- assert checkout.shipping_method is None---# Deprecated-@patch("saleor.shipping.postal_codes.is_shipping_method_applicable_for_postal_code")-def test_checkout_shipping_method_update_excluded_postal_code(- mock_is_shipping_method_available,- staff_api_client,- shipping_method,- checkout_with_item,- address,-):- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_SHIPPING_METHOD- mock_is_shipping_method_available.return_value = False-- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)-- response = staff_api_client.post_graphql(- query,- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},- )- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]-- checkout.refresh_from_db()-- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["field"] == "shippingMethod"- assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name- assert checkout.shipping_method is None- assert (- mock_is_shipping_method_available.call_count- == shipping_models.ShippingMethod.objects.count()- )---def test_checkout_delivery_method_update_unavailable_variant(- staff_api_client,- shipping_method,- checkout_with_item,- address,-):- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- checkout_with_item.lines.first().variant.channel_listings.filter(- channel=checkout_with_item.channel- ).delete()- query = MUTATION_UPDATE_SHIPPING_METHOD-- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)-- response = staff_api_client.post_graphql(- query,- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},- )- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]-- checkout.refresh_from_db()-- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["field"] == "lines"- assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name---@patch("saleor.shipping.postal_codes.is_shipping_method_applicable_for_postal_code")-def test_checkout_delivery_method_update_excluded_postal_code(- mock_is_shipping_method_available,- staff_api_client,- shipping_method,- checkout_with_item,- address,-):- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_DELIVERY_METHOD- mock_is_shipping_method_available.return_value = False-- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)-- response = staff_api_client.post_graphql(- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}- )- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]-- checkout.refresh_from_db()-- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["field"] == "deliveryMethodId"- assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name- assert checkout.shipping_method is None- assert (- mock_is_shipping_method_available.call_count- == shipping_models.ShippingMethod.objects.count()- )---# Deprecated-def test_checkout_shipping_method_update_shipping_zone_without_channel(- staff_api_client,- shipping_method,- checkout_with_item,- address,-):- shipping_method.shipping_zone.channels.clear()- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_SHIPPING_METHOD-- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)-- response = staff_api_client.post_graphql(- query,- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},- )- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]-- checkout.refresh_from_db()-- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["field"] == "shippingMethod"- assert errors[0]["code"] == CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name- assert checkout.shipping_method is None---def test_checkout_delivery_method_update_shipping_zone_without_channel(- api_client,- shipping_method,- checkout_with_item,- address,-):- shipping_method.shipping_zone.channels.clear()- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_DELIVERY_METHOD-- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)-- response = api_client.post_graphql(- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}- )- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]-- checkout.refresh_from_db()-- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["field"] == "deliveryMethodId"- assert errors[0]["code"] == CheckoutErrorCode.DELIVERY_METHOD_NOT_APPLICABLE.name- assert checkout.shipping_method is None---# Deprecated-def test_checkout_shipping_method_update_shipping_zone_with_channel(- staff_api_client,- shipping_method,- checkout_with_item,- address,-):- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_SHIPPING_METHOD-- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)-- response = staff_api_client.post_graphql(- query,- {"id": to_global_id_or_none(checkout_with_item), "shippingMethodId": method_id},- )- data = get_graphql_content(response)["data"]["checkoutShippingMethodUpdate"]-- checkout.refresh_from_db()-- checkout.refresh_from_db()- errors = data["errors"]- assert not errors- assert data["checkout"]["token"] == str(checkout_with_item.token)-- assert checkout.shipping_method == shipping_method---def test_checkout_delivery_method_update_shipping_zone_with_channel(- staff_api_client,- shipping_method,- checkout_with_item,- address,-):- checkout = checkout_with_item- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])- query = MUTATION_UPDATE_DELIVERY_METHOD-- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)-- response = staff_api_client.post_graphql(- query, {"id": to_global_id_or_none(checkout), "deliveryMethodId": method_id}- )- data = get_graphql_content(response)["data"]["checkoutDeliveryMethodUpdate"]-- checkout.refresh_from_db()-- checkout.refresh_from_db()- errors = data["errors"]- assert not errors-- assert checkout.shipping_method == shipping_method--def test_query_checkouts(checkout_with_item, staff_api_client, permission_manage_checkouts):diff --git a/saleor/graphql/checkout/tests/test_checkout_digital.py b/saleor/graphql/checkout/tests/test_checkout_digital.pyindex b25b25d4d9..2c1a0ec315 100644--- a/saleor/graphql/checkout/tests/test_checkout_digital.py+++ b/saleor/graphql/checkout/tests/test_checkout_digital.py@@ -1,67 +1,10 @@"""Test the API's checkout process over full digital orders."""-import graphene-import pytest-from ....account.models import Address-from ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from ....checkout.models import Checkout-from ....checkout.utils import add_variant_to_checkoutfrom ....plugins.manager import get_plugins_managerfrom ...core.utils import to_global_id_or_nonefrom ...tests.utils import get_graphql_contentfrom ..mutations.utils import update_checkout_shipping_method_if_invalid-from .mutations.test_checkout_create import MUTATION_CHECKOUT_CREATE-from .mutations.test_checkout_shipping_address_update import (- MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE,-)-from .test_checkout import MUTATION_UPDATE_SHIPPING_METHOD-from .test_checkout_lines import (- MUTATION_CHECKOUT_LINE_DELETE,- MUTATION_CHECKOUT_LINES_UPDATE,-)--[email protected]("with_shipping_address", (True, False))-def test_create_checkout(- api_client,- digital_content,- graphql_address_data,- with_shipping_address,- channel_USD,-):- """Test creating a checkout with a shipping address gets the address ignored."""-- address_count = Address.objects.count()-- variant = digital_content.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- checkout_input = {- "channel": channel_USD.slug,- "lines": [{"quantity": 1, "variantId": variant_id}],- "email": "[email protected]",- }-- if with_shipping_address:- checkout_input["shippingAddress"] = graphql_address_data-- get_graphql_content(- api_client.post_graphql(- MUTATION_CHECKOUT_CREATE, {"checkoutInput": checkout_input}- )- )["data"]["checkoutCreate"]-- # Retrieve the created checkout- checkout = Checkout.objects.get()-- # Check that the shipping address was ignored, thus not created- assert (- checkout.shipping_address is None- ), "The address shouldn't have been associated"- assert (- Address.objects.count() == address_count- ), "No address should have been created"def test_checkout_has_no_available_shipping_methods(@@ -96,66 +39,6 @@ def test_checkout_has_no_available_shipping_methods(assert len(data["availableShippingMethods"]) == 0-def test_checkout_update_shipping_address(- api_client, checkout_with_digital_item, graphql_address_data-):- """Test updating the shipping address of a digital order throws an error."""-- checkout = checkout_with_digital_item- variables = {- "id": to_global_id_or_none(checkout),- "shippingAddress": graphql_address_data,- }-- response = api_client.post_graphql(- MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables- )- content = get_graphql_content(response)- data = content["data"]["checkoutShippingAddressUpdate"]-- assert data["errors"] == [- {- "field": "shippingAddress",- "message": "This checkout doesn't need shipping",- "code": CheckoutErrorCode.SHIPPING_NOT_REQUIRED.name,- }- ]-- # Ensure the address was unchanged- checkout.refresh_from_db(fields=["shipping_address"])- assert checkout.shipping_address is None---def test_checkout_update_shipping_method(- api_client, checkout_with_digital_item, address, shipping_method-):- """Test updating the shipping method of a digital order throws an error."""-- checkout = checkout_with_digital_item- method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.pk)- variables = {"id": to_global_id_or_none(checkout), "shippingMethodId": method_id}-- # Put a shipping address, to ensure it is still handled properly- checkout.shipping_address = address- checkout.save(update_fields=["shipping_address"])-- response = api_client.post_graphql(MUTATION_UPDATE_SHIPPING_METHOD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutShippingMethodUpdate"]-- assert data["errors"] == [- {- "field": "shippingMethod",- "message": "This checkout doesn't need shipping",- "code": CheckoutErrorCode.SHIPPING_NOT_REQUIRED.name,- }- ]-- # Ensure the shipping method was unchanged- checkout.refresh_from_db(fields=["shipping_method"])- assert checkout.shipping_method is None--def test_remove_shipping_method_if_only_digital_in_checkout(checkout_with_digital_item, address, shipping_method):@@ -172,57 +55,3 @@ def test_remove_shipping_method_if_only_digital_in_checkout(checkout.refresh_from_db()assert not checkout.shipping_method---def test_checkout_lines_update_remove_shipping_if_removed_product_with_shipping(- user_api_client, checkout_with_item, digital_content, address, shipping_method-):- checkout = checkout_with_item- digital_variant = digital_content.product_variant- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.save()- checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())- add_variant_to_checkout(checkout_info, digital_variant, 1)- line = checkout.lines.first()- variant = line.variant-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 0}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 1- assert not checkout.shipping_method---def test_checkout_line_delete_remove_shipping_if_removed_product_with_shipping(- user_api_client, checkout_with_item, digital_content, address, shipping_method-):- checkout = checkout_with_item- digital_variant = digital_content.product_variant- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.save()- checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())- add_variant_to_checkout(checkout_info, digital_variant, 1)- line = checkout.lines.first()-- line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)-- variables = {"id": to_global_id_or_none(checkout), "lineId": line_id}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLineDelete"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 1- assert not checkout.shipping_methoddiff --git a/saleor/graphql/checkout/tests/test_checkout_lines.py b/saleor/graphql/checkout/tests/test_checkout_lines.pydeleted file mode 100644index 618f8d6c5f..0000000000--- a/saleor/graphql/checkout/tests/test_checkout_lines.py+++ /dev/null@@ -1,1811 +0,0 @@-import datetime-from decimal import Decimal-from unittest import mock--import graphene-import pytest-import pytz-from django.utils import timezone--from ....checkout.error_codes import CheckoutErrorCode-from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from ....checkout.models import Checkout, CheckoutLine-from ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity-from ....plugins.manager import get_plugins_manager-from ....product.models import ProductChannelListing-from ....warehouse import WarehouseClickAndCollectOption-from ....warehouse.models import Reservation, Stock-from ....warehouse.tests.utils import get_available_quantity_for_stock-from ...core.utils import to_global_id_or_none-from ...tests.utils import assert_no_permission, get_graphql_content-from ..mutations.utils import (- CheckoutLineData,- group_quantity_and_custom_prices_by_variants,- update_checkout_shipping_method_if_invalid,-)--MUTATION_CHECKOUT_LINES_ADD = """- mutation checkoutLinesAdd(- $id: ID, $lines: [CheckoutLineInput!]!) {- checkoutLinesAdd(id: $id, lines: $lines) {- checkout {- token- quantity- lines {- quantity- variant {- id- }- }- }- errors {- field- code- message- variants- }- }- }"""--- "saleor.graphql.checkout.mutations.checkout_lines_add."- "update_checkout_shipping_method_if_invalid",- wraps=update_checkout_shipping_method_if_invalid,-)-def test_checkout_lines_add(- mocked_update_shipping_method, user_api_client, checkout_with_item, stock-):- variant = stock.product_variant- checkout = checkout_with_item- line = checkout.lines.first()- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 3- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- previous_last_change = checkout.last_change-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- line = checkout.lines.last()- assert line.variant == variant- assert line.quantity == 1- assert calculate_checkout_quantity(lines) == 4- assert not Reservation.objects.exists()-- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)- assert checkout.last_change != previous_last_change---def test_checkout_lines_add_with_reservations(- site_settings_with_reservations, user_api_client, checkout_with_item, stock-):- variant = stock.product_variant- checkout = checkout_with_item- line = checkout.lines.first()- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 3- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- line = checkout.lines.last()- assert line.variant == variant- assert line.quantity == 1- assert calculate_checkout_quantity(lines) == 4-- reservation = line.reservations.get()- assert reservation- assert reservation.checkout_line == line- assert reservation.quantity_reserved == line.quantity---def test_checkout_lines_add_updates_reservation(- site_settings_with_reservations,- user_api_client,- checkout_line_with_one_reservation,- stock,-):- variant = checkout_line_with_one_reservation.variant- checkout = checkout_line_with_one_reservation.checkout- line = checkout_line_with_one_reservation- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 2- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- line = checkout.lines.last()- assert line.variant == variant- assert line.quantity == 3- assert calculate_checkout_quantity(lines) == 3-- reservation = line.reservations.get()- assert reservation- assert reservation.checkout_line == line- assert reservation.quantity_reserved == line.quantity---def test_checkout_lines_add_new_variant_updates_other_lines_reservations_expirations(- site_settings_with_reservations,- user_api_client,- checkout_line_with_one_reservation,- product,- warehouse,-):- variant = checkout_line_with_one_reservation.variant- checkout = checkout_line_with_one_reservation.checkout- line = checkout_line_with_one_reservation- reservation = line.reservations.get()- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 2-- variant_other = product.variants.create(sku="SKU_B")- variant_other.channel_listings.create(- channel=checkout.channel,- price_amount=Decimal(10),- cost_price_amount=Decimal(1),- currency=checkout.channel.currency_code,- )- Stock.objects.create(- product_variant=variant_other, warehouse=warehouse, quantity=15- )- variant_other_id = graphene.Node.to_global_id("ProductVariant", variant_other.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_other_id, "quantity": 3}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- line.refresh_from_db()- assert line.variant == variant- assert line.quantity == 2- new_line = checkout.lines.get(variant=variant_other)- assert new_line.variant == variant_other- assert new_line.quantity == 3- assert calculate_checkout_quantity(lines) == 5-- updated_reservation = Reservation.objects.get(checkout_line__variant=variant)- assert updated_reservation.checkout_line == line- assert updated_reservation.quantity_reserved == line.quantity- assert updated_reservation.reserved_until > reservation.reserved_until-- other_reservation = Reservation.objects.get(checkout_line__variant=variant_other)- assert other_reservation.checkout_line == new_line- assert other_reservation.quantity_reserved == new_line.quantity- assert other_reservation.reserved_until > reservation.reserved_until-- assert updated_reservation.reserved_until == other_reservation.reserved_until-- with pytest.raises(Reservation.DoesNotExist):- reservation.refresh_from_db()---def test_checkout_lines_add_existing_variant(user_api_client, checkout_with_item):- checkout = checkout_with_item- line = checkout.lines.first()- variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)- previous_last_change = checkout.last_change-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 7}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- line = checkout.lines.last()- assert line.quantity == 10- assert checkout.last_change != previous_last_change---def test_checkout_lines_add_custom_price(- app_api_client, checkout, stock, permission_handle_checkouts-):- variant = stock.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- price = Decimal("13.11")-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],- "channelSlug": checkout.channel.slug,- }- response = app_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_ADD,- variables,- permissions=[permission_handle_checkouts],- )- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- line = checkout.lines.last()- assert line.variant == variant- assert line.quantity == 1- assert line.price_override == price---def test_checkout_lines_add_existing_variant_with_custom_price(- app_api_client, checkout_with_item, permission_handle_checkouts-):- checkout = checkout_with_item- line = checkout.lines.first()- variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)- price = Decimal("13.11")-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 7, "price": price}],- "channelSlug": checkout.channel.slug,- }- response = app_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_ADD,- variables,- permissions=[permission_handle_checkouts],- )- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- line = checkout.lines.last()- assert line.quantity == 10- assert line.price_override == price---def test_checkout_lines_add_existing_variant_override_previous_custom_price(- app_api_client, checkout_with_item, permission_handle_checkouts-):- checkout = checkout_with_item- line = checkout.lines.first()- line.price_override = 8.22- line.save(update_fields=["price_override"])-- variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)- price = Decimal("13.11")-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 7, "price": price}],- "channelSlug": checkout.channel.slug,- }- response = app_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_ADD,- variables,- permissions=[permission_handle_checkouts],- )- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- line = checkout.lines.last()- assert line.quantity == 10- assert line.price_override == price---def test_checkout_lines_add_custom_price_app_no_perm(app_api_client, checkout, stock):- variant = stock.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- price = Decimal("13.11")-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],- "channelSlug": checkout.channel.slug,- }- response = app_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- assert_no_permission(response)---def test_checkout_lines_add_custom_price_permission_denied_for_staff_user(- staff_api_client, checkout, stock, permission_handle_checkouts-):- variant = stock.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- price = Decimal("13.11")-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],- "channelSlug": checkout.channel.slug,- }- response = staff_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_ADD,- variables,- permissions=[permission_handle_checkouts],- )- assert_no_permission(response)---def test_checkout_lines_add_existing_variant_over_allowed_stock(- user_api_client, checkout_with_item-):- checkout = checkout_with_item- line = checkout.lines.first()- variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)- current_stock = line.variant.stocks.first()-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": current_stock.quantity - 1}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- errors = content["data"]["checkoutLinesAdd"]["errors"]- assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name---def test_checkout_lines_add_with_unavailable_variant(- user_api_client, checkout_with_item, stock-):- variant = stock.product_variant- variant.channel_listings.filter(channel=checkout_with_item.channel).update(- price_amount=None- )- checkout = checkout_with_item- line = checkout.lines.first()- assert line.quantity == 3- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- errors = content["data"]["checkoutLinesAdd"]["errors"]- assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name- assert errors[0]["field"] == "lines"- assert errors[0]["variants"] == [variant_id]---def test_checkout_lines_add_with_insufficient_stock(- user_api_client, checkout_with_item, stock-):- variant = stock.product_variant- checkout = checkout_with_item- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 49}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- errors = content["data"]["checkoutLinesAdd"]["errors"]- assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name- assert errors[0]["field"] == "quantity"---def test_checkout_lines_add_with_reserved_insufficient_stock(- site_settings_with_reservations,- user_api_client,- checkout_with_item,- stock,- channel_USD,-):- variant = stock.product_variant- checkout = checkout_with_item- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- quantity_available = get_available_quantity_for_stock(stock)-- other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")- other_checkout_line = other_checkout.lines.create(- variant=variant,- quantity=quantity_available - 1,- )- Reservation.objects.create(- checkout_line=other_checkout_line,- stock=stock,- quantity_reserved=quantity_available - 1,- reserved_until=timezone.now() + datetime.timedelta(minutes=5),- )-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 2}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- errors = content["data"]["checkoutLinesAdd"]["errors"]- assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name- assert errors[0]["field"] == "quantity"--- "cc_option",- [- WarehouseClickAndCollectOption.ALL_WAREHOUSES,- WarehouseClickAndCollectOption.LOCAL_STOCK,- ],-)-def test_checkout_lines_for_click_and_collect_insufficient_stock(- user_api_client, checkout_with_item_for_cc, warehouse_for_cc, cc_option-):- checkout = checkout_with_item_for_cc- checkout.collection_point = warehouse_for_cc-- warehouse_for_cc.click_and_collect_option = cc_option- warehouse_for_cc.save(update_fields=["click_and_collect_option"])- checkout.refresh_from_db()-- variant = checkout.lines.last().variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 42}],- "channelSlug": checkout.channel.slug,- }-- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- errors = content["data"]["checkoutLinesAdd"]["errors"]-- assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name- assert errors[0]["field"] == "quantity"---def test_checkout_lines_add_with_zero_quantity(- user_api_client, checkout_with_item, stock-):- variant = stock.product_variant- checkout = checkout_with_item- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 0}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- errors = content["data"]["checkoutLinesAdd"]["errors"]- assert errors[0]["code"] == CheckoutErrorCode.ZERO_QUANTITY.name- assert errors[0]["field"] == "quantity"---def test_checkout_lines_add_no_channel_shipping_zones(- user_api_client, checkout_with_item, stock-):- variant = stock.product_variant- checkout = checkout_with_item- checkout.channel.shipping_zones.clear()- line = checkout.lines.first()- assert line.quantity == 3- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesAdd"]- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name- assert errors[0]["field"] == "quantity"---def test_checkout_lines_add_with_unpublished_product(- user_api_client, checkout_with_item, stock, channel_USD-):- variant = stock.product_variant- product = variant.product- ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(- is_published=False- )-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1}],- "channelSlug": checkout_with_item.channel.slug,- }-- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)-- content = get_graphql_content(response)- error = content["data"]["checkoutLinesAdd"]["errors"][0]- assert error["code"] == CheckoutErrorCode.PRODUCT_NOT_PUBLISHED.name---def test_checkout_lines_add_with_unavailable_for_purchase_product(- user_api_client, checkout_with_item, stock-):- # given- variant = stock.product_variant- product = stock.product_variant.product- product.channel_listings.update(available_for_purchase_at=None)-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1}],- }-- # when- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)-- # then- content = get_graphql_content(response)- error = content["data"]["checkoutLinesAdd"]["errors"][0]- assert error["field"] == "lines"- assert error["code"] == CheckoutErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name- assert error["variants"] == [variant_id]---def test_checkout_lines_add_with_available_for_purchase_from_tomorrow_product(- user_api_client, checkout_with_item, stock-):- # given- variant = stock.product_variant- product = stock.product_variant.product- product.channel_listings.update(- available_for_purchase_at=datetime.datetime.now(pytz.UTC)- + datetime.timedelta(days=1)- )-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1}],- }-- # when- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)-- # then- content = get_graphql_content(response)- error = content["data"]["checkoutLinesAdd"]["errors"][0]- assert error["field"] == "lines"- assert error["code"] == CheckoutErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name- assert error["variants"] == [variant_id]---def test_checkout_lines_add_too_many(user_api_client, checkout_with_item, stock):- variant = stock.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 51}],- "channelSlug": checkout_with_item.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)["data"]["checkoutLinesAdd"]-- assert content["errors"]- assert content["errors"] == [- {- "field": "quantity",- "message": "Cannot add more than 50 times this item: SKU_A.",- "code": "QUANTITY_GREATER_THAN_LIMIT",- "variants": None,- }- ]--[email protected]("is_preorder", [True, False])-def test_checkout_lines_add_too_many_after_two_trials(- user_api_client, checkout_with_item, stock, is_preorder-):- variant = stock.product_variant- variant.is_preorder = is_preorder- variant.preorder_end_date = timezone.now() + datetime.timedelta(days=1)- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- stock.quantity = 200- stock.save(update_fields=["quantity"])- variant.save(update_fields=["is_preorder", "preorder_end_date"])-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 26}],- "channelSlug": checkout_with_item.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)["data"]["checkoutLinesAdd"]-- assert not content["errors"]-- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)["data"]["checkoutLinesAdd"]-- assert content["errors"] == [- {- "field": "quantity",- "message": "Cannot add more than 50 times this item: SKU_A.",- "code": "QUANTITY_GREATER_THAN_LIMIT",- "variants": None,- }- ]---def test_checkout_lines_add_empty_checkout(user_api_client, checkout, stock):- variant = stock.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- line = checkout.lines.first()- assert line.variant == variant- assert line.quantity == 1---def test_checkout_lines_add_variant_without_inventory_tracking(- user_api_client, checkout, variant_without_inventory_tracking-):- variant = variant_without_inventory_tracking- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert not data["errors"]- checkout.refresh_from_db()- line = checkout.lines.first()- assert line.variant == variant- assert line.quantity == 1---def test_checkout_lines_add_check_lines_quantity(user_api_client, checkout, stock):- variant = stock.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 16}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- assert data["errors"][0]["message"] == (- "Could not add items SKU_A. Only 15 remaining in stock."- )- assert data["errors"][0]["field"] == "quantity"---def test_checkout_lines_invalid_variant_id(user_api_client, checkout, stock):- variant = stock.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- invalid_variant_id = "InvalidId"-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [- {"variantId": variant_id, "quantity": 1},- {"variantId": invalid_variant_id, "quantity": 3},- ],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesAdd"]- error_msg = "Could not resolve to a node with the global id list of '%s'."- assert data["errors"][0]["message"] == error_msg % [invalid_variant_id]- assert data["errors"][0]["field"] == "variantId"---MUTATION_CHECKOUT_LINES_UPDATE = """- mutation checkoutLinesUpdate(- $id: ID, $lines: [CheckoutLineUpdateInput!]!) {- checkoutLinesUpdate(id: $id, lines: $lines) {- checkout {- id- token- quantity- lines {- quantity- variant {- id- }- }- totalPrice {- gross {- amount- }- net {- amount- }- }- discount {- amount- }- }- errors {- field- code- message- variants- }- }- }- """--- "saleor.graphql.checkout.mutations.checkout_lines_add."- "update_checkout_shipping_method_if_invalid",- wraps=update_checkout_shipping_method_if_invalid,-)-def test_checkout_lines_update(- mocked_update_shipping_method, user_api_client, checkout_with_item-):- checkout = checkout_with_item- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- assert calculate_checkout_quantity(lines) == 3- line = checkout.lines.first()- variant = line.variant- assert line.quantity == 3- previous_last_change = checkout.last_change-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- line = checkout.lines.first()- assert line.variant == variant- assert line.quantity == 1- assert calculate_checkout_quantity(lines) == 1-- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)- assert checkout.last_change != previous_last_change---def test_checkout_lines_update_checkout_with_voucher(- user_api_client, checkout_with_item, voucher_percentage-):- """Ensure that discount is correct calculated when updating the checkout with- already applied discount."""- # given- channel = checkout_with_item.channel- line = checkout_with_item.lines.first()- variant = line.variant-- channel_listing = variant.channel_listings.get(channel=channel)- unit_price = variant.get_price(- variant.product, [], checkout_with_item.channel, channel_listing- )-- voucher_channel_listing = voucher_percentage.channel_listings.get(channel=channel)- voucher_channel_listing.discount_value = 100- voucher_channel_listing.save(update_fields=["discount_value"])-- checkout_with_item.voucher_code = voucher_percentage.code- checkout_with_item.discount_amount = (unit_price * line.quantity).amount- checkout_with_item.save()-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1}],- }-- # when- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)-- # then- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout_data = data["checkout"]- total_price_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]- assert total_price_gross_amount == 0- assert checkout_data["discount"]["amount"] == unit_price.amount-- checkout_with_item.refresh_from_db()- assert checkout_with_item.discount_amount == unit_price.amount---def test_checkout_lines_update_with_new_reservations(- site_settings_with_reservations,- user_api_client,- checkout_line_with_reservation_in_many_stocks,-):- assert Reservation.objects.count() == 2- checkout = checkout_line_with_reservation_in_many_stocks.checkout- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- assert calculate_checkout_quantity(lines) == 3- line = checkout.lines.first()- variant = line.variant- assert line.quantity == 3-- Stock.objects.filter(- warehouse__shipping_zones__countries__contains="US", product_variant=variant- ).update(quantity=3)-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- line = checkout.lines.first()- assert line.variant == variant- assert line.quantity == 1- assert calculate_checkout_quantity(lines) == 1-- reservation = checkout_line_with_reservation_in_many_stocks.reservations.first()- assert reservation.quantity_reserved == line.quantity-- assert Reservation.objects.count() == 1---def test_checkout_lines_update_against_reserved_stock(- site_settings_with_reservations,- user_api_client,- checkout_line,- stock,- channel_USD,-):- assert Reservation.objects.count() == 0- checkout = checkout_line.checkout- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- assert calculate_checkout_quantity(lines) == 3- variant = checkout_line.variant- assert checkout_line.quantity == 3-- other_checkout = Checkout.objects.create(channel=channel_USD, currency="USD")- other_checkout_line = other_checkout.lines.create(- variant=variant,- quantity=7,- )- reservation = Reservation.objects.create(- checkout_line=other_checkout_line,- stock=variant.stocks.first(),- quantity_reserved=7,- reserved_until=timezone.now() + datetime.timedelta(minutes=5),- )-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 5}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert data["errors"]- assert data["errors"][0]["message"] == (- "Could not add items 123. Only 3 remaining in stock."- )- assert data["errors"][0]["field"] == "quantity"-- checkout.refresh_from_db()- assert checkout.lines.count() == 1- line = checkout.lines.first()- assert line.variant == variant- assert line.quantity == 3- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 3- reservation.refresh_from_db()- assert Reservation.objects.count() == 1---def test_checkout_lines_update_other_lines_reservations_expirations(- site_settings_with_reservations,- user_api_client,- checkout_line_with_one_reservation,- product,- warehouse,-):- variant = checkout_line_with_one_reservation.variant- checkout = checkout_line_with_one_reservation.checkout- line = checkout_line_with_one_reservation- reservation = line.reservations.get()- checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 2-- variant_other = product.variants.create(sku="SKU_B")- variant_other.channel_listings.create(- channel=checkout.channel,- price_amount=Decimal(10),- cost_price_amount=Decimal(1),- currency=checkout.channel.currency_code,- )- Stock.objects.create(- product_variant=variant_other, warehouse=warehouse, quantity=15- )- add_variant_to_checkout(checkout_info, variant_other, 2)- variant_other_id = graphene.Node.to_global_id("ProductVariant", variant_other.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_other_id, "quantity": 3}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- line.refresh_from_db()- assert line.variant == variant- assert line.quantity == 2- new_line = checkout.lines.get(variant=variant_other)- assert new_line.variant == variant_other- assert new_line.quantity == 3- assert calculate_checkout_quantity(lines) == 5-- updated_reservation = Reservation.objects.get(checkout_line__variant=variant)- assert updated_reservation.checkout_line == line- assert updated_reservation.quantity_reserved == line.quantity- assert updated_reservation.reserved_until > reservation.reserved_until-- other_reservation = Reservation.objects.get(checkout_line__variant=variant_other)- assert other_reservation.checkout_line == new_line- assert other_reservation.quantity_reserved == new_line.quantity-- assert updated_reservation.reserved_until == other_reservation.reserved_until-- with pytest.raises(Reservation.DoesNotExist):- reservation.refresh_from_db()---def test_checkout_lines_update_quantity_and_custom_price(- app_api_client, checkout_with_item, permission_handle_checkouts-):- checkout = checkout_with_item- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- assert calculate_checkout_quantity(lines) == 3- line = checkout.lines.first()- variant = line.variant- assert line.quantity == 3-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- price = Decimal("22.22")-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],- }- response = app_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_UPDATE,- variables,- permissions=[permission_handle_checkouts],- )- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 1- line = checkout.lines.first()- assert line.variant == variant- assert line.quantity == 1- assert line.price_override == price- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 1---def test_checkout_lines_update_custom_price(- app_api_client, checkout_with_item, permission_handle_checkouts-):- checkout = checkout_with_item- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- assert calculate_checkout_quantity(lines) == 3- line = checkout.lines.first()- variant = line.variant- previous_quantity = line.quantity-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- price = Decimal("22.22")-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "price": price}],- }- response = app_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_UPDATE,- variables,- permissions=[permission_handle_checkouts],- )- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 1- line = checkout.lines.first()- assert line.variant == variant- assert line.quantity == previous_quantity- assert line.price_override == price- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 3---def test_checkout_lines_update_with_custom_price_override_existing_price(- app_api_client, checkout_with_item, permission_handle_checkouts-):- 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.price_override = Decimal("10.12")- line.save(update_fields=["price_override"])- variant = line.variant- assert line.quantity == 3-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- price = Decimal("22.10")-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],- }- response = app_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_UPDATE,- variables,- permissions=[permission_handle_checkouts],- )- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 1- line = checkout.lines.first()- assert line.variant == variant- assert line.quantity == 1- assert line.price_override == price- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 1---def test_checkout_lines_update_clear_custom_price(- app_api_client, checkout_with_item, permission_handle_checkouts-):- 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.price_override = Decimal("10.12")- line.save(update_fields=["price_override"])- variant = line.variant- assert line.quantity == 3-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1, "price": None}],- }- response = app_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_UPDATE,- variables,- permissions=[permission_handle_checkouts],- )- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 1- line = checkout.lines.first()- assert line.variant == variant- assert line.quantity == 1- assert line.price_override is None- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 1---def test_checkout_lines_update_set_quantity_to_0_then_update_customer_price(- app_api_client, checkout_with_item, permission_handle_checkouts-):- """Ensure an error is not raised and the line is deleted when the line quantity- is set to 0 firstly and then the custom price is changed."""-- 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.price_override = Decimal("10.12")- line.save(update_fields=["price_override"])- variant = line.variant- assert line.quantity == 3-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [- {"variantId": variant_id, "quantity": 0},- {"variantId": variant_id, "price": 10},- ],- }- response = app_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_UPDATE,- variables,- permissions=[permission_handle_checkouts],- )- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 0- with pytest.raises(CheckoutLine.DoesNotExist):- line.refresh_from_db()---def test_checkout_lines_update_with_custom_price_by_app_no_perm(- app_api_client, checkout_with_item-):- checkout = checkout_with_item- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- assert calculate_checkout_quantity(lines) == 3- line = checkout.lines.first()- variant = line.variant- assert line.quantity == 3-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- price = Decimal("22.22")-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],- }- response = app_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- assert_no_permission(response)---def test_checkout_lines_update_with_custom_price_raise_permission_denied_for_staff(- staff_api_client, checkout_with_item, permission_handle_checkouts-):- checkout = checkout_with_item- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- assert calculate_checkout_quantity(lines) == 3- line = checkout.lines.first()- variant = line.variant- assert line.quantity == 3-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- price = Decimal("22.22")-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],- }- response = staff_api_client.post_graphql(- MUTATION_CHECKOUT_LINES_UPDATE,- variables,- permissions=[permission_handle_checkouts],- )- assert_no_permission(response)---def test_checkout_lines_update_no_quantity_provided(- user_api_client, checkout_with_item-):- checkout = checkout_with_item- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 1- assert calculate_checkout_quantity(lines) == 3- line = checkout.lines.first()- variant = line.variant- assert line.quantity == 3-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "lines": [{"variantId": variant_id}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["code"] == CheckoutErrorCode.REQUIRED.name- assert errors[0]["field"] == "quantity"---def test_checkout_lines_update_with_unavailable_variant(- user_api_client, checkout_with_item-):- checkout = checkout_with_item- previous_last_change = checkout.last_change- assert checkout.lines.count() == 1- line = checkout.lines.first()- variant = line.variant- variant.channel_listings.filter(channel=checkout_with_item.channel).update(- price_amount=None- )- assert line.quantity == 3-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- errors = content["data"]["checkoutLinesUpdate"]["errors"]- assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name- assert errors[0]["field"] == "lines"- assert errors[0]["variants"] == [variant_id]- checkout.refresh_from_db()- assert checkout.last_change == previous_last_change---def test_checkout_lines_update_channel_without_shipping_zones(- user_api_client, checkout_with_item-):- checkout = checkout_with_item- checkout.channel.shipping_zones.clear()- assert checkout.lines.count() == 1- line = checkout.lines.first()- variant = line.variant- assert line.quantity == 3-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesUpdate"]- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name- assert errors[0]["field"] == "quantity"---def test_checkout_lines_update_variant_quantity_over_avability_stock(- user_api_client, checkout_with_item-):- checkout = checkout_with_item- line = checkout.lines.first()- variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)- current_stock = line.variant.stocks.first()- line.quantity = current_stock.quantity - 1- line.save()-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": current_stock.quantity - 2}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesUpdate"]- assert data["checkout"]["lines"][0]["quantity"] == variables["lines"][0]["quantity"]---def test_checkout_lines_delete_with_by_zero_quantity_when_variant_out_of_stock(- user_api_client, checkout_with_item-):- checkout = checkout_with_item- line = checkout.lines.first()- variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)- stock = line.variant.stocks.first()- stock.quantity = 0- stock.save(update_fields=["quantity"])- previous_last_change = checkout.last_change-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 0}],- "channelSlug": checkout.channel.slug,- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesUpdate"]- assert not data["checkout"]["lines"]- checkout.refresh_from_db()- assert checkout.last_change != previous_last_change--- "saleor.graphql.checkout.mutations.checkout_lines_add."- "update_checkout_shipping_method_if_invalid",- wraps=update_checkout_shipping_method_if_invalid,-)-def test_checkout_line_delete_by_zero_quantity(- mocked_update_shipping_method, user_api_client, checkout_with_item-):- checkout = checkout_with_item- assert checkout.lines.count() == 1- line = checkout.lines.first()- variant = line.variant- assert line.quantity == 3- previous_last_change = checkout.last_change-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 0}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 0- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)- assert checkout.last_change != previous_last_change--- "saleor.graphql.checkout.mutations.checkout_lines_add."- "update_checkout_shipping_method_if_invalid",- wraps=update_checkout_shipping_method_if_invalid,-)-def test_checkout_line_delete_by_zero_quantity_when_variant_unavailable_for_purchase(- mocked_update_shipping_method, user_api_client, checkout_with_item-):- checkout = checkout_with_item- assert checkout.lines.count() == 1- line = checkout.lines.first()- variant = line.variant- assert line.quantity == 3- variant.channel_listings.all().delete()- variant.product.channel_listings.all().delete()-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 0}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 0- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)--- "saleor.graphql.checkout.mutations.checkout_lines_add."- "update_checkout_shipping_method_if_invalid",- wraps=update_checkout_shipping_method_if_invalid,-)-def test_checkout_line_update_by_zero_quantity_dont_create_new_lines(- mocked_update_shipping_method,- user_api_client,- checkout_with_item,-):- checkout = checkout_with_item- line = checkout.lines.first()- variant = line.variant- checkout.lines.all().delete()- assert checkout.lines.count() == 0- previous_last_change = checkout.last_change-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 0}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- assert checkout.lines.count() == 0- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)- assert checkout.last_change != previous_last_change---def test_checkout_lines_update_with_unpublished_product(- user_api_client, checkout_with_item, channel_USD-):- checkout = checkout_with_item- line = checkout.lines.first()- variant = line.variant- product = variant.product- ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(- is_published=False- )-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)-- content = get_graphql_content(response)- error = content["data"]["checkoutLinesUpdate"]["errors"][0]- assert error["code"] == CheckoutErrorCode.PRODUCT_NOT_PUBLISHED.name---def test_checkout_lines_update_invalid_checkout_id(user_api_client):- variables = {"id": "1234", "lines": []}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLinesUpdate"]- assert data["errors"][0]["field"] == "id"---def test_checkout_lines_update_check_lines_quantity(- user_api_client, checkout_with_item-):- checkout = checkout_with_item- line = checkout.lines.first()- variant = line.variant-- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)-- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 11}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert data["errors"][0]["message"] == (- "Could not add items 123. Only 10 remaining in stock."- )- assert data["errors"][0]["field"] == "quantity"---def test_checkout_lines_update_with_chosen_shipping(- user_api_client, checkout, stock, address, shipping_method-):- checkout.shipping_address = address- checkout.shipping_method = shipping_method- checkout.save()-- variant = stock.product_variant- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- variables = {- "id": to_global_id_or_none(checkout),- "lines": [{"variantId": variant_id, "quantity": 1}],- }- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesUpdate"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 1---MUTATION_CHECKOUT_LINE_DELETE = """- mutation checkoutLineDelete($id: ID, $lineId: ID!) {- checkoutLineDelete(id: $id, lineId: $lineId) {- checkout {- token- lines {- quantity- variant {- id- }- }- }- errors {- field- message- }- }- }-"""--- "saleor.graphql.checkout.mutations.checkout_line_delete."- "update_checkout_shipping_method_if_invalid",- wraps=update_checkout_shipping_method_if_invalid,-)-def test_checkout_line_delete(- mocked_update_shipping_method,- user_api_client,- checkout_line_with_reservation_in_many_stocks,-):- assert Reservation.objects.count() == 2- checkout = checkout_line_with_reservation_in_many_stocks.checkout- previous_last_change = checkout.last_change- lines, _ = fetch_checkout_lines(checkout)- assert calculate_checkout_quantity(lines) == 3- assert checkout.lines.count() == 1- line = checkout.lines.first()- assert line.quantity == 3-- line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)-- variables = {"id": to_global_id_or_none(checkout), "lineId": line_id}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLineDelete"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() == 0- assert calculate_checkout_quantity(lines) == 0- assert Reservation.objects.count() == 0- manager = get_plugins_manager()- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)- assert checkout.last_change != previous_last_change---MUTATION_CHECKOUT_LINES_DELETE = """- mutation checkoutLinesDelete($id: ID, $linesIds: [ID!]!) {- checkoutLinesDelete(id: $id, linesIds: $linesIds) {- checkout {- token- lines {- id- quantity- variant {- id- }- }- }- errors {- message- code- field- lines- }- }- }-"""--- "saleor.graphql.checkout.mutations.checkout_lines_delete."- "update_checkout_shipping_method_if_invalid",- wraps=update_checkout_shipping_method_if_invalid,-)-def test_checkout_lines_delete(- mocked_update_shipping_method, user_api_client, checkout_with_items-):- checkout = checkout_with_items- checkout_lines_count = checkout.lines.count()- previous_last_change = checkout.last_change- line = checkout.lines.first()- second_line = checkout.lines.last()-- first_line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)- second_line_id = graphene.Node.to_global_id("CheckoutLine", second_line.pk)- lines_list = [first_line_id, second_line_id]-- variables = {"id": to_global_id_or_none(checkout), "linesIds": lines_list}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)- content = get_graphql_content(response)-- data = content["data"]["checkoutLinesDelete"]- assert not data["errors"]- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- assert checkout.lines.count() + len(lines_list) == checkout_lines_count- remaining_lines = data["checkout"]["lines"]- lines_ids = [line["id"] for line in remaining_lines]- assert lines_list not in lines_ids- manager = get_plugins_manager()- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)- assert checkout.last_change != previous_last_change---def test_checkout_lines_delete_invalid_checkout_id(- user_api_client, checkout_with_items-):- checkout = checkout_with_items- line = checkout.lines.first()- second_line = checkout.lines.last()-- first_line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)- second_line_id = graphene.Node.to_global_id("CheckoutLine", second_line.pk)- lines_list = [first_line_id, second_line_id]-- variables = {- "id": graphene.Node.to_global_id("Checkout", checkout.pk),- "linesIds": lines_list,- }- checkout.delete()- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)- content = get_graphql_content(response)- errors = content["data"]["checkoutLinesDelete"]["errors"][0]- assert errors["code"] == CheckoutErrorCode.NOT_FOUND.name---def tests_checkout_lines_delete_invalid_lines_ids(user_api_client, checkout_with_items):- checkout = checkout_with_items- previous_last_change = checkout.last_change- line = checkout.lines.first()-- first_line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)- lines_list = [first_line_id, "Q2hlY2tvdXRMaW5lOjE8"]-- variables = {"id": to_global_id_or_none(checkout), "linesIds": lines_list}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)- content = get_graphql_content(response, ignore_errors=True)- errors = content["errors"][0]- assert errors["extensions"]["exception"]["code"] == "GraphQLError"- assert checkout.last_change == previous_last_change--- "lines, expected",- [- (- [- {"quantity": 6, "variant_id": "abc", "price": 1.22},- {"quantity": 6, "variant_id": "abc"},- {"quantity": 1, "variant_id": "def", "price": 33.2},- {"quantity": 1, "variant_id": "def", "price": 10},- ],- [- CheckoutLineData(- quantity=12,- quantity_to_update=True,- custom_price=1.22,- custom_price_to_update=True,- ),- CheckoutLineData(- quantity=2,- quantity_to_update=True,- custom_price=10,- custom_price_to_update=True,- ),- ],- ),- (- [- {"quantity": 8, "variant_id": "ghi"},- {"quantity": 2, "variant_id": "ghi"},- {"quantity": 6, "variant_id": "abc"},- {"quantity": 1, "variant_id": "def"},- {"quantity": 6, "variant_id": "abc"},- {"quantity": 1, "variant_id": "def"},- {"quantity": 8, "variant_id": "ghi"},- {"quantity": 2, "variant_id": "ghi"},- {"quantity": 922, "variant_id": "xyz"},- {"quantity": 6, "variant_id": "abc"},- {"quantity": 1, "variant_id": "def"},- {"quantity": 6, "variant_id": "abc"},- {"quantity": 1, "variant_id": "def"},- {"quantity": 1000, "variant_id": "jkl"},- {"quantity": 999, "variant_id": "zzz"},- ],- [- CheckoutLineData(- quantity=quantity,- quantity_to_update=True,- custom_price=None,- custom_price_to_update=False,- )- for quantity in [20, 24, 4, 922, 1000, 999]- ],- ),- (- [- {"quantity": 100, "variant_id": name}- for name in (l1 + l2 for l1 in "abcdef" for l2 in "ghijkl")- ],- [- CheckoutLineData(- quantity=100,- quantity_to_update=True,- custom_price=None,- custom_price_to_update=False,- )- ]- * 36,- ),- ],-)-def test_group_by_variants(lines, expected):- assert expected == group_quantity_and_custom_prices_by_variants(lines)diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.pyindex c18e51e86b..f8e037e410 100644--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py@@ -1,107 +1,14 @@-from datetime import date, timedelta-from decimal import Decimal-from unittest import mock--import graphene-import pytest-from prices import Money-from ....checkout import calculations-from ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from ....checkout.utils import (- add_variant_to_checkout,- add_voucher_to_checkout,- set_external_shipping_id,-)-from ....core.taxes import TaxedMoney-from ....discount import DiscountInfo, VoucherType+from ....discount import DiscountInfofrom ....plugins.manager import get_plugins_manager-from ....warehouse.models import Stockfrom ...core.utils import to_global_id_or_nonefrom ...tests.utils import get_graphql_content-from .mutations.test_checkout_shipping_address_update import (- MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE,-)-from .test_checkout_lines import MUTATION_CHECKOUT_LINE_DELETE---def test_checkout_lines_delete_with_not_applicable_voucher(- user_api_client, checkout_with_item, voucher, channel_USD-):- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout_with_item)- checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)- subtotal = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout_with_item.shipping_address,- )- voucher.channel_listings.filter(channel=channel_USD).update(- min_spent_amount=subtotal.gross.amount- )- checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)-- add_voucher_to_checkout(manager, checkout_info, lines, voucher)- assert checkout_with_item.voucher_code == voucher.code-- line = checkout_with_item.lines.first()-- line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)- variables = {"id": to_global_id_or_none(checkout_with_item), "lineId": line_id}- response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)- content = get_graphql_content(response)- data = content["data"]["checkoutLineDelete"]- assert not data["errors"]- checkout_with_item.refresh_from_db()- assert checkout_with_item.lines.count() == 0- assert checkout_with_item.voucher_code is None---def test_checkout_shipping_address_update_with_not_applicable_voucher(- user_api_client,- checkout_with_item,- voucher_shipping_type,- graphql_address_data,- address_other_country,- shipping_method,-):- assert checkout_with_item.shipping_address is None- assert checkout_with_item.voucher_code is None-- checkout_with_item.shipping_address = address_other_country- checkout_with_item.shipping_method = shipping_method- checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])- assert checkout_with_item.shipping_address.country == address_other_country.country-- voucher = voucher_shipping_type- assert voucher.countries[0].code == address_other_country.country-- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout_with_item)- checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)- add_voucher_to_checkout(manager, checkout_info, lines, voucher)- assert checkout_with_item.voucher_code == voucher.code-- new_address = graphql_address_data- variables = {- "id": to_global_id_or_none(checkout_with_item),- "shippingAddress": new_address,- }- response = user_api_client.post_graphql(- MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables- )- content = get_graphql_content(response)- data = content["data"]["checkoutShippingAddressUpdate"]- assert not data["errors"]-- checkout_with_item.refresh_from_db()- checkout_with_item.shipping_address.refresh_from_db()-- assert checkout_with_item.shipping_address.country == new_address["country"]- assert checkout_with_item.voucher_code is None+# from .mutations.test_checkout_shipping_address_update import (+# MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE,+# )+# from .test_checkout_lines import MUTATION_CHECKOUT_LINE_DELETEdef test_checkout_totals_use_discounts(@@ -232,1207 +139,3 @@ def test_checkout_get_gift_card_code_without_gift_card(user_api_client, checkoutcontent = get_graphql_content(response)data = content["data"]["checkout"]["giftCards"]assert not data---MUTATION_CHECKOUT_ADD_PROMO_CODE = """- mutation($id: ID, $promoCode: String!) {- checkoutAddPromoCode(- id: $id, promoCode: $promoCode) {- errors {- field- message- code- }- checkout {- id- token- voucherCode- discount {- amount- }- giftCards {- id- last4CodeChars- }- totalPrice {- gross {- amount- }- }- availableShippingMethods {- id- price {- amount- }- }- shippingMethod {- id- price {- amount- }- }- }- }- }-"""---def _mutate_checkout_add_promo_code(client, variables):- response = client.post_graphql(MUTATION_CHECKOUT_ADD_PROMO_CODE, variables)- content = get_graphql_content(response)- return content["data"]["checkoutAddPromoCode"]---def test_checkout_add_voucher_for_entire_order(api_client, checkout_with_item, voucher):- # given- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }- assert voucher.type == VoucherType.ENTIRE_ORDER- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout_with_item)- checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)- taxed_total = calculations.checkout_total(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout_with_item.shipping_address,- discounts=[],- )-- # when- data = _mutate_checkout_add_promo_code(api_client, variables)-- # then- checkout_with_item.refresh_from_db()- assert not data["errors"]- checkout_data = data["checkout"]- total_price_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]- assert (- total_price_gross_amount- == taxed_total.gross.amount - checkout_with_item.discount_amount- )---def test_checkout_add_voucher_code_by_token(api_client, checkout_with_item, voucher):- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_item.token)- assert data["checkout"]["voucherCode"] == voucher.code---def test_checkout_add_already_applied_voucher_for_entire_order(- api_client, checkout_with_item, voucher-):- # given- variant = checkout_with_item.lines.first().variant- channel = checkout_with_item.channel- channel_listing = variant.channel_listings.get(channel=channel)- net = (- variant.get_price(- variant.product, [], checkout_with_item.channel, channel_listing- )- * checkout_with_item.lines.first().quantity- )-- voucher_channel_listing = voucher.channel_listings.get(channel=channel)- voucher_channel_listing.discount_value = net.amount- voucher_channel_listing.save(update_fields=["discount_value"])-- checkout_with_item.voucher_code = voucher.code- checkout_with_item.discount_amount = net.amount- checkout_with_item.save()-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }- assert voucher.type == VoucherType.ENTIRE_ORDER-- # when- data = _mutate_checkout_add_promo_code(api_client, variables)-- # then- checkout_with_item.refresh_from_db()- assert not data["errors"]- checkout_data = data["checkout"]- total_price_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]- assert total_price_gross_amount == 0- assert checkout_data["discount"]["amount"] == net.amount--[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")-def test_checkout_add_voucher_code_by_token_with_external_shipment(- mock_send_request,- api_client,- checkout_with_item,- voucher,- shipping_app,- address,- settings,-):- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]- response_method_id = "abcd"- mock_json_response = [- {- "id": response_method_id,- "name": "Provider - Economy",- "amount": "10",- "currency": "USD",- "maximum_delivery_days": "7",- }- ]- mock_send_request.return_value = mock_json_response-- external_shipping_method_id = graphene.Node.to_global_id(- "app", f"{shipping_app.id}:{response_method_id}"- )-- checkout = checkout_with_item- checkout.shipping_address = address- set_external_shipping_id(checkout, external_shipping_method_id)- checkout.save(update_fields=["shipping_address", "private_metadata"])-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_item.token)- assert data["checkout"]["voucherCode"] == voucher.code- assert data["checkout"]["shippingMethod"]["id"] == external_shipping_method_id---def test_checkout_add_voucher_code_with_display_gross_prices(- api_client, checkout_with_item, voucher, site_settings, monkeypatch-):- site_settings.display_gross_prices = True- site_settings.save()-- previous_checkout_last_change = checkout_with_item.last_change-- voucher = voucher- voucher_channel_listing = voucher.channel_listings.first()- voucher_channel_listing.min_spent_amount = 100- voucher_channel_listing.save()-- monkeypatch.setattr(- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",- lambda checkout_lines, channel, currency, discounts: TaxedMoney(- Money(95, "USD"), Money(100, "USD")- ),- )-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_item.token)- assert data["checkout"]["voucherCode"] == voucher.code- checkout_with_item.refresh_from_db()- assert checkout_with_item.last_change != previous_checkout_last_change---def test_checkout_add_voucher_code_without_display_gross_prices(- api_client, checkout_with_item, voucher, site_settings, monkeypatch-):- site_settings.display_gross_prices = False- site_settings.save()-- previous_checkout_last_change = checkout_with_item.last_change-- voucher = voucher- voucher_channel_listing = voucher.channel_listings.first()- voucher_channel_listing.min_spent_amount = 100- voucher_channel_listing.save()-- monkeypatch.setattr(- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",- lambda checkout_lines, channel, currency, discounts: TaxedMoney(- Money(95, "USD"), Money(100, "USD")- ),- )-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert data["errors"][0]["code"] == CheckoutErrorCode.VOUCHER_NOT_APPLICABLE.name- assert data["errors"][0]["field"] == "promoCode"-- checkout_with_item.refresh_from_db()- assert checkout_with_item.last_change == previous_checkout_last_change---def test_checkout_add_voucher_code_variant_unavailable(- api_client, checkout_with_item, voucher-):- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }- checkout_with_item.lines.first().variant.channel_listings.filter(- channel=checkout_with_item.channel- ).delete()- data = _mutate_checkout_add_promo_code(api_client, variables)-- errors = data["errors"]- assert len(errors) == 1- assert errors[0]["code"] == CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL.name- assert errors[0]["field"] == "lines"---def test_checkout_add_voucher_code_checkout_with_sale(- api_client, checkout_with_item, voucher_percentage, discount_info-):- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout_with_item)- checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)- address = checkout_with_item.shipping_address- subtotal = calculations.checkout_subtotal(- manager=manager, checkout_info=checkout_info, lines=lines, address=address- )- subtotal_discounted = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=address,- discounts=[discount_info],- )- assert subtotal > subtotal_discounted- previous_checkout_last_change = checkout_with_item.last_change-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher_percentage.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- checkout_with_item.refresh_from_db()- assert not data["errors"]- assert checkout_with_item.voucher_code == voucher_percentage.code- assert checkout_with_item.discount_amount == Decimal(1.5)- assert checkout_with_item.last_change != previous_checkout_last_change---def test_checkout_add_specific_product_voucher_code_checkout_with_sale(- api_client, checkout_with_item, voucher_specific_product_type, discount_info-):- # given- voucher = voucher_specific_product_type- checkout = checkout_with_item- expected_discount = Decimal(1.5)- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)-- subtotal = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- )- checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)- subtotal_discounted = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- discounts=[discount_info],- )-- assert subtotal > subtotal_discounted- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }-- # when- data = _mutate_checkout_add_promo_code(api_client, variables)-- # then- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- subtotal_with_voucher = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- discounts=[discount_info],- )- assert not data["errors"]- assert subtotal_discounted == subtotal_with_voucher + Money(- expected_discount, "USD"- )- assert checkout.voucher_code == voucher.code- assert checkout.discount_amount == Decimal(0)---def test_checkout_add_products_voucher_code_checkout_with_sale(- api_client, checkout_with_item, voucher_percentage, discount_info-):- # given- checkout = checkout_with_item- product = checkout.lines.first().variant.product- voucher = voucher_percentage- voucher.type = VoucherType.SPECIFIC_PRODUCT- voucher.save()- voucher.products.add(product)- expected_discount = Money(Decimal(1.5), checkout.currency)-- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)-- subtotal = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- )-- checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)- subtotal_discounted = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- discounts=[discount_info],- )- assert subtotal > subtotal_discounted- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }-- # when- data = _mutate_checkout_add_promo_code(api_client, variables)-- # then- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- subtotal_with_voucher = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- discounts=[discount_info],- )- assert not data["errors"]- assert subtotal_discounted == subtotal_with_voucher + expected_discount- assert checkout.voucher_code == voucher.code- assert checkout.discount_amount == Decimal(0)---def test_checkout_add_collection_voucher_code_checkout_with_sale(- api_client, checkout_with_item, voucher_percentage, discount_info, collection-):- # given- checkout = checkout_with_item- voucher = voucher_percentage- product = checkout.lines.first().variant.product- product.collections.add(collection)- voucher.type = VoucherType.SPECIFIC_PRODUCT- voucher.save()- voucher.collections.add(collection)- expected_voucher_discount = Money(Decimal(1.5), checkout.currency)-- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)- subtotal = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- )- checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)- subtotal_discounted = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- discounts=[discount_info],- )- assert subtotal > subtotal_discounted- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }-- # when- data = _mutate_checkout_add_promo_code(api_client, variables)-- # then- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- subtotal_with_voucher = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- discounts=[discount_info],- )-- assert not data["errors"]- assert subtotal_discounted == subtotal_with_voucher + expected_voucher_discount- assert checkout.voucher_code == voucher.code- assert checkout.discount_amount == Decimal(0)---def test_checkout_add_category_code_checkout_with_sale(- api_client, checkout_with_item, voucher_percentage, discount_info-):- # given- checkout = checkout_with_item- category = checkout.lines.first().variant.product.category- voucher = voucher_percentage- voucher.type = VoucherType.SPECIFIC_PRODUCT- voucher.save()- voucher.categories.add(category)- expected_discount = Money(Decimal(1.5), checkout.currency)-- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout)- checkout_info = fetch_checkout_info(checkout, lines, [], manager)-- subtotal = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- )- checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)- subtotal_discounted = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- discounts=[discount_info],- )- assert subtotal > subtotal_discounted- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }-- # when- data = _mutate_checkout_add_promo_code(api_client, variables)-- # then- checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)- subtotal_with_voucher = calculations.checkout_subtotal(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout.shipping_address,- discounts=[discount_info],- )- assert not data["errors"]- assert subtotal_discounted == subtotal_with_voucher + expected_discount- assert checkout.voucher_code == voucher.code- assert checkout.discount_amount == Decimal(0)---def test_checkout_add_voucher_code_not_applicable_voucher(- api_client, checkout_with_item, voucher_with_high_min_spent_amount-):- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher_with_high_min_spent_amount.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["field"] == "promoCode"---def test_checkout_add_voucher_code_not_assigned_to_channel(- api_client, checkout_with_item, voucher_without_channel-):- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher_without_channel.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["field"] == "promoCode"---def test_checkout_add_gift_card_code(api_client, checkout_with_item, gift_card):- gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_item.token)- assert data["checkout"]["giftCards"][0]["id"] == gift_card_id- assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_code---def test_checkout_add_many_gift_card_code(- api_client, checkout_with_gift_card, gift_card_created_by_staff-):- assert checkout_with_gift_card.gift_cards.count() > 0- gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card_created_by_staff.pk)- variables = {- "id": to_global_id_or_none(checkout_with_gift_card),- "promoCode": gift_card_created_by_staff.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_gift_card.token)- gift_card_data = data["checkout"]["giftCards"]- assert gift_card_id in {gift_card["id"] for gift_card in gift_card_data}---def test_checkout_add_inactive_gift_card_code(- staff_api_client, checkout_with_item, gift_card-):- # given- gift_card.is_active = False- gift_card.save(update_fields=["is_active"])-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card.code,- }-- # when- data = _mutate_checkout_add_promo_code(staff_api_client, variables)-- # then- assert not data["checkout"]- assert len(data["errors"]) == 1- assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID.name- assert data["errors"][0]["field"] == "promoCode"---def test_checkout_add_expired_gift_card_code(- staff_api_client, checkout_with_item, gift_card-):- # given- gift_card.expiry_date = date.today() - timedelta(days=10)- gift_card.save(update_fields=["expiry_date"])-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card.code,- }-- # when- data = _mutate_checkout_add_promo_code(staff_api_client, variables)-- # then- assert not data["checkout"]- assert len(data["errors"]) == 1- assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID.name- assert data["errors"][0]["field"] == "promoCode"---def test_checkout_add_used_gift_card_code(- staff_api_client, checkout_with_item, gift_card_used, customer_user-):- # given- checkout_with_item.email = gift_card_used.used_by_email- checkout_with_item.save(update_fields=["email"])-- gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card_used.pk)-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card_used.code,- }-- # when- data = _mutate_checkout_add_promo_code(staff_api_client, variables)-- # then- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_item.token)- assert data["checkout"]["giftCards"][0]["id"] == gift_card_id- assert (- data["checkout"]["giftCards"][0]["last4CodeChars"]- == gift_card_used.display_code- )---def test_checkout_add_used_gift_card_code_invalid_user(- staff_api_client, checkout_with_item, gift_card_used, staff_user-):- # given- checkout_with_item.user = staff_user- assert gift_card_used.used_by_email != checkout_with_item.user.email-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card_used.code,- }-- # when- data = _mutate_checkout_add_promo_code(staff_api_client, variables)-- # then- assert not data["checkout"]- assert len(data["errors"]) == 1- assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID.name- assert data["errors"][0]["field"] == "promoCode"---def test_checkout_get_total_with_gift_card(api_client, checkout_with_item, gift_card):- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout_with_item)- checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)- taxed_total = calculations.checkout_total(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout_with_item.shipping_address,- )- total_with_gift_card = taxed_total.gross.amount - gift_card.current_balance_amount-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_item.token)- assert not data["checkout"]["giftCards"] == []- assert data["checkout"]["totalPrice"]["gross"]["amount"] == total_with_gift_card---def test_checkout_get_total_with_many_gift_card(- api_client, checkout_with_gift_card, gift_card_created_by_staff-):- manager = get_plugins_manager()- lines, _ = fetch_checkout_lines(checkout_with_gift_card)- checkout_info = fetch_checkout_info(checkout_with_gift_card, lines, [], manager)- taxed_total = calculations.checkout_total(- manager=manager,- checkout_info=checkout_info,- lines=lines,- address=checkout_with_gift_card.shipping_address,- )- taxed_total.gross -= checkout_with_gift_card.get_total_gift_cards_balance()- taxed_total.net -= checkout_with_gift_card.get_total_gift_cards_balance()- total_with_gift_card = (- taxed_total.gross.amount - gift_card_created_by_staff.current_balance_amount- )-- assert checkout_with_gift_card.gift_cards.count() > 0- variables = {- "id": to_global_id_or_none(checkout_with_gift_card),- "promoCode": gift_card_created_by_staff.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_gift_card.token)- assert data["checkout"]["totalPrice"]["gross"]["amount"] == total_with_gift_card---def test_checkout_get_total_with_more_money_on_gift_card(- api_client, checkout_with_item, gift_card_used, customer_user-):- checkout_with_item.email = gift_card_used.used_by_email- checkout_with_item.save(update_fields=["email"])-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card_used.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_item.token)- assert not data["checkout"]["giftCards"] == []- assert data["checkout"]["totalPrice"]["gross"]["amount"] == 0---def test_checkout_add_same_gift_card_code(api_client, checkout_with_gift_card):- gift_card = checkout_with_gift_card.gift_cards.first()- gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)- gift_card_count = checkout_with_gift_card.gift_cards.count()- variables = {- "id": to_global_id_or_none(checkout_with_gift_card),- "promoCode": gift_card.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_gift_card.token)- assert data["checkout"]["giftCards"][0]["id"] == gift_card_id- assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_code- assert len(data["checkout"]["giftCards"]) == gift_card_count---def test_checkout_add_gift_card_code_in_active_gift_card(- api_client, checkout_with_item, gift_card-):- gift_card.is_active = False- gift_card.save()-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["field"] == "promoCode"---def test_checkout_add_gift_card_code_in_expired_gift_card(- api_client, checkout_with_item, gift_card-):- gift_card.expiry_date = date.today() - timedelta(days=1)- gift_card.save()-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": gift_card.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["field"] == "promoCode"---def test_checkout_add_promo_code_invalid_checkout(api_client, voucher, checkout):- variables = {"id": to_global_id_or_none(checkout), "promoCode": voucher.code}- checkout.delete()- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["field"] == "id"---def test_checkout_add_promo_code_invalid_promo_code(api_client, checkout_with_item):- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": "unexisting_code",- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["field"] == "promoCode"---def test_checkout_add_promo_code_invalidate_shipping_method(- api_client,- checkout,- variant_with_many_stocks_different_shipping_zones,- gift_card_created_by_staff,- address_usa,- shipping_method,- channel_USD,- voucher,-):- Stock.objects.update(quantity=5)-- # Free shipping for 50 USD- shipping_channel_listing = shipping_method.channel_listings.first()- shipping_channel_listing.minimum_order_price = Money(50, "USD")- shipping_channel_listing.price = Money(0, "USD")- shipping_channel_listing.save()-- # Setup checkout with items worth $50- checkout.shipping_address = address_usa- checkout.shipping_method = shipping_method- checkout.billing_address = address_usa- checkout.save()-- checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())- variant = variant_with_many_stocks_different_shipping_zones- add_variant_to_checkout(checkout_info, variant, 5)-- # Apply voucher- variables = {"id": to_global_id_or_none(checkout), "promoCode": voucher.code}- data = _mutate_checkout_add_promo_code(api_client, variables)-- shipping_method_id = graphene.Node.to_global_id(- "ShippingMethodType", shipping_method.pk- )- assert data["checkout"]["shippingMethod"] is None- assert shipping_method_id not in data["checkout"]["availableShippingMethods"]---def test_checkout_add_promo_code_no_checkout_email(- api_client, checkout_with_item, voucher-):- checkout_with_item.email = None- checkout_with_item.save(update_fields=["email"])-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["code"] == CheckoutErrorCode.EMAIL_NOT_SET.name--[email protected]("shipping_price", [12, 10, 5])-def test_checkout_add_free_shipping_voucher_do_not_invalidate_shipping_method(- shipping_price,- api_client,- checkout_with_item,- voucher_free_shipping,- shipping_method,- address_usa,-):- """Ensure that adding free shipping voucher do not invalidate- current shipping method.- """- checkout_with_item.shipping_method = shipping_method- checkout_with_item.shipping_address = address_usa- checkout_with_item.save(update_fields=["shipping_method", "shipping_address"])-- channel = checkout_with_item.channel-- line = checkout_with_item.lines.first()- line.quantity = 1- line.save(update_fields=["quantity"])-- variant_listing = line.variant.channel_listings.get(channel=channel)- variant_listing.price = Money(10, "USD")- variant_listing.save(update_fields=["price_amount"])-- # set minimal price similar to order subtotal price;- # set shipping price so big, that in case the discount will be applied- # substracted from subtotal the shipping method will be not valid anymore- shipping_listing = shipping_method.channel_listings.get(channel=channel)- shipping_listing.price = Money(shipping_price, "USD")- shipping_listing.minimum_order_price = Money(8, "USD")- shipping_listing.save(update_fields=["price_amount", "minimum_order_price_amount"])-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher_free_shipping.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- # ensure that shipping method wasn't invalidate- assert data["checkout"]["shippingMethod"]["id"] == graphene.Node.to_global_id(- "ShippingMethod", shipping_method.id- )--[email protected]("shipping_discount", [12, 10, 5])-def test_checkout_add_shipping_voucher_do_not_invalidate_shipping_method(- shipping_discount,- api_client,- checkout_with_item,- voucher_shipping_type,- shipping_method,- address_usa,-):- """Ensure that adding shipping voucher do not invalidate current shipping method."""- checkout_with_item.shipping_method = shipping_method- checkout_with_item.shipping_address = address_usa- checkout_with_item.save(update_fields=["shipping_method", "shipping_address"])-- channel = checkout_with_item.channel-- line = checkout_with_item.lines.first()- line.quantity = 1- line.save(update_fields=["quantity"])-- variant_listing = line.variant.channel_listings.get(channel=channel)- variant_listing.price = Money(10, "USD")- variant_listing.save(update_fields=["price_amount"])-- # set minimal price similar to order subtotal price;- shipping_listing = shipping_method.channel_listings.get(channel=channel)- shipping_listing.price = Money(20, "USD")- shipping_listing.minimum_order_price = Money(8, "USD")- shipping_listing.save(update_fields=["price_amount", "minimum_order_price_amount"])-- # set shipping voucher price so big, that in case the discount will be- # substracted from subtotal price the shipping method will be not valid anymore- voucher_listing = voucher_shipping_type.channel_listings.get(channel=channel)- voucher_listing.discount = Money(shipping_discount, "USD")- voucher_listing.save(update_fields=["discount_value"])-- voucher_shipping_type.countries = []- voucher_shipping_type.save(update_fields=["countries"])-- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": voucher_shipping_type.code,- }- data = _mutate_checkout_add_promo_code(api_client, variables)-- # ensure that shipping method wasn't invalidate- assert data["checkout"]["shippingMethod"]["id"] == graphene.Node.to_global_id(- "ShippingMethod", shipping_method.id- )---MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """- mutation($id: ID, $promoCode: String, $promoCodeId: ID) {- checkoutRemovePromoCode(- id: $id, promoCode: $promoCode, promoCodeId: $promoCodeId) {- errors {- field- code- message- }- checkout {- token,- voucherCode- giftCards {- id- last4CodeChars- }- }- }- }-"""---def _mutate_checkout_remove_promo_code(client, variables):- response = client.post_graphql(MUTATION_CHECKOUT_REMOVE_PROMO_CODE, variables)- content = get_graphql_content(response)- return content["data"]["checkoutRemovePromoCode"]---def test_checkout_remove_voucher_code(api_client, checkout_with_voucher):- assert checkout_with_voucher.voucher_code is not None- previous_checkout_last_change = checkout_with_voucher.last_change-- variables = {- "id": to_global_id_or_none(checkout_with_voucher),- "promoCode": checkout_with_voucher.voucher_code,- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- checkout_with_voucher.refresh_from_db()- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_voucher.token)- assert data["checkout"]["voucherCode"] is None- assert checkout_with_voucher.voucher_code is None- assert checkout_with_voucher.last_change != previous_checkout_last_change---def test_checkout_remove_voucher_code_with_inactive_channel(- api_client, checkout_with_voucher-):- channel = checkout_with_voucher.channel- channel.is_active = False- channel.save()- previous_checkout_last_change = checkout_with_voucher.last_change-- variables = {- "id": to_global_id_or_none(checkout_with_voucher),- "promoCode": checkout_with_voucher.voucher_code,- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- checkout_with_voucher.refresh_from_db()- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_voucher.token)- assert data["checkout"]["voucherCode"] == checkout_with_voucher.voucher_code- assert checkout_with_voucher.last_change == previous_checkout_last_change---def test_checkout_remove_gift_card_code(api_client, checkout_with_gift_card):- assert checkout_with_gift_card.gift_cards.count() == 1- previous_checkout_last_change = checkout_with_gift_card.last_change-- variables = {- "id": to_global_id_or_none(checkout_with_gift_card),- "promoCode": checkout_with_gift_card.gift_cards.first().code,- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- assert data["checkout"]["token"] == str(checkout_with_gift_card.token)- assert data["checkout"]["giftCards"] == []- assert not checkout_with_gift_card.gift_cards.all().exists()- checkout_with_gift_card.refresh_from_db()- assert checkout_with_gift_card.last_change != previous_checkout_last_change---def test_checkout_remove_one_of_gift_cards(- api_client, checkout_with_gift_card, gift_card_created_by_staff-):- checkout_with_gift_card.gift_cards.add(gift_card_created_by_staff)- checkout_with_gift_card.save()- previous_checkout_last_change = checkout_with_gift_card.last_change- gift_card_first = checkout_with_gift_card.gift_cards.first()- gift_card_last = checkout_with_gift_card.gift_cards.last()-- variables = {- "id": to_global_id_or_none(checkout_with_gift_card),- "promoCode": gift_card_first.code,- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- checkout_gift_cards = checkout_with_gift_card.gift_cards- assert data["checkout"]["token"] == str(checkout_with_gift_card.token)- assert checkout_gift_cards.filter(code=gift_card_last.code).exists()- assert not checkout_gift_cards.filter(code=gift_card_first.code).exists()- checkout_with_gift_card.refresh_from_db()- assert checkout_with_gift_card.last_change != previous_checkout_last_change---def test_checkout_remove_promo_code_invalid_promo_code(api_client, checkout_with_item):- previous_checkout_last_change = checkout_with_item.last_change- variables = {- "id": to_global_id_or_none(checkout_with_item),- "promoCode": "unexisting_code",- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_item.token)- checkout_with_item.refresh_from_db()- assert checkout_with_item.last_change == previous_checkout_last_change---def test_checkout_remove_promo_code_invalid_checkout(api_client, voucher, checkout):- variables = {"id": to_global_id_or_none(checkout), "promoCode": voucher.code}- checkout.delete()-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["field"] == "id"---def test_checkout_remove_voucher_code_by_id(- api_client, checkout_with_voucher, voucher, gift_card-):- assert checkout_with_voucher.voucher_code is not None- checkout_with_voucher.gift_cards.add(gift_card)-- variables = {- "id": to_global_id_or_none(checkout_with_voucher),- "promoCodeId": graphene.Node.to_global_id("Voucher", voucher.id),- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- checkout_with_voucher.refresh_from_db()- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_voucher.token)- assert data["checkout"]["voucherCode"] is None- assert len(data["checkout"]["giftCards"]) == 1- assert checkout_with_voucher.voucher_code is None---def test_checkout_remove_gift_card_by_id(- api_client, checkout_with_voucher, gift_card, gift_card_expiry_date-):- assert checkout_with_voucher.voucher_code is not None- checkout_with_voucher.gift_cards.add(gift_card, gift_card_expiry_date)-- variables = {- "id": to_global_id_or_none(checkout_with_voucher),- "promoCodeId": graphene.Node.to_global_id("GiftCard", gift_card.id),- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- checkout_with_voucher.refresh_from_db()- assert not data["errors"]- assert data["checkout"]["token"] == str(checkout_with_voucher.token)- assert data["checkout"]["voucherCode"] is not None- gift_cards = data["checkout"]["giftCards"]- assert len(gift_cards) == 1- assert gift_cards[0]["id"] == graphene.Node.to_global_id(- "GiftCard", gift_card_expiry_date.pk- )---def test_checkout_remove_promo_code_id_and_code_given(- api_client, checkout_with_voucher, gift_card-):- assert checkout_with_voucher.voucher_code is not None-- variables = {- "token": checkout_with_voucher.token,- "promoCode": checkout_with_voucher.voucher_code,- "promoCodeId": graphene.Node.to_global_id("GiftCard", gift_card.id),- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name---def test_checkout_remove_promo_code_no_id_and_code_given(- api_client, checkout_with_voucher, gift_card-):- assert checkout_with_voucher.voucher_code is not None-- variables = {- "token": checkout_with_voucher.token,- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name---def test_checkout_remove_promo_code_id_does_not_exist(- api_client, checkout_with_voucher, gift_card-):- assert checkout_with_voucher.voucher_code is not None-- variables = {- "token": checkout_with_voucher.token,- "promoCodeId": "Abc",- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name- assert data["errors"][0]["field"] == "promoCodeId"---def test_checkout_remove_promo_code_invalid_object_type(- api_client, checkout_with_voucher, gift_card-):- assert checkout_with_voucher.voucher_code is not None-- variables = {- "token": checkout_with_voucher.token,- "promoCodeId": graphene.Node.to_global_id("Product", gift_card.id),- }-- data = _mutate_checkout_remove_promo_code(api_client, variables)-- assert data["errors"]- assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name- assert data["errors"][0]["field"] == "promoCodeId"