Skip to content

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

Don't accumulate errors in lists passed between mutations' parts

Marcin Gębala2b63e120a144
diff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.py
index 606c2ccf9a..4300d87b59 100644
--- a/saleor/graphql/account/mutations.py
+++ b/saleor/graphql/account/mutations.py
@@ -128,10 +128,10 @@ class CustomerCreate(ModelMutation, I18nMixin):
return user.has_perm('account.manage_users')
@classmethod
- def clean_input(cls, info, instance, input, errors):
+ def clean_input(cls, info, instance, input):
shipping_address_data = input.pop(SHIPPING_ADDRESS_FIELD, None)
billing_address_data = input.pop(BILLING_ADDRESS_FIELD, None)
- cleaned_input = super().clean_input(info, instance, input, errors)
+ cleaned_input = super().clean_input(info, instance, input)
if shipping_address_data:
shipping_address = cls.validate_address(
@@ -234,8 +234,8 @@ class StaffCreate(ModelMutation):
return user.has_perm('account.manage_staff')
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
# set is_staff to True to create a staff user
cleaned_input['is_staff'] = True
@@ -279,8 +279,8 @@ class StaffUpdate(StaffCreate):
'is_active': 'Cannot deactivate superuser\'s account.'})
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
is_active = cleaned_input.get('is_active')
if is_active is not None:
cls.clean_is_active(is_active, instance, info.context.user)
@@ -305,10 +305,9 @@ class StaffDelete(StaffDeleteMixin, UserDelete):
if not cls.user_is_allowed(info.context.user, data):
raise PermissionDenied()
- errors = []
user_id = data.get('id')
- instance = cls.get_node_or_error(info, user_id, errors, 'id', User)
- cls.clean_instance(info, instance, errors)
+ instance = cls.get_node_or_error(info, user_id, only_type=User)
+ cls.clean_instance(info, instance)
db_id = instance.id
remove_staff_member(instance)
@@ -339,8 +338,8 @@ class SetPassword(ModelMutation):
model = models.User
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
token = cleaned_input.pop('token')
if not default_token_generator.check_token(instance, token):
raise ValidationError({'token': SetPassword.INVALID_TOKEN})
@@ -408,10 +407,10 @@ class AddressCreate(ModelMutation):
User, description='A user instance for which the address was created.')
class Arguments:
- input = AddressInput(
- description='Fields required to create address', required=True)
user_id = graphene.ID(
description='ID of a user to create address for', required=True)
+ input = AddressInput(
+ description='Fields required to create address', required=True)
class Meta:
description = 'Creates user address'
@@ -419,9 +418,9 @@ class AddressCreate(ModelMutation):
@classmethod
def perform_mutation(cls, root, info, **data):
- errors = []
user_id = data['user_id']
- user = cls.get_node_or_error(info, user_id, errors, 'userId', User)
+ user = cls.get_node_or_error(
+ info, user_id, field='user_id', only_type=User)
response = super().perform_mutation(root, info, **data)
if not response.errors:
user.addresses.add(response.address)
@@ -449,12 +448,12 @@ class AddressUpdate(ModelMutation):
exclude = ['user_addresses']
@classmethod
- def clean_input(cls, info, instance, input, errors):
+ def clean_input(cls, info, instance, input):
# Method user_is_allowed cannot be used for permission check, because
# it doesn't have the address instance.
if not can_edit_address(info.context.user, instance):
raise PermissionDenied()
- return super().clean_input(info, instance, input, errors)
+ return super().clean_input(info, instance, input)
@classmethod
def perform_mutation(cls, root, info, **data):
@@ -477,25 +476,22 @@ class AddressDelete(ModelDeleteMutation):
model = models.Address
@classmethod
- def clean_instance(cls, info, instance, errors):
+ def clean_instance(cls, info, instance):
# Method user_is_allowed cannot be used for permission check, because
# it doesn't have the address instance.
if not can_edit_address(info.context.user, instance):
raise PermissionDenied()
- return super().clean_instance(info, instance, errors)
+ return super().clean_instance(info, instance)
@classmethod
def perform_mutation(cls, root, info, **data):
if not cls.user_is_allowed(info.context.user, data):
raise PermissionDenied()
- errors = []
node_id = data.get('id')
- instance = cls.get_node_or_error(info, node_id, errors, 'id', Address)
+ instance = cls.get_node_or_error(info, node_id, Address)
if instance:
- cls.clean_instance(info, instance, errors)
- if errors:
- return cls(errors=errors)
+ cls.clean_instance(info, instance)
db_id = instance.id
@@ -539,10 +535,10 @@ class AddressSetDefault(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, address_id, user_id, type):
- errors = []
address = cls.get_node_or_error(
- info, address_id, errors, 'addressId', Address)
- user = cls.get_node_or_error(info, user_id, errors, 'userId', User)
+ info, address_id, field='address_id', only_type=Address)
+ user = cls.get_node_or_error(
+ info, user_id, field='user_id', only_type=User)
if address not in user.addresses.all():
raise ValidationError({
@@ -556,7 +552,7 @@ class AddressSetDefault(BaseMutation):
raise ValueError('Unknown value of AddressTypeEnum: %s' % type)
utils.change_user_default_address(user, address, address_type)
- return cls(errors=errors, user=user)
+ return cls(user=user)
# The same as AddressCreate, but for the currently authenticated user.
@@ -614,8 +610,7 @@ class CustomerSetDefaultAddress(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, type):
- errors = []
- address = cls.get_node_or_error(info, id, errors, 'id', Address)
+ address = cls.get_node_or_error(info, id, Address)
user = info.context.user
if address not in user.addresses.all():
@@ -630,7 +625,7 @@ class CustomerSetDefaultAddress(BaseMutation):
raise ValueError('Unknown value of AddressTypeEnum: %s' % type)
utils.change_user_default_address(user, address, address_type)
- return cls(errors=errors, user=user)
+ return cls(user=user)
class UserAvatarUpdate(BaseMutation):
diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.py
index beea316641..1acd9eda63 100644
--- a/saleor/graphql/account/utils.py
+++ b/saleor/graphql/account/utils.py
@@ -6,7 +6,7 @@ class UserDeleteMixin:
abstract = True
@classmethod
- def clean_instance(cls, info, instance, errors):
+ def clean_instance(cls, info, instance):
user = info.context.user
if instance == user:
raise ValidationError({
@@ -20,8 +20,8 @@ class CustomerDeleteMixin(UserDeleteMixin):
abstract = True
@classmethod
- def clean_instance(cls, info, instance, errors):
- super().clean_instance(info, instance, errors)
+ def clean_instance(cls, info, instance):
+ super().clean_instance(info, instance)
if instance.is_staff:
raise ValidationError({'id': 'Cannot delete a staff account.'})
@@ -31,7 +31,7 @@ class StaffDeleteMixin(UserDeleteMixin):
abstract = True
@classmethod
- def clean_instance(cls, info, instance, errors):
- super().clean_instance(info, instance, errors)
+ def clean_instance(cls, info, instance):
+ super().clean_instance(info, instance)
if not instance.is_staff:
raise ValidationError({'id': 'Cannot delete a non-staff user.'})
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 756252615e..5d8b368323 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -29,11 +29,11 @@ from .types import Checkout, CheckoutLine
def clean_shipping_method(
- checkout, method, errors, discounts, taxes, country_code=None,
- remove=True):
+ checkout, method, discounts, taxes, country_code=None, remove=True):
# FIXME Add tests for this function
if not method:
- return errors
+ return
+
if not checkout.is_shipping_required():
raise ValidationError('This checkout does not requires shipping.')
@@ -58,8 +58,6 @@ def clean_shipping_method(
checkout.shipping_method = None
checkout.save(update_fields=['shipping_method'])
- return errors
-
def check_lines_quantity(variants, quantities):
"""Check if stock is sufficient for each line in the list of dicts."""
@@ -108,15 +106,14 @@ class CheckoutCreate(ModelMutation, I18nMixin):
return_field_name = 'checkout'
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
user = info.context.user
lines = input.pop('lines', None)
if lines:
variant_ids = [line.get('variant_id') for line in lines]
variants = cls.get_nodes_or_error(
- ids=variant_ids, errors=errors, field='variant_id',
- only_type=ProductVariant)
+ variant_ids, 'variant_id', ProductVariant)
quantities = [line.get('quantity') for line in lines]
check_lines_quantity(variants, quantities)
@@ -170,7 +167,6 @@ class CheckoutCreate(ModelMutation, I18nMixin):
@classmethod
def perform_mutation(cls, root, info, input):
- errors = []
user = info.context.user
# `perform_mutation` is overriden to properly get or create a checkout
@@ -180,16 +176,16 @@ class CheckoutCreate(ModelMutation, I18nMixin):
# If user has an active checkout, return it without any
# modifications.
if not created:
- return CheckoutCreate(checkout=checkout, errors=errors)
+ return CheckoutCreate(checkout=checkout)
else:
checkout = models.Cart()
- cleaned_input = cls.clean_input(info, checkout, input, errors)
+ cleaned_input = cls.clean_input(info, checkout, input)
checkout = cls.construct_instance(checkout, cleaned_input)
- cls.clean_instance(checkout, errors)
+ cls.clean_instance(checkout)
cls.save(info, checkout, cleaned_input)
cls._save_m2m(info, checkout, cleaned_input)
- return CheckoutCreate(checkout=checkout, errors=errors)
+ return CheckoutCreate(checkout=checkout)
class CheckoutLinesAdd(BaseMutation):
@@ -210,16 +206,14 @@ class CheckoutLinesAdd(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, checkout_id, lines, replace=False):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
variants, quantities = None, None
variant_ids = [line.get('variant_id') for line in lines]
variants = cls.get_nodes_or_error(
- ids=variant_ids, errors=errors, field='variant_id',
- only_type=ProductVariant)
+ variant_ids, 'variant_id', ProductVariant)
quantities = [line.get('quantity') for line in lines]
check_lines_quantity(variants, quantities)
@@ -227,7 +221,7 @@ class CheckoutLinesAdd(BaseMutation):
# FIXME test if below function is called
clean_shipping_method(
checkout=checkout, method=checkout.shipping_method,
- errors=errors, discounts=info.context.discounts,
+ discounts=info.context.discounts,
taxes=get_taxes_for_address(checkout.shipping_address))
if variants and quantities:
@@ -238,7 +232,7 @@ class CheckoutLinesAdd(BaseMutation):
recalculate_cart_discount(
checkout, info.context.discounts, info.context.taxes)
- return CheckoutLinesAdd(checkout=checkout, errors=errors)
+ return CheckoutLinesAdd(checkout=checkout)
class CheckoutLinesUpdate(CheckoutLinesAdd):
@@ -266,25 +260,24 @@ class CheckoutLineDelete(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, checkout_id, line_id):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
line = cls.get_node_or_error(
- info, line_id, errors, 'line_id', only_type=CheckoutLine)
+ info, line_id, only_type=CheckoutLine, field='line_id')
if line and line in checkout.lines.all():
line.delete()
# FIXME test if below function is called
clean_shipping_method(
- checkout=checkout, method=checkout.shipping_method, errors=errors,
+ checkout=checkout, method=checkout.shipping_method,
discounts=info.context.discounts,
taxes=get_taxes_for_address(checkout.shipping_address))
recalculate_cart_discount(
checkout, info.context.discounts, info.context.taxes)
- return CheckoutLineDelete(checkout=checkout, errors=errors)
+ return CheckoutLineDelete(checkout=checkout)
class CheckoutCustomerAttach(BaseMutation):
@@ -301,14 +294,13 @@ class CheckoutCustomerAttach(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, checkout_id, customer_id):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
customer = cls.get_node_or_error(
- info, customer_id, errors, 'customer_id', only_type=User)
+ info, customer_id, only_type=User, field='customer_id')
checkout.user = customer
checkout.save(update_fields=['user'])
- return CheckoutCustomerAttach(checkout=checkout, errors=errors)
+ return CheckoutCustomerAttach(checkout=checkout)
class CheckoutCustomerDetach(BaseMutation):
@@ -322,9 +314,8 @@ class CheckoutCustomerDetach(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, checkout_id):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
checkout.user = None
checkout.save(update_fields=['user'])
return CheckoutCustomerDetach(checkout=checkout)
@@ -345,17 +336,16 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
@classmethod
def perform_mutation(cls, root, info, checkout_id, shipping_address):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
shipping_address = cls.validate_address(
shipping_address, instance=checkout.shipping_address)
# FIXME test if below function is called
clean_shipping_method(
- checkout, checkout.shipping_method, errors,
- info.context.discounts,
- get_taxes_for_address(shipping_address))
+ checkout=checkout, method=checkout.shipping_method,
+ discounts=info.context.discounts,
+ taxes=get_taxes_for_address(shipping_address))
with transaction.atomic():
shipping_address.save()
@@ -363,7 +353,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
recalculate_cart_discount(
checkout, info.context.discounts, info.context.taxes)
- return CheckoutShippingAddressUpdate(checkout=checkout, errors=errors)
+ return CheckoutShippingAddressUpdate(checkout=checkout)
class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):
@@ -380,16 +370,15 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):
@classmethod
def perform_mutation(cls, root, info, checkout_id, billing_address):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
billing_address = cls.validate_address(
billing_address, instance=checkout.billing_address)
with transaction.atomic():
billing_address.save()
change_billing_address_in_cart(checkout, billing_address)
- return CheckoutShippingAddressUpdate(checkout=checkout, errors=errors)
+ return CheckoutShippingAddressUpdate(checkout=checkout)
class CheckoutEmailUpdate(BaseMutation):
@@ -404,14 +393,13 @@ class CheckoutEmailUpdate(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, checkout_id, email):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
checkout.email = email
- cls.clean_instance(checkout, errors)
+ cls.clean_instance(checkout)
checkout.save(update_fields=['email'])
- return CheckoutEmailUpdate(checkout=checkout, errors=errors)
+ return CheckoutEmailUpdate(checkout=checkout)
class CheckoutShippingMethodUpdate(BaseMutation):
@@ -427,23 +415,23 @@ class CheckoutShippingMethodUpdate(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, checkout_id, shipping_method_id):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
shipping_method = cls.get_node_or_error(
- info, shipping_method_id, errors, 'shipping_method_id',
- only_type=ShippingMethod)
+ info, shipping_method_id, only_type=ShippingMethod,
+ field='shipping_method_id')
clean_shipping_method(
- checkout, shipping_method, errors, info.context.discounts,
- info.context.taxes, remove=False)
+ checkout=checkout, method=shipping_method,
+ discounts=info.context.discounts, taxes=info.context.taxes,
+ remove=False)
checkout.shipping_method = shipping_method
checkout.save(update_fields=['shipping_method'])
recalculate_cart_discount(
checkout, info.context.discounts, info.context.taxes)
- return CheckoutShippingMethodUpdate(checkout=checkout, errors=errors)
+ return CheckoutShippingMethodUpdate(checkout=checkout)
class CheckoutComplete(BaseMutation):
@@ -460,9 +448,8 @@ class CheckoutComplete(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, checkout_id):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
taxes = get_taxes_for_cart(checkout, info.context.taxes)
clean_checkout(checkout, taxes, info.context.discounts)
@@ -494,7 +481,7 @@ class CheckoutComplete(BaseMutation):
payment=payment, payment_token=payment.token)
except PaymentError as e:
raise ValidationError(str(e))
- return CheckoutComplete(order=order, errors=errors)
+ return CheckoutComplete(order=order)
class CheckoutUpdateVoucher(BaseMutation):
@@ -512,11 +499,8 @@ class CheckoutUpdateVoucher(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, checkout_id, voucher_code=None):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
- if checkout is None:
- return CheckoutUpdateVoucher(errors=errors)
+ info, checkout_id, only_type=Checkout, field='checkout_id')
if voucher_code:
try:
@@ -537,4 +521,4 @@ class CheckoutUpdateVoucher(BaseMutation):
if existing_voucher:
remove_voucher_from_cart(checkout)
- return CheckoutUpdateVoucher(checkout=checkout, errors=errors)
+ return CheckoutUpdateVoucher(checkout=checkout)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 95276db2be..cc16e5e3ef 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -90,7 +90,7 @@ class Checkout(CountableDjangoObjectType):
taxes = get_taxes_for_address(self.shipping_address)
price = self.get_subtotal(
taxes=taxes, discounts=info.context.discounts)
- return applicable_shipping_methods(self, info, price.gross.amount)
+ return applicable_shipping_methods(self, price.gross.amount)
def resolve_available_payment_gateways(self, info):
return settings.CHECKOUT_PAYMENT_GATEWAYS.keys()
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 4dd6edb1b1..0d359c1b4a 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -81,24 +81,24 @@ class BaseMutation(graphene.Mutation):
cls._meta.fields.update(fields)
@classmethod
- def get_node_or_error(cls, info, global_id, errors, field, only_type=None):
- if not global_id:
+ def get_node_or_error(cls, info, node_id, field='id', only_type=None):
+ if not node_id:
return None
node = None
try:
node = graphene.Node.get_node_from_global_id(
- info, global_id, only_type)
+ info, node_id, only_type)
except (AssertionError, GraphQLError) as e:
raise ValidationError({field: str(e)})
else:
if node is None:
raise ValidationError({
- field: "Couldn't resolve to a node: %s" % global_id})
+ field: "Couldn't resolve to a node: %s" % node_id})
return node
@classmethod
- def get_nodes_or_error(cls, ids, errors, field, only_type=None):
+ def get_nodes_or_error(cls, ids, field, only_type=None):
instances = None
try:
instances = get_nodes(ids, only_type)
@@ -107,12 +107,11 @@ class BaseMutation(graphene.Mutation):
return instances
@classmethod
- def clean_instance(cls, instance, errors):
+ def clean_instance(cls, instance):
"""Clean the instance that was created using the input data.
- Once a instance is created, this method runs `full_clean()` to perform
- model fields' validation. Returns errors ready to be returned by
- the GraphQL response (if any occurred).
+ Once an instance is created, this method runs `full_clean()` to perform
+ model validation.
"""
try:
instance.full_clean()
@@ -223,14 +222,13 @@ class ModelMutation(BaseMutation):
arguments=arguments, fields=fields)
@classmethod
- def clean_input(cls, info, instance, input, errors):
+ def clean_input(cls, info, instance, input):
"""Clean input data received from mutation arguments.
Fields containing IDs or lists of IDs are automatically resolved into
model instances. `instance` argument is the model instance the mutation
is operating on (before setting the input data). `input` is raw input
- data the mutation receives. `errors` is a list of errors that occurred
- during mutation's execution.
+ data the mutation receives.
Override this method to provide custom transformations of incoming
data.
@@ -262,14 +260,12 @@ class ModelMutation(BaseMutation):
# handle list of IDs field
if value is not None and is_list_of_ids(field):
instances = cls.get_nodes_or_error(
- value, errors=errors,
- field=field_name) if value else []
+ value, field_name) if value else []
cleaned_input[field_name] = instances
# handle ID field
elif value is not None and is_id_field(field):
- instance = cls.get_node_or_error(
- info, value, errors=errors, field=field_name)
+ instance = cls.get_node_or_error(info, value, field_name)
cleaned_input[field_name] = instance
# handle uploaded files
@@ -301,12 +297,12 @@ class ModelMutation(BaseMutation):
instance.save()
@classmethod
- def get_instance(cls, info, errors, **data):
+ def get_instance(cls, info, **data):
object_id = data.get('id')
if object_id:
model_type = registry.get_type_for_model(cls._meta.model)
instance = cls.get_node_or_error(
- info, object_id, errors, 'id', model_type)
+ info, object_id, only_type=model_type)
else:
instance = cls._meta.model()
return instance
@@ -320,14 +316,11 @@ class ModelMutation(BaseMutation):
that this is an "update" mutation. Otherwise, a new instance is
created based on the model associated with this mutation.
"""
- errors = [] # Initialize the errors list.
- instance = cls.get_instance(info, errors, **data)
-
+ instance = cls.get_instance(info, **data)
input_data = data.get('input')
-
- cleaned_input = cls.clean_input(info, instance, input_data, errors)
+ cleaned_input = cls.clean_input(info, instance, input_data)
instance = cls.construct_instance(instance, cleaned_input)
- cls.clean_instance(instance, errors)
+ cls.clean_instance(instance)
cls.save(info, instance, cleaned_input)
cls._save_m2m(info, instance, cleaned_input)
return cls.success_response(instance)
@@ -338,7 +331,7 @@ class ModelDeleteMutation(ModelMutation):
abstract = True
@classmethod
- def clean_instance(cls, info, instance, errors):
+ def clean_instance(cls, info, instance):
"""Perform additional logic before deleting the model instance.
Override this method to raise custom validation error and abort
@@ -351,17 +344,12 @@ class ModelDeleteMutation(ModelMutation):
if not cls.user_is_allowed(info.context.user, data):
raise PermissionDenied()
- errors = []
node_id = data.get('id')
model_type = registry.get_type_for_model(cls._meta.model)
- instance = cls.get_node_or_error(
- info, node_id, errors, 'id', model_type)
+ instance = cls.get_node_or_error(info, node_id, only_type=model_type)
if instance:
- cls.clean_instance(info, instance, errors)
-
- if errors:
- return cls(errors=errors)
+ cls.clean_instance(info, instance)
db_id = instance.id
instance.delete()
@@ -418,7 +406,7 @@ class ModelBulkDeleteMutation(BaseBulkMutation):
abstract = True
@classmethod
- def clean_instance(cls, info, instance, errors):
+ def clean_instance(cls, info, instance):
"""Perform additional logic before deleting the model instance.
Override this method to raise custom validation error and abort
@@ -430,14 +418,14 @@ class ModelBulkDeleteMutation(BaseBulkMutation):
"""Perform a mutation that deletes a list of model instances."""
count, errors = 0, {}
model_type = registry.get_type_for_model(cls._meta.model)
- instances = cls.get_nodes_or_error(ids, errors, 'id', model_type)
+ instances = cls.get_nodes_or_error(ids, 'id', model_type)
for instance, node_id in zip(instances, ids):
instance_errors = []
# catch individual validation errors to raise them later as
# a single error
try:
- cls.clean_instance(info, instance, [])
+ cls.clean_instance(info, instance)
except ValidationError as e:
msg = '. '.join(e.messages)
instance_errors.append(msg)
diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.py
index dde06022ae..05c5f77a75 100644
--- a/saleor/graphql/discount/mutations.py
+++ b/saleor/graphql/discount/mutations.py
@@ -29,39 +29,38 @@ class BaseDiscountCatalogueMutation(BaseMutation):
abstract = True
@classmethod
- def add_catalogues_to_node(cls, node, input, errors):
+ def add_catalogues_to_node(cls, node, input):
products = input.get('products', [])
if products:
products = cls.get_nodes_or_error(
- products, errors, 'products', only_type=Product)
+ products, 'products', Product)
node.products.add(*products)
categories = input.get('categories', [])
if categories:
categories = cls.get_nodes_or_error(
- categories, errors, 'categories', only_type=Category)
+ categories, 'categories', Category)
node.categories.add(*categories)
collections = input.get('collections', [])
if collections:
collections = cls.get_nodes_or_error(
- collections, errors, 'collections', only_type=Collection)
+ collections, 'collections', Collection)
node.collections.add(*collections)
@classmethod
- def remove_catalogues_from_node(cls, node, input, errors):
+ def remove_catalogues_from_node(cls, node, input):
products = input.get('products', [])
if products:
- products = cls.get_nodes_or_error(
- products, errors, 'products', only_type=Product)
+ products = cls.get_nodes_or_error(products, 'products', Product)
node.products.remove(*products)
categories = input.get('categories', [])
if categories:
categories = cls.get_nodes_or_error(
- categories, errors, 'categories', only_type=Category)
+ categories, 'categories', Category)
node.categories.remove(*categories)
collections = input.get('collections', [])
if collections:
collections = cls.get_nodes_or_error(
- collections, errors, 'collections', only_type=Collection)
+ collections, 'collections', Collection)
node.collections.remove(*collections)
@@ -110,11 +109,11 @@ class VoucherCreate(ModelMutation):
return user.has_perm('discount.manage_discounts')
@classmethod
- def clean_input(cls, info, instance, input, errors):
+ def clean_input(cls, info, instance, input):
code = input.get('code', None)
if code == '':
input['code'] = generate_voucher_code()
- cleaned_input = super().clean_input(info, instance, input, errors)
+ cleaned_input = super().clean_input(info, instance, input)
return cleaned_input
@@ -170,12 +169,10 @@ class VoucherAddCatalogues(VoucherBaseCatalogueMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- errors = []
voucher = cls.get_node_or_error(
- info, id, errors, 'voucherId', only_type=Voucher)
-
- cls.add_catalogues_to_node(voucher, input, errors)
- return VoucherAddCatalogues(voucher=voucher, errors=errors)
+ info, id, only_type=Voucher, field='voucher_id')
+ cls.add_catalogues_to_node(voucher, input)
+ return VoucherAddCatalogues(voucher=voucher)
class VoucherRemoveCatalogues(VoucherBaseCatalogueMutation):
@@ -189,12 +186,10 @@ class VoucherRemoveCatalogues(VoucherBaseCatalogueMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- errors = []
voucher = cls.get_node_or_error(
- info, id, errors, 'voucherId', only_type=Voucher)
-
- cls.remove_catalogues_from_node(voucher, input, errors)
- return VoucherRemoveCatalogues(voucher=voucher, errors=errors)
+ info, id, only_type=Voucher, field='voucher_id')
+ cls.remove_catalogues_from_node(voucher, input)
+ return VoucherRemoveCatalogues(voucher=voucher)
class SaleInput(graphene.InputObjectType):
@@ -285,12 +280,9 @@ class SaleAddCatalogues(SaleBaseCatalogueMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- errors = []
- sale = cls.get_node_or_error(
- info, id, errors, 'saleId', only_type=Sale)
-
- cls.add_catalogues_to_node(sale, input, errors)
- return SaleAddCatalogues(sale=sale, errors=errors)
+ sale = cls.get_node_or_error(info, id, only_type=Sale, field='sale_id')
+ cls.add_catalogues_to_node(sale, input)
+ return SaleAddCatalogues(sale=sale)
class SaleRemoveCatalogues(SaleBaseCatalogueMutation):
@@ -303,9 +295,7 @@ class SaleRemoveCatalogues(SaleBaseCatalogueMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- errors = []
sale = cls.get_node_or_error(
- info, id, errors, 'saleId', only_type=Sale)
-
- cls.remove_catalogues_from_node(sale, input, errors)
- return SaleRemoveCatalogues(sale=sale, errors=errors)
+ info, id, only_type=Sale, field='sale_id')
+ cls.remove_catalogues_from_node(sale, input)
+ return SaleRemoveCatalogues(sale=sale)
diff --git a/saleor/graphql/menu/mutations.py b/saleor/graphql/menu/mutations.py
index 8f74a413fc..f092420cef 100644
--- a/saleor/graphql/menu/mutations.py
+++ b/saleor/graphql/menu/mutations.py
@@ -57,10 +57,9 @@ class MenuCreate(ModelMutation):
return user.has_perm('menu.manage_menus')
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
items = []
- errors = {}
for item in cleaned_input.get('items', []):
category = item.get('category')
collection = item.get('collection')
@@ -71,24 +70,20 @@ class MenuCreate(ModelMutation):
else:
if category:
category = cls.get_node_or_error(
- info, category, errors, 'items', only_type=Category)
+ info, category, field='items', only_type=Category)
item['category'] = category
elif collection:
collection = cls.get_node_or_error(
- info, collection, errors, 'items',
- only_type=Collection)
+ info, collection, field='items', only_type=Collection)
item['collection'] = collection
elif page:
page = cls.get_node_or_error(
- info, page, errors, 'items', only_type=Page)
+ info, page, field='items', only_type=Page)
item['page'] = page
elif not url:
raise ValidationError({'items': 'No menu item provided.'})
items.append(item)
- if errors:
- raise ValidationError(errors)
-
cleaned_input['items'] = items
return cleaned_input
@@ -148,8 +143,8 @@ class MenuItemCreate(ModelMutation):
return user.has_perm('menu.manage_menus')
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
items = [
cleaned_input.get('page'), cleaned_input.get('collection'),
cleaned_input.get('url'), cleaned_input.get('category')]
@@ -220,11 +215,9 @@ class AssignNavigation(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, navigation_type, menu=None):
- errors = []
site_settings = info.context.site.settings
if menu is not None:
- menu = cls.get_node_or_error(
- info, menu, errors=errors, field='menu')
+ menu = cls.get_node_or_error(info, menu, field='menu')
if navigation_type == NavigationType.MAIN:
site_settings.top_menu = menu
@@ -236,4 +229,4 @@ class AssignNavigation(BaseMutation):
raise AssertionError(
'Unknown navigation type: %s' % navigation_type)
- return AssignNavigation(menu=menu, errors=errors)
+ return AssignNavigation(menu=menu)
diff --git a/saleor/graphql/order/bulk_mutations/draft_orders.py b/saleor/graphql/order/bulk_mutations/draft_orders.py
index e2880fbc7a..953bb623d1 100644
--- a/saleor/graphql/order/bulk_mutations/draft_orders.py
+++ b/saleor/graphql/order/bulk_mutations/draft_orders.py
@@ -17,7 +17,7 @@ class DraftOrderBulkDelete(ModelBulkDeleteMutation):
model = models.Order
@classmethod
- def clean_instance(cls, info, instance, errors):
+ def clean_instance(cls, info, instance):
if instance.status != OrderStatus.DRAFT:
raise ValidationError({'id': 'Cannot delete non-draft orders.'})
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index f3c8736172..e68e8bb43f 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -17,7 +17,7 @@ from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.scalars import Decimal
from ...product.types import ProductVariant
from ..types import Order, OrderLine
-from ..utils import can_finalize_draft_order
+from ..utils import validate_draft_order
class OrderLineInput(graphene.InputObjectType):
@@ -64,19 +64,20 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
model = models.Order
@classmethod
- def clean_input(cls, info, instance, input, errors):
+ def clean_input(cls, info, instance, input):
shipping_address = input.pop('shipping_address', None)
billing_address = input.pop('billing_address', None)
- cleaned_input = super().clean_input(info, instance, input, errors)
+ cleaned_input = super().clean_input(info, instance, input)
+
lines = input.pop('lines', None)
if lines:
variant_ids = [line.get('variant_id') for line in lines]
variants = cls.get_nodes_or_error(
- ids=variant_ids, only_type=ProductVariant, errors=errors,
- field='variants')
+ variant_ids, 'variants', ProductVariant)
quantities = [line.get('quantity') for line in lines]
cleaned_input['variants'] = variants
cleaned_input['quantities'] = quantities
+
cleaned_input['status'] = OrderStatus.DRAFT
display_gross_prices = info.context.site.settings.display_gross_prices
cleaned_input['display_gross_prices'] = display_gross_prices
@@ -180,21 +181,19 @@ class DraftOrderComplete(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id):
- errors = []
- order = cls.get_node_or_error(info, id, errors, 'id', Order)
- if order:
- errors = can_finalize_draft_order(order, errors)
- if errors:
- return cls(errors=errors)
-
+ order = cls.get_node_or_error(info, id, only_type=Order)
+ validate_draft_order(order)
cls.update_user_fields(order)
order.status = OrderStatus.UNFULFILLED
+
if not order.is_shipping_required():
order.shipping_method_name = None
order.shipping_price = ZERO_TAXED_MONEY
if order.shipping_address:
order.shipping_address.delete()
+
order.save()
+
oversold_items = []
for line in order:
try:
@@ -208,6 +207,7 @@ class DraftOrderComplete(BaseMutation):
type=OrderEvents.OVERSOLD_ITEMS.value,
user=info.context.user,
parameters={'oversold_items': oversold_items})
+
order.events.create(
type=OrderEvents.PLACED_FROM_DRAFT.value,
user=info.context.user)
@@ -237,7 +237,7 @@ class DraftOrderLinesCreate(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- order = cls.get_node_or_error(info, id, [], 'id', Order)
+ order = cls.get_node_or_error(info, id, only_type=Order)
if order.status != OrderStatus.DRAFT:
raise ValidationError({'id': 'Only draft orders can be edited.'})
@@ -245,7 +245,7 @@ class DraftOrderLinesCreate(BaseMutation):
for input_line in input:
variant_id = input_line['variant_id']
variant = cls.get_node_or_error(
- info, variant_id, [], 'variant_id', ProductVariant)
+ info, variant_id, 'variant_id', only_type=ProductVariant)
quantity = input_line['quantity']
if quantity > 0:
if variant:
@@ -279,7 +279,7 @@ class DraftOrderLineDelete(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id):
- line = cls.get_node_or_error(info, id, [], 'id', OrderLine)
+ line = cls.get_node_or_error(info, id, only_type=OrderLine)
order = line.order
if order.status != OrderStatus.DRAFT:
raise ValidationError({'id': 'Only draft orders can be edited.'})
@@ -310,8 +310,8 @@ class DraftOrderLineUpdate(ModelMutation):
return user.has_perm('order.manage_orders')
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
if instance.order.status != OrderStatus.DRAFT:
raise ValidationError({'id': 'Only draft orders can be edited.'})
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index f5ac610837..d44a171ad5 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -67,7 +67,7 @@ class FulfillmentCreate(BaseMutation):
description = 'Creates a new fulfillment for an order.'
@classmethod
- def clean_lines(cls, order_lines, quantities, errors):
+ def clean_lines(cls, order_lines, quantities):
for order_line, quantity in zip(order_lines, quantities):
if quantity > order_line.quantity_unfulfilled:
msg = npgettext_lazy(
@@ -80,14 +80,14 @@ class FulfillmentCreate(BaseMutation):
raise ValidationError({'order_line_id': msg})
@classmethod
- def clean_input(cls, input, errors):
+ def clean_input(cls, input):
lines = input['lines']
quantities = [line['quantity'] for line in lines]
lines_ids = [line['order_line_id'] for line in lines]
order_lines = cls.get_nodes_or_error(
- lines_ids, errors, 'lines', OrderLine)
+ lines_ids, field='lines', only_type=OrderLine)
- cls.clean_lines(order_lines, quantities, errors)
+ cls.clean_lines(order_lines, quantities)
if sum(quantities) <= 0:
raise ValidationError({
@@ -129,12 +129,12 @@ class FulfillmentCreate(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, order, input):
- errors = []
- order = cls.get_node_or_error(info, order, errors, 'order', Order)
+ order = cls.get_node_or_error(
+ info, order, field='order', only_type=Order)
fulfillment = models.Fulfillment(
tracking_number=input.pop('tracking_number', None) or '',
order=order)
- cleaned_input = cls.clean_input(input, errors)
+ cleaned_input = cls.clean_input(input)
fulfillment = cls.save(
info.context.user, fulfillment, order, cleaned_input)
return FulfillmentCreate(
@@ -163,9 +163,7 @@ class FulfillmentUpdateTracking(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- errors = []
- fulfillment = cls.get_node_or_error(
- info, id, errors, 'id', Fulfillment)
+ fulfillment = cls.get_node_or_error(info, id, only_type=Fulfillment)
tracking_number = input.get('tracking_number') or ''
fulfillment.tracking_number = tracking_number
fulfillment.save()
@@ -203,7 +201,7 @@ class FulfillmentCancel(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
restock = input.get('restock')
- fulfillment = cls.get_node_or_error(info, id, [], 'id', Fulfillment)
+ fulfillment = cls.get_node_or_error(info, id, only_type=Fulfillment)
if not fulfillment.can_edit():
err_msg = pgettext_lazy(
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 27b5fdf3b3..dab120ad7e 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -119,8 +119,7 @@ class OrderUpdateShipping(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- errors = []
- order = cls.get_node_or_error(info, id, errors, 'id', Order)
+ order = cls.get_node_or_error(info, id, only_type=Order)
if not input['shipping_method']:
if not order.is_draft() and order.is_shipping_required():
@@ -138,8 +137,8 @@ class OrderUpdateShipping(BaseMutation):
return OrderUpdateShipping(order=order)
method = cls.get_node_or_error(
- info, input['shipping_method'], errors,
- 'shipping_method', ShippingMethod)
+ info, input['shipping_method'], field='shipping_method',
+ only_type=ShippingMethod)
clean_order_update_shipping(order, method)
@@ -178,8 +177,7 @@ class OrderAddNote(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- errors = []
- order = cls.get_node_or_error(info, id, errors, 'id', Order)
+ order = cls.get_node_or_error(info, id, only_type=Order)
event = order.events.create(
type=OrderEvents.NOTE_ADDED.value,
user=info.context.user,
@@ -207,8 +205,7 @@ class OrderCancel(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, restock):
- errors = []
- order = cls.get_node_or_error(info, id, errors, 'id', Order)
+ order = cls.get_node_or_error(info, id, only_type=Order)
clean_order_cancel(order)
cancel_order(order=order, restock=restock)
if restock:
@@ -238,8 +235,7 @@ class OrderMarkAsPaid(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id):
- errors = []
- order = cls.get_node_or_error(info, id, errors, 'id', Order)
+ order = cls.get_node_or_error(info, id, only_type=Order)
try:
clean_mark_order_as_paid(order)
except PaymentError as e:
@@ -266,12 +262,11 @@ class OrderCapture(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, amount):
- errors = []
if amount <= 0:
raise ValidationError({
'amount': 'Amount should be a positive number.'})
- order = cls.get_node_or_error(info, id, errors, 'id', Order)
+ order = cls.get_node_or_error(info, id, only_type=Order)
payment = order.get_last_payment()
clean_order_capture(payment, amount)
@@ -303,8 +298,7 @@ class OrderVoid(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id):
- errors = []
- order = cls.get_node_or_error(info, id, errors, 'id', Order)
+ order = cls.get_node_or_error(info, id, only_type=Order)
payment = order.get_last_payment()
clean_void_payment(payment)
try:
@@ -335,12 +329,11 @@ class OrderRefund(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, amount):
- errors = []
if amount <= 0:
raise ValidationError({
'amount': 'Amount should be a positive number.'})
- order = cls.get_node_or_error(info, id, errors, 'id', Order)
+ order = cls.get_node_or_error(info, id, only_type=Order)
payment = order.get_last_payment()
clean_refund_payment(payment, amount)
diff --git a/saleor/graphql/order/resolvers.py b/saleor/graphql/order/resolvers.py
index d04d5c0b49..7f437cce13 100644
--- a/saleor/graphql/order/resolvers.py
+++ b/saleor/graphql/order/resolvers.py
@@ -54,10 +54,6 @@ def resolve_order(info, id):
return None
-def resolve_shipping_methods(obj, info, price):
- return applicable_shipping_methods(obj, info, price)
-
-
def resolve_homepage_events(info):
# Filter only selected events to be displayed on homepage.
types = [
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 8571158008..5d3da9dd6b 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1,5 +1,6 @@
from textwrap import dedent
+from django.core.exceptions import ValidationError
import graphene
import graphene_django_optimizer as gql_optimizer
from graphene import relay
@@ -14,7 +15,7 @@ from ..payment.types import OrderAction, Payment, PaymentChargeStatusEnum
from ..product.types import Image, ProductVariant
from ..shipping.types import ShippingMethod
from .enums import OrderEventsEmailsEnum, OrderEventsEnum
-from .utils import applicable_shipping_methods, can_finalize_draft_order
+from .utils import applicable_shipping_methods, validate_draft_order
class OrderEvent(CountableDjangoObjectType):
@@ -318,8 +319,11 @@ class Order(CountableDjangoObjectType):
@staticmethod
def resolve_can_finalize(self, info):
- errors = can_finalize_draft_order(self, [])
- return not errors
+ try:
+ validate_draft_order(self)
+ except ValidationError:
+ return False
+ return True
@staticmethod
def resolve_user_email(self, info):
@@ -332,7 +336,7 @@ class Order(CountableDjangoObjectType):
@staticmethod
def resolve_available_shipping_methods(self, info):
return applicable_shipping_methods(
- self, info, self.get_subtotal().gross.amount)
+ self, self.get_subtotal().gross.amount)
def resolve_is_shipping_required(self, info):
return self.is_shipping_required()
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index d183907dbc..4bbd12e0d7 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -1,54 +1,47 @@
+from django.core.exceptions import ValidationError
+
from ...shipping import models as shipping_models
-from ..core.types.common import Error
-def _check_can_finalize_products_quantity(order, errors):
+def validate_total_quantity(order):
if order.get_total_quantity() == 0:
- errors.append(
- Error(
- field='lines',
- message='Could not create order without any products.'))
+ raise ValidationError({
+ 'lines': 'Could not create order without any products.'})
-def _check_can_finalize_shipping(order, errors):
- if order.is_shipping_required():
- method = order.shipping_method
- shipping_address = order.shipping_address
- shipping_not_valid = (
- method and shipping_address and
- shipping_address.country.code not in method.shipping_zone.countries) # noqa
- if shipping_not_valid:
- errors.append(
- Error(
- field='shipping',
- message='Shipping method is not valid for chosen shipping '
- 'address'))
-
-
-def _check_can_finalize_products_exists(order, errors):
- line_variants = [line.variant for line in order]
- if None in line_variants:
- errors.append(
- Error(
- field='lines',
- message='Could not create orders with non-existing products.'))
-
-
-def can_finalize_draft_order(order, errors):
- """Return a list of errors associated with the order.
-
- Checks, if given order has a proper customer data, shipping
+def validate_shipping_method(order):
+ method = order.shipping_method
+ shipping_address = order.shipping_address
+ shipping_not_valid = (
+ method and shipping_address and
+ shipping_address.country.code not in method.shipping_zone.countries) # noqa
+ if shipping_not_valid:
+ raise ValidationError({
+ 'shipping':
+ 'Shipping method is not valid for chosen shipping address'})
+
+
+def validate_order_lines(order):
+ for line in order:
+ if line.variant is None:
+ raise ValidationError({
+ 'lines': 'Could not create orders with non-existing products.'})
+
+
+def validate_draft_order(order):
+ """Checks, if given order has a proper customer data, shipping
address and method set up and return list of errors if not.
Checks if product variants for order lines still exists in
database, too.
"""
- _check_can_finalize_products_quantity(order, errors)
- _check_can_finalize_shipping(order, errors)
- _check_can_finalize_products_exists(order, errors)
- return errors
+ if order.is_shipping_required():
+ validate_shipping_method(order)
+ validate_total_quantity(order)
+ validate_order_lines(order)
-def applicable_shipping_methods(obj, info, price):
+# FIXME: is this function needed? QS method might be enough
+def applicable_shipping_methods(obj, price):
if not obj.is_shipping_required():
return []
if not obj.shipping_address:
diff --git a/saleor/graphql/page/mutations.py b/saleor/graphql/page/mutations.py
index 6d7713c3bb..41e99b943c 100644
--- a/saleor/graphql/page/mutations.py
+++ b/saleor/graphql/page/mutations.py
@@ -36,8 +36,8 @@ class PageCreate(ModelMutation):
return user.has_perm('page.manage_pages')
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
slug = cleaned_input.get('slug', '')
if not slug:
cleaned_input['slug'] = slugify(cleaned_input['title'])
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index d406156b5e..c436ef3274 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -55,9 +55,8 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
@classmethod
def perform_mutation(cls, root, info, checkout_id, input):
- errors = []
checkout = cls.get_node_or_error(
- info, checkout_id, errors, 'checkout_id', only_type=Checkout)
+ info, checkout_id, field='checkout_id', only_type=Checkout)
billing_address = checkout.billing_address
if 'billing_address' in input:
@@ -109,10 +108,8 @@ class PaymentCapture(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, payment_id, amount=None):
- errors = []
payment = cls.get_node_or_error(
- info, payment_id, errors, 'payment_id', only_type=Payment)
-
+ info, payment_id, field='payment_id', only_type=Payment)
try:
gateway_capture(payment, amount)
except PaymentError as e:
@@ -131,10 +128,8 @@ class PaymentRefund(PaymentCapture):
@classmethod
def perform_mutation(cls, root, info, payment_id, amount=None):
- errors = []
payment = cls.get_node_or_error(
- info, payment_id, errors, 'payment_id', only_type=Payment)
-
+ info, payment_id, field='payment_id', only_type=Payment)
try:
gateway_refund(payment, amount=amount)
except PaymentError as e:
@@ -157,10 +152,8 @@ class PaymentVoid(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, payment_id, amount=None):
- errors = []
payment = cls.get_node_or_error(
- info, payment_id, errors, 'payment_id', only_type=Payment)
-
+ info, payment_id, field='payment_id', only_type=Payment)
try:
gateway_void(payment)
except PaymentError as e:
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index a436390683..144023ea23 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -56,7 +56,7 @@ class AttributeMixin:
'Provided values are not unique.'})
@classmethod
- def clean_values(cls, cleaned_input, attribute, errors):
+ def clean_values(cls, cleaned_input, attribute):
"""Clean attribute values.
Transforms AttributeValueCreateInput into AttributeValue instances.
@@ -81,7 +81,7 @@ class AttributeMixin:
@classmethod
def clean_attribute(
- cls, instance, cleaned_input, errors, product_type=None):
+ cls, instance, cleaned_input, product_type=None):
if 'name' in cleaned_input:
slug = slugify(cleaned_input['name'])
elif instance.pk:
@@ -141,17 +141,15 @@ class AttributeCreate(AttributeMixin, ModelMutation):
@classmethod
def perform_mutation(cls, root, info, id, type, input):
- errors = []
- product_type = cls.get_node_or_error(
- info, id, errors, 'id', ProductType)
+ product_type = cls.get_node_or_error(info, id, only_type=ProductType)
instance = models.Attribute()
- cleaned_input = cls.clean_input(info, instance, input, errors)
+ cleaned_input = cls.clean_input(info, instance, input)
cls.clean_attribute(
- instance, cleaned_input, errors, product_type=product_type)
- cls.clean_values(cleaned_input, instance, errors)
+ instance, cleaned_input, product_type=product_type)
+ cls.clean_values(cleaned_input, instance)
instance = cls.construct_instance(instance, cleaned_input)
- cls.clean_instance(instance, errors)
+ cls.clean_instance(instance)
instance.save()
if type == AttributeTypeEnum.VARIANT.name:
@@ -180,7 +178,7 @@ class AttributeUpdate(AttributeMixin, ModelMutation):
model = models.Attribute
@classmethod
- def clean_remove_values(cls, cleaned_input, instance, errors):
+ def clean_remove_values(cls, cleaned_input, instance):
"""Check if AttributeValues to be removed are assigned to given
Attribute.
"""
@@ -203,17 +201,16 @@ class AttributeUpdate(AttributeMixin, ModelMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- errors = []
- instance = cls.get_node_or_error(info, id, errors, 'id', Attribute)
+ instance = cls.get_node_or_error(info, id, only_type=Attribute)
- cleaned_input = cls.clean_input(info, instance, input, errors)
+ cleaned_input = cls.clean_input(info, instance, input)
product_type = instance.product_type
cls.clean_attribute(
- instance, cleaned_input, errors, product_type=product_type)
- cls.clean_values(cleaned_input, instance, errors)
- cls.clean_remove_values(cleaned_input, instance, errors)
+ instance, cleaned_input, product_type=product_type)
+ cls.clean_values(cleaned_input, instance)
+ cls.clean_remove_values(cleaned_input, instance)
instance = cls.construct_instance(instance, cleaned_input)
- cls.clean_instance(instance, errors)
+ cls.clean_instance(instance)
instance.save()
cls._save_m2m(info, instance, cleaned_input)
@@ -261,8 +258,8 @@ class AttributeValueCreate(ModelMutation):
model = models.AttributeValue
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
cleaned_input['slug'] = slugify(cleaned_input['name'])
return cleaned_input
@@ -272,14 +269,13 @@ class AttributeValueCreate(ModelMutation):
@classmethod
def perform_mutation(cls, root, info, attribute_id, input):
- errors = []
attribute = cls.get_node_or_error(
- info, attribute_id, errors, 'id', Attribute)
+ info, attribute_id, only_type=Attribute)
instance = models.AttributeValue(attribute=attribute)
- cleaned_input = cls.clean_input(info, instance, input, errors)
+ cleaned_input = cls.clean_input(info, instance, input)
instance = cls.construct_instance(instance, cleaned_input)
- cls.clean_instance(instance, errors)
+ cls.clean_instance(instance)
instance.save()
cls._save_m2m(info, instance, cleaned_input)
@@ -307,8 +303,8 @@ class AttributeValueUpdate(ModelMutation):
return user.has_perm('product.manage_products')
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
if 'name' in cleaned_input:
cleaned_input['slug'] = slugify(cleaned_input['name'])
return cleaned_input
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index af2f1146b5..406d3fde17 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -48,18 +48,18 @@ class CategoryCreate(ModelMutation):
model = models.Category
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
if 'slug' not in cleaned_input and 'name' in cleaned_input:
cleaned_input['slug'] = slugify(cleaned_input['name'])
parent_id = input['parent_id']
if parent_id:
parent = cls.get_node_or_error(
- info, parent_id, errors, field='parent', only_type=Category)
+ info, parent_id, field='parent', only_type=Category)
cleaned_input['parent'] = parent
if input.get('background_image'):
image_data = info.context.FILES.get(input['background_image'])
- validate_image_file(cls, image_data, 'background_image', errors)
+ validate_image_file(image_data, 'background_image')
clean_seo_fields(cleaned_input)
return cleaned_input
@@ -151,13 +151,13 @@ class CollectionCreate(ModelMutation):
return user.has_perm('product.manage_products')
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
if 'slug' not in cleaned_input and 'name' in cleaned_input:
cleaned_input['slug'] = slugify(cleaned_input['name'])
if input.get('background_image'):
image_data = info.context.FILES.get(input['background_image'])
- validate_image_file(cls, image_data, 'background_image', errors)
+ validate_image_file(image_data, 'background_image')
clean_seo_fields(cleaned_input)
return cleaned_input
@@ -223,13 +223,11 @@ class CollectionAddProducts(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, collection_id, products):
- errors = []
collection = cls.get_node_or_error(
- info, collection_id, errors, 'collectionId', only_type=Collection)
- products = cls.get_nodes_or_error(
- products, errors, 'products', only_type=Product)
+ info, collection_id, field='collection_id', only_type=Collection)
+ products = cls.get_nodes_or_error(products, 'products', Product)
collection.products.add(*products)
- return CollectionAddProducts(collection=collection, errors=[])
+ return CollectionAddProducts(collection=collection)
class CollectionRemoveProducts(BaseMutation):
@@ -252,11 +250,10 @@ class CollectionRemoveProducts(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, collection_id, products):
- errors = []
collection = cls.get_node_or_error(
- info, collection_id, errors, 'collectionId', only_type=Collection)
+ info, collection_id, field='collection_id', only_type=Collection)
products = cls.get_nodes_or_error(
- products, errors, 'products', only_type=Product)
+ products, 'products', only_type=Product)
collection.products.remove(*products)
return CollectionRemoveProducts(collection=collection)
@@ -324,8 +321,8 @@ class ProductCreate(ModelMutation):
model = models.Product
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
# Attributes are provided as list of `AttributeValueInput` objects.
# We need to transform them into the format they're stored in the
# `Product` model, which is HStore field that maps attribute's PK to
@@ -345,11 +342,11 @@ class ProductCreate(ModelMutation):
else:
cleaned_input['attributes'] = attributes
clean_seo_fields(cleaned_input)
- cls.clean_sku(product_type, cleaned_input, errors)
+ cls.clean_sku(product_type, cleaned_input)
return cleaned_input
@classmethod
- def clean_sku(cls, product_type, cleaned_input, errors):
+ def clean_sku(cls, product_type, cleaned_input):
"""Validate SKU input field.
When creating products that don't use variants, SKU is required in
@@ -402,7 +399,7 @@ class ProductUpdate(ProductCreate):
model = models.Product
@classmethod
- def clean_sku(cls, product_type, cleaned_input, errors):
+ def clean_sku(cls, product_type, cleaned_input):
input_sku = cleaned_input.get('sku')
if (not product_type.has_variants and
input_sku and
@@ -482,8 +479,7 @@ class ProductVariantCreate(ModelMutation):
model = models.ProductVariant
@classmethod
- def clean_product_type_attributes(
- cls, attributes_qs, attributes_input, errors):
+ def clean_product_type_attributes(cls, attributes_qs, attributes_input):
# transform attributes_input list to a dict of slug:value pairs
attributes_input = {
item['slug']: item['value'] for item in attributes_input}
@@ -496,8 +492,8 @@ class ProductVariantCreate(ModelMutation):
fieldname: 'This field cannot be blank.'})
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
# Attributes are provided as list of `AttributeValueInput` objects.
# We need to transform them into the format they're stored in the
@@ -513,7 +509,7 @@ class ProductVariantCreate(ModelMutation):
'values')
try:
cls.clean_product_type_attributes(
- variant_attrs, attributes_input, errors)
+ variant_attrs, attributes_input)
attributes = attributes_to_hstore(
attributes_input, variant_attrs)
except ValueError as e:
@@ -675,11 +671,10 @@ class ProductImageCreate(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, input):
- errors = []
product = cls.get_node_or_error(
- info, input['product'], errors, 'product', only_type=Product)
+ info, input['product'], field='product', only_type=Product)
image_data = info.context.FILES.get(input['image'])
- validate_image_file(cls, image_data, 'image', errors)
+ validate_image_file(image_data, 'image')
image = product.images.create(
image=image_data, alt=input.get('alt', ''))
@@ -711,15 +706,12 @@ class ProductImageUpdate(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id, input):
- errors = []
- image = cls.get_node_or_error(
- info, id, errors, 'id', only_type=ProductImage)
+ image = cls.get_node_or_error(info, id, only_type=ProductImage)
product = image.product
- if not errors:
- alt = input.get('alt')
- if alt is not None:
- image.alt = alt
- image.save(update_fields=['alt'])
+ alt = input.get('alt')
+ if alt is not None:
+ image.alt = alt
+ image.save(update_fields=['alt'])
return ProductImageUpdate(product=product, image=image)
@@ -744,26 +736,27 @@ class ProductImageReorder(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, product_id, images_ids):
- errors = []
product = cls.get_node_or_error(
- info, product_id, errors, 'productId', Product)
+ info, product_id, field='product_id', only_type=Product)
if len(images_ids) != product.images.count():
raise ValidationError({
'order': 'Incorrect number of image IDs provided.'})
+
images = []
for image_id in images_ids:
image = cls.get_node_or_error(
- info, image_id, errors, 'order', only_type=ProductImage)
+ info, image_id, field='order', only_type=ProductImage)
if image and image.product != product:
raise ValidationError({
'order':
'Image %(image_id)s does not belong to this product.'},
params={'image_id': image_id})
images.append(image)
- if not errors:
- for order, image in enumerate(images):
- image.sort_order = order
- image.save(update_fields=['sort_order'])
+
+ for order, image in enumerate(images):
+ image.sort_order = order
+ image.save(update_fields=['sort_order'])
+
return ProductImageReorder(
product=product, images=images)
@@ -785,12 +778,9 @@ class ProductImageDelete(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id):
- errors = []
- image = cls.get_node_or_error(
- info, id, errors, 'id', only_type=ProductImage)
+ image = cls.get_node_or_error(info, id, only_type=ProductImage)
image_id = image.id
- if not errors:
- image.delete()
+ image.delete()
image.id = image_id
return ProductImageDelete(
product=image.product, image=image)
@@ -817,11 +807,10 @@ class VariantImageAssign(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, image_id, variant_id):
- errors = []
image = cls.get_node_or_error(
- info, image_id, errors, 'imageId', ProductImage)
+ info, image_id, field='image_id', only_type=ProductImage)
variant = cls.get_node_or_error(
- info, variant_id, errors, 'variantId', ProductVariant)
+ info, variant_id, field='variant_id', only_type=ProductVariant)
if image and variant:
# check if the given image and variant can be matched together
image_belongs_to_product = variant.product.images.filter(
@@ -855,20 +844,18 @@ class VariantImageUnassign(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, image_id, variant_id):
- errors = []
image = cls.get_node_or_error(
- info, image_id, errors, 'imageId', ProductImage)
+ info, image_id, field='image_id', only_type=ProductImage)
variant = cls.get_node_or_error(
- info, variant_id, errors, 'variantId', ProductVariant)
- if not errors:
- if image and variant:
- try:
- variant_image = models.VariantImage.objects.get(
- image=image, variant=variant)
- except models.VariantImage.DoesNotExist:
- raise ValidationError({
- 'image_id': 'Image is not assigned to this variant.'})
- else:
- variant_image.delete()
- return VariantImageUnassign(
- product_variant=variant, image=image)
+ info, variant_id, field='variant_id', only_type=ProductVariant)
+
+ try:
+ variant_image = models.VariantImage.objects.get(
+ image=image, variant=variant)
+ except models.VariantImage.DoesNotExist:
+ raise ValidationError({
+ 'image_id': 'Image is not assigned to this variant.'})
+ else:
+ variant_image.delete()
+
+ return VariantImageUnassign(product_variant=variant, image=image)
diff --git a/saleor/graphql/shipping/mutations.py b/saleor/graphql/shipping/mutations.py
index 110158e0ff..7bb84df265 100644
--- a/saleor/graphql/shipping/mutations.py
+++ b/saleor/graphql/shipping/mutations.py
@@ -44,8 +44,8 @@ class ShippingZoneInput(graphene.InputObjectType):
class ShippingZoneMixin:
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
default = cleaned_input.get('default')
if default:
if default_shipping_zone_exists(instance.pk):
@@ -112,8 +112,8 @@ class ShippingZoneDelete(ModelDeleteMutation):
class ShippingPriceMixin:
@classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
+ def clean_input(cls, info, instance, input):
+ cleaned_input = super().clean_input(info, instance, input)
type = cleaned_input.get('type')
if type:
if type == ShippingMethodTypeEnum.PRICE.value:
@@ -209,10 +209,8 @@ class ShippingPriceDelete(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, id):
- errors = []
shipping_method = cls.get_node_or_error(
- info, id, errors, 'id', only_type=ShippingMethod)
-
+ info, id, only_type=ShippingMethod)
shipping_method_id = shipping_method.id
shipping_zone = shipping_method.shipping_zone
shipping_method.delete()
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index 29c775c840..76587b3ecc 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -53,14 +53,12 @@ class ShopSettingsUpdate(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, input):
- errors = []
instance = info.context.site.settings
for field_name, desired_value in input.items():
current_value = getattr(instance, field_name)
if current_value != desired_value:
setattr(instance, field_name, desired_value)
- cls.clean_instance(instance, errors)
-
+ cls.clean_instance(instance)
instance.save()
return ShopSettingsUpdate(shop=Shop())
@@ -80,7 +78,6 @@ class ShopDomainUpdate(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, input):
- errors = []
site = info.context.site
domain = input.get('domain')
name = input.get('name')
@@ -88,7 +85,7 @@ class ShopDomainUpdate(BaseMutation):
site.domain = domain
if name is not None:
site.name = name
- cls.clean_instance(site, errors)
+ cls.clean_instance(site)
site.save()
return ShopDomainUpdate(shop=Shop())
@@ -105,7 +102,6 @@ class ShopFetchTaxRates(BaseMutation):
@classmethod
def perform_mutation(cls, root, info):
- errors = []
if settings.VATLAYER_ACCESS_KEY:
call_command('get_vat_rates')
else:
@@ -131,12 +127,11 @@ class HomepageCollectionUpdate(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, collection=None):
- errors = []
new_collection = cls.get_node_or_error(
- info, collection, errors, 'collection', Collection)
+ info, collection, field='collection', only_type=Collection)
site_settings = info.context.site.settings
site_settings.homepage_collection = new_collection
- cls.clean_instance(site_settings, errors)
+ cls.clean_instance(site_settings)
site_settings.save(update_fields=['homepage_collection'])
return HomepageCollectionUpdate(shop=Shop())
@@ -169,7 +164,6 @@ class AuthorizationKeyAdd(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, key_type, input):
- errors = []
if site_models.AuthorizationKey.objects.filter(name=key_type).exists():
raise ValidationError({
'key_type': 'Authorization key already exists.'})
@@ -177,7 +171,7 @@ class AuthorizationKeyAdd(BaseMutation):
site_settings = info.context.site.settings
instance = site_models.AuthorizationKey(
name=key_type, site_settings=site_settings, **input)
- cls.clean_instance(instance, errors)
+ cls.clean_instance(instance)
instance.save()
return AuthorizationKeyAdd(authorization_key=instance, shop=Shop())
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index b5995e23e6..9c8e762b2d 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -744,13 +744,13 @@ def test_customer_delete(
def test_customer_delete_errors(customer_user, admin_user, staff_user):
info = Mock(context=Mock(user=admin_user))
with pytest.raises(ValidationError) as e:
- CustomerDelete.clean_instance(info, staff_user, [])
+ CustomerDelete.clean_instance(info, staff_user)
msg = 'Cannot delete a staff account.'
assert e.value.error_dict['id'][0].message == msg
# shuold not raise any errors
- CustomerDelete.clean_instance(info, customer_user, [])
+ CustomerDelete.clean_instance(info, customer_user)
@patch('saleor.dashboard.emails.send_set_password_staff_email.delay')
@@ -878,14 +878,14 @@ def test_staff_delete(staff_api_client, permission_manage_staff):
def test_user_delete_errors(staff_user, admin_user):
info = Mock(context=Mock(user=staff_user))
with pytest.raises(ValidationError) as e:
- UserDelete.clean_instance(info, staff_user, [])
+ UserDelete.clean_instance(info, staff_user)
msg = 'You cannot delete your own account.'
assert e.value.error_dict['id'][0].message == msg
info = Mock(context=Mock(user=staff_user))
with pytest.raises(ValidationError) as e:
- UserDelete.clean_instance(info, admin_user, [])
+ UserDelete.clean_instance(info, admin_user)
msg = 'Cannot delete this account.'
assert e.value.error_dict['id'][0].message == msg
@@ -894,13 +894,13 @@ def test_user_delete_errors(staff_user, admin_user):
def test_staff_delete_errors(staff_user, customer_user, admin_user):
info = Mock(context=Mock(user=staff_user))
with pytest.raises(ValidationError) as e:
- StaffDelete.clean_instance(info, customer_user, [])
+ StaffDelete.clean_instance(info, customer_user)
msg = 'Cannot delete a non-staff user.'
assert e.value.error_dict['id'][0].message == msg
# shuold not raise any errors
info = Mock(context=Mock(user=admin_user))
- StaffDelete.clean_instance(info, staff_user, [])
+ StaffDelete.clean_instance(info, staff_user)
def test_staff_update_errors(staff_user, customer_user, admin_user):
diff --git a/tests/api/test_base_mutation.py b/tests/api/test_base_mutation.py
index 50c3afd54b..9e96f970ee 100644
--- a/tests/api/test_base_mutation.py
+++ b/tests/api/test_base_mutation.py
@@ -19,9 +19,9 @@ class Mutation(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, product_id):
- errors = []
product = cls.get_node_or_error(
- info, product_id, errors, 'product_id', product_types.Product)
+ info, product_id, field='product_id',
+ only_type=product_types.Product)
return Mutation(name=product.name)
@@ -115,8 +115,6 @@ def test_user_error_id_of_different_type(product, schema_context):
def test_get_node_or_error_returns_null_for_empty_id():
- errors = []
info = Mock()
- response = Mutation.get_node_or_error(info, '', errors, '')
- assert not errors
+ response = Mutation.get_node_or_error(info, '', field='')
assert response is None
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 984785b909..2b658aed13 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -1059,7 +1059,8 @@ def test_checkout_shipping_method_update(
checkout.refresh_from_db()
assert checkout.shipping_method == shipping_method
mock_clean_shipping.assert_called_once_with(
- checkout, shipping_method, [], ANY, ANY, remove=False)
+ checkout=checkout, method=shipping_method, discounts=ANY, taxes=ANY,
+ remove=False)
def test_query_checkout_line(cart_with_item, user_api_client):
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index a7e0a685ab..e92fad3f39 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -7,11 +7,11 @@ from django.core.exceptions import ValidationError
from saleor.core.utils.taxes import ZERO_TAXED_MONEY
from saleor.graphql.core.enums import ReportingPeriod
-from saleor.graphql.order.enums import OrderEventsEmailsEnum, OrderStatusFilter
+from saleor.graphql.order.enums import OrderEventsEmailsEnum
from saleor.graphql.order.mutations.orders import (
clean_order_cancel, clean_order_capture, clean_refund_payment,
clean_void_payment)
-from saleor.graphql.order.utils import can_finalize_draft_order
+from saleor.graphql.order.utils import validate_draft_order
from saleor.graphql.payment.types import PaymentChargeStatusEnum
from saleor.order import OrderEvents, OrderEventsEmails, OrderStatus
from saleor.order.models import Order, OrderEvent
@@ -459,8 +459,8 @@ def test_can_finalize_order_no_order_lines(
def test_can_finalize_draft_order(order_with_lines):
- errors = can_finalize_draft_order(order_with_lines, [])
- assert not errors
+ # should not raise any errors
+ validate_draft_order(order_with_lines)
def test_can_finalize_draft_order_wrong_shipping(order_with_lines):
@@ -469,14 +469,17 @@ def test_can_finalize_draft_order_wrong_shipping(order_with_lines):
shipping_zone.countries = ['DE']
shipping_zone.save()
assert order.shipping_address.country.code not in shipping_zone.countries
- errors = can_finalize_draft_order(order, [])
+ with pytest.raises(ValidationError) as e:
+ validate_draft_order(order)
msg = 'Shipping method is not valid for chosen shipping address'
- assert errors[0].message == msg
+ assert e.value.error_dict['shipping'][0].message == msg
def test_can_finalize_draft_order_no_order_lines(order):
- errors = can_finalize_draft_order(order, [])
- assert errors[0].message == 'Could not create order without any products.'
+ with pytest.raises(ValidationError) as e:
+ validate_draft_order(order)
+ msg = 'Could not create order without any products.'
+ assert e.value.error_dict['lines'][0].message == msg
def test_can_finalize_draft_order_non_existing_variant(order_with_lines):
@@ -487,10 +490,10 @@ def test_can_finalize_draft_order_non_existing_variant(order_with_lines):
line.refresh_from_db()
assert line.variant is None
- errors = can_finalize_draft_order(order, [])
- assert (
- errors[0].message ==
- 'Could not create orders with non-existing products.')
+ with pytest.raises(ValidationError) as e:
+ validate_draft_order(order)
+ msg = 'Could not create orders with non-existing products.'
+ assert e.value.error_dict['lines'][0].message == msg
def test_draft_order_complete(
@@ -1212,7 +1215,6 @@ def test_clean_order_void_payment():
payment.is_active = False
with pytest.raises(ValidationError) as e:
clean_void_payment(payment)
-
msg = 'Only pre-authorized payments can be voided'
assert e.value.error_dict['payment'][0].message == msg
@@ -1223,7 +1225,6 @@ def test_clean_order_refund_payment():
amount = Mock(spec='string')
with pytest.raises(ValidationError) as e:
clean_refund_payment(payment, amount)
-
msg = 'Manual payments can not be refunded.'
assert e.value.error_dict['payment'][0].message == msg
@@ -1232,7 +1233,6 @@ def test_clean_order_capture():
amount = Mock(spec='string')
with pytest.raises(ValidationError) as e:
clean_order_capture(None, amount)
-
msg = 'There\'s no payment associated with the order.'
assert e.value.error_dict['payment'][0].message == msg
@@ -1246,7 +1246,6 @@ def test_clean_order_cancel(order):
with pytest.raises(ValidationError) as e:
clean_order_cancel(order)
-
msg = 'This order can\'t be canceled.'
assert e.value.error_dict['order'][0].message == msg
@@ -1423,8 +1422,6 @@ def test_order_by_token_query(api_client, order):
}
"""
order_id = graphene.Node.to_global_id('Order', order.id)
-
response = api_client.post_graphql(query, {'token': order.token})
content = get_graphql_content(response)
-
assert content['data']['orderByToken']['id'] == order_id