Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add tests for the digital checkout process
NyanKiyoshice2d1af134ac
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex deb6b0b9dc..5742985653 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,7 @@ All notable, unreleased changes to this project will be documented in this file.- Display menu item form errors - #4551 by @dominik-zeglen- Add voucher settings - #4556 by @benekex2- Enforced pydocstyle for Python docstrings over the project - #4562 by @NyanKiyoshi+- The checkout process of digital orders no longer require shipping information over the API - #4573 by @NyanKiyoshi## 2.8.0diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 132dfe8ec6..a96a070029 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -215,37 +215,36 @@ class CheckoutCreate(ModelMutation, I18nMixin):return cleaned_input@classmethod- def save_addresses(- cls,- instance: models.Checkout,- cleaned_input: dict,- variants: List[product_models.ProductVariant],- ):+ def save_addresses(cls, instance: models.Checkout, cleaned_input: dict):shipping_address = cleaned_input.get("shipping_address")billing_address = cleaned_input.get("billing_address")- if shipping_address and any(- variant.is_shipping_required() for variant in variants- ):+ updated_fields = []++ if shipping_address and instance.is_shipping_required():shipping_address.save()instance.shipping_address = shipping_address.get_copy()+ updated_fields.append("shipping_address")if billing_address:billing_address.save()instance.billing_address = billing_address.get_copy()+ updated_fields.append("billing_address")++ # Save the updated fields+ # Note django will simply return if the list is empty+ instance.save(update_fields=updated_fields)@classmethod@transaction.atomic()def save(cls, info, instance: models.Checkout, cleaned_input):- variants = cleaned_input.get("variants")- quantities = cleaned_input.get("quantities")-- # Save provided addresses and associate them to the checkout- cls.save_addresses(instance, cleaned_input, variants)-# Create the checkout objectinstance.save()- # Update/create checkout lines+ # Retrieve the lines to create+ variants = cleaned_input.get("variants")+ quantities = cleaned_input.get("quantities")++ # Create the checkout linesif variants and quantities:for variant, quantity in zip(variants, quantities):try:@@ -253,6 +252,9 @@ class CheckoutCreate(ModelMutation, I18nMixin):except InsufficientStock as exc:raise ValidationError(f"Insufficient product stock: {exc.item}")+ # Save provided addresses and associate them to the checkout+ cls.save_addresses(instance, cleaned_input)+@classmethoddef perform_mutation(cls, _root, info, **data):user = info.context.user@@ -597,13 +599,19 @@ class CheckoutComplete(BaseMutation):)try:- billing_address = order_data["billing_address"] # type: models.Address- shipping_address = order_data["shipping_address"] # type: models.Address+ billing_address = order_data["billing_address"]+ shipping_address = order_data.get("shipping_address", None)++ billing_address = AddressData(**billing_address.as_data())++ if shipping_address is not None:+ shipping_address = AddressData(**shipping_address.as_data())+txn = gateway_process_payment(payment=payment,payment_token=payment.token,- billing_address=AddressData(**billing_address.as_data()),- shipping_address=AddressData(**shipping_address.as_data()),+ billing_address=billing_address,+ shipping_address=shipping_address,store_source=store_source,)if txn.is_success and txn.customer_id and user.is_authenticated:diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 811db7420f..fd2f090eed 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -459,6 +459,7 @@ type CheckoutCountableEdge {type CheckoutCreate {errors: [Error!]+ created: Booleancheckout: Checkout}diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 1956b61169..4d3d5227cf 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -76,10 +76,10 @@ def create_payment_information("""billing, shipping = None, None- if billing_address is None and payment.order.billing_address:+ if billing_address is None and payment.order and payment.order.billing_address:billing = AddressData(**payment.order.billing_address.as_data())- if shipping_address is None and payment.order.shipping_address:+ if shipping_address is None and payment.order and payment.order.shipping_address:shipping = AddressData(**payment.order.shipping_address.as_data())order_id = payment.order.pk if payment.order else Nonediff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 0c961b465e..dd3a4a9ea1 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -37,8 +37,10 @@ def other_shipping_method(shipping_zone):def test_clean_shipping_method_after_shipping_address_changes_stay_the_same(checkout_with_single_item, address, shipping_method, other_shipping_method):- """If current shipping method applies to new address- then it doesn't need to be changed."""+ """Ensure the current shipping method applies to new address.++ If it does, then it doesn't need to be changed.+ """checkout = checkout_with_single_itemcheckout.shipping_address = address@@ -86,22 +88,23 @@ def test_update_checkout_shipping_method_if_invalid(MUTATION_CHECKOUT_CREATE = """mutation createCheckout($checkoutInput: CheckoutCreateInput!) {- checkoutCreate(input: $checkoutInput) {- checkout {- id- token- lines {- quantity- }- }- errors {- field- message- }+ checkoutCreate(input: $checkoutInput) {+ created+ checkout {+ id+ token+ lines {+ quantity+ }+ }+ errors {+ field+ message}+ }}- """+"""def test_checkout_create(api_client, variant, graphql_address_data):@@ -118,11 +121,14 @@ def test_checkout_create(api_client, variant, graphql_address_data):}assert not Checkout.objects.exists()response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)- content = get_graphql_content(response)+ content = get_graphql_content(response)["data"]["checkoutCreate"]++ # Look at the flag to see whether a new checkout was created or not+ assert content["created"] is Truenew_checkout = Checkout.objects.first()assert new_checkout is not None- checkout_data = content["data"]["checkoutCreate"]["checkout"]+ checkout_data = content["checkout"]assert checkout_data["token"] == str(new_checkout.token)assert new_checkout.lines.count() == 1checkout_line = new_checkout.lines.first()@@ -183,10 +189,13 @@ def test_checkout_create_reuse_checkout(checkout, user_api_client, variant):variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)variables = {"checkoutInput": {"lines": [{"quantity": 1, "variantId": variant_id}]}}response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)- content = get_graphql_content(response)+ content = get_graphql_content(response)["data"]["checkoutCreate"]++ # Look at the flag to see whether a new checkout was created or not+ assert not content["created"]# assert that existing checkout was reused and returned by mutation- checkout_data = content["data"]["checkoutCreate"]["checkout"]+ checkout_data = content["checkout"]assert checkout_data["token"] == str(checkout.token)# if checkout was reused it should be returned unmodified (e.g. without@@ -1261,7 +1270,7 @@ def test_checkout_prices(user_api_client, checkout_with_item):)-UPDATE_SHIPPING_METHOD_QUERY = """+MUTATION_UPDATE_SHIPPING_METHOD = """mutation checkoutShippingMethodUpdate($checkoutId:ID!, $shippingMethodId:ID!){checkoutShippingMethodUpdate(@@ -1288,7 +1297,7 @@ def test_checkout_shipping_method_update(is_valid_shipping_method,):checkout = checkout_with_item- query = UPDATE_SHIPPING_METHOD_QUERY+ query = MUTATION_UPDATE_SHIPPING_METHODmock_clean_shipping.return_value = is_valid_shipping_methodcheckout_id = graphene.Node.to_global_id("Checkout", checkout.pk)diff --git a/tests/api/test_checkout_digital.py b/tests/api/test_checkout_digital.pynew file mode 100644index 0000000000..fea12e4378--- /dev/null+++ b/tests/api/test_checkout_digital.py@@ -0,0 +1,183 @@+"""Test the API's checkout process over full digital orders."""+import pytest+from graphene import Node+from prices import TaxedMoney++from saleor.account.models import Address+from saleor.checkout.models import Checkout+from saleor.checkout.utils import add_variant_to_checkout+from saleor.order.models import Order+from tests.api.utils import get_graphql_content++from .test_checkout import (+ MUTATION_CHECKOUT_COMPLETE,+ MUTATION_CHECKOUT_CREATE,+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE,+ MUTATION_UPDATE_SHIPPING_METHOD,+)+++def checkout_with_digital_item(checkout, digital_content):+ """Create a checkout with a digital line."""+ variant = digital_content.product_variant+ add_variant_to_checkout(checkout, variant, 1)+ checkout.email = "[email protected]"+ checkout.save()+ return checkout++[email protected]("with_shipping_address", (True, False))+def test_create_checkout(+ api_client, digital_content, graphql_address_data, with_shipping_address+):+ """Test creating a checkout with a shipping address gets the address ignored."""++ address_count = Address.objects.count()++ variant = digital_content.product_variant+ variant_id = Node.to_global_id("ProductVariant", variant.pk)++ checkout_input = {+ "lines": [{"quantity": 1, "variantId": variant_id}],+ "email": "[email protected]",+ }++ if with_shipping_address:+ checkout_input["shippingAddress"] = graphql_address_data++ content = get_graphql_content(+ api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE, {"checkoutInput": checkout_input}+ )+ )["data"]["checkoutCreate"]++ # Ensure checkout was created+ assert content["created"] is True, "The checkout should have been created"++ # 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(+ api_client, checkout_with_digital_item, address, shipping_zone+):+ """Test no shipping method are available on digital orders."""++ query = """+ query getCheckout($token: UUID!) {+ checkout(token: $token) {+ availableShippingMethods {+ name+ }+ }+ }+ """++ checkout = checkout_with_digital_item++ # 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(query, {"token": checkout.token})+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ 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+ checkout_id = Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id, "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 have shipping"}+ ]++ # 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+ checkout_id = Node.to_global_id("Checkout", checkout.pk)+ method_id = Node.to_global_id("ShippingMethod", shipping_method.pk)+ variables = {"checkoutId": checkout_id, "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 have shipping"}+ ]++ # Ensure the shipping method was unchanged+ checkout.refresh_from_db(fields=["shipping_method"])+ assert checkout.shipping_method is None+++def test_checkout_complete(+ api_client, checkout_with_digital_item, address, payment_dummy+):+ """Ensure it is possible to complete a digital checkout without shipping."""++ order_count = Order.objects.count()+ checkout = checkout_with_digital_item+ checkout_id = Node.to_global_id("Checkout", checkout.pk)+ variables = {"checkoutId": checkout_id}++ # Set a billing address+ checkout.billing_address = address+ checkout.save(update_fields=["billing_address"])++ # Create a dummy payment to charge+ total = checkout.get_total()+ total = TaxedMoney(total, total)+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()+ assert not payment.transactions.exists()++ # Send the creation request+ response = api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)+ content = get_graphql_content(response)["data"]["checkoutComplete"]+ assert not content["errors"]++ # Ensure the order was actually created+ assert (+ Order.objects.count() == order_count + 1+ ), "The order should have been created"diff --git a/tests/conftest.py b/tests/conftest.pyindex f1dc98b237..4f75b748f7 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1195,7 +1195,7 @@ def payment_dummy(db, settings, order_with_lines):@pytest.fixture-def digital_content(category, media_root):+def digital_content(category, media_root) -> DigitalContent:product_type = ProductType.objects.create(name="Digital Type",has_variants=True,