Skip to content

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

Adjust tests

Marcin Gębalaae296d7229ea
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index ad77235d53..a2dafcb02b 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -893,24 +893,19 @@ def is_fully_paid(cart: Cart, taxes, discounts):
def clean_checkout(cart: Cart, taxes, discounts):
"""Check if checkout can be completed."""
- errors = {}
-
if cart.is_shipping_required():
if not cart.shipping_method:
- errors.append('Shipping method is not set')
+ raise ValidationError('Shipping method is not set')
if not cart.shipping_address:
- errors.append('Shipping address is not set')
+ raise ValidationError('Shipping address is not set')
if not is_valid_shipping_method(cart, taxes, discounts):
- errors.append(
+ raise ValidationError(
'Shipping method is not valid for your shipping address')
if not cart.billing_address:
- errors.append('Billing address is not set')
+ raise ValidationError('Billing address is not set')
if not is_fully_paid(cart, taxes, discounts):
- errors.append(
+ raise ValidationError(
'Provided payment methods can not cover the checkout\'s total '
'amount')
-
- if errors:
- raise ValidationError(errors)
diff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.py
index d7e2eb729c..606c2ccf9a 100644
--- a/saleor/graphql/account/mutations.py
+++ b/saleor/graphql/account/mutations.py
@@ -269,10 +269,7 @@ class StaffUpdate(StaffCreate):
model = models.User
@classmethod
- def clean_is_active(cls, is_active, instance, user, errors):
- if is_active is None:
- return errors
-
+ def clean_is_active(cls, is_active, instance, user):
if not is_active:
if user == instance:
raise ValidationError({
@@ -280,14 +277,13 @@ class StaffUpdate(StaffCreate):
elif instance.is_superuser:
raise ValidationError({
'is_active': 'Cannot deactivate superuser\'s account.'})
- return errors
@classmethod
def clean_input(cls, info, instance, input, errors):
cleaned_input = super().clean_input(info, instance, input, errors)
- cls.clean_is_active(
- cleaned_input.get('is_active'), instance, info.context.user,
- errors)
+ is_active = cleaned_input.get('is_active')
+ if is_active is not None:
+ cls.clean_is_active(is_active, instance, info.context.user)
return cleaned_input
@@ -376,6 +372,7 @@ class PasswordReset(BaseMutation):
'email': 'User with this email doesn\'t exist'})
site = info.context.site
send_user_password_reset_email(user, site)
+ return PasswordReset()
class CustomerPasswordResetInput(graphene.InputObjectType):
@@ -536,6 +533,7 @@ class AddressSetDefault(BaseMutation):
class Meta:
description = 'Sets a default address for the given user.'
+ @classmethod
def user_is_allowed(cls, user, input):
return user.has_perm('account.manage_users')
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 1faf2d23e7..edbd08eb9d 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -28,10 +28,12 @@ from ..shipping.types import ShippingMethod
from .types import Checkout, CheckoutLine
-# FIXME Add tests for this function
def clean_shipping_method(
checkout, method, errors, discounts, taxes, country_code=None,
remove=True):
+ # FIXME Add tests for this function
+ if not method:
+ return errors
if not checkout.is_shipping_required():
raise ValidationError('This checkout does not requires shipping.')
@@ -173,7 +175,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
add_variant_to_cart(instance, variant, quantity)
@classmethod
- def perform_mutation(cls, root, info, **data):
+ def perform_mutation(cls, root, info, input):
errors = []
user = info.context.user
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 90e12019c4..fd215b33ad 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -43,10 +43,10 @@ def validation_error_to_error_type(validation_error: ValidationError) -> list:
err_list = []
if hasattr(validation_error, 'error_dict'):
# convert field errors
- for field, field_errors in validation_error.error_dict.items():
+ for field, field_errors in validation_error.message_dict.items():
for err in field_errors:
field = None if field == NON_FIELD_ERRORS else snake_to_camel_case(field)
- err_list.append(Error(field=field, message=err.message))
+ err_list.append(Error(field=field, message=err))
else:
# convert non-field errors
for err in validation_error.error_list:
@@ -402,6 +402,18 @@ class BaseBulkMutation(BaseMutation):
"""
return True
+ @classmethod
+ def mutate(cls, root, info, **data):
+ if not cls.user_is_allowed(info.context.user, data):
+ raise PermissionDenied()
+
+ count, errors = cls.perform_mutation(root, info, **data)
+ if errors:
+ errors = validation_error_to_error_type(errors)
+ return cls(errors=errors, count=count)
+ else:
+ return cls(count=count)
+
class ModelBulkDeleteMutation(BaseBulkMutation):
class Meta:
@@ -416,24 +428,34 @@ class ModelBulkDeleteMutation(BaseBulkMutation):
"""
@classmethod
- def mutate(cls, root, info, ids):
+ def perform_mutation(cls, root, info, ids):
"""Perform a mutation that deletes a list of model instances."""
- if not cls.user_is_allowed(info.context.user, ids):
- raise PermissionDenied()
-
- count, errors = 0, []
+ count, errors = 0, {}
model_type = registry.get_type_for_model(cls._meta.model)
instances = cls.get_nodes_or_error(ids, errors, 'id', model_type)
- for instance in instances:
+ for instance, node_id in zip(instances, ids):
instance_errors = []
- cls.clean_instance(info, instance, instance_errors)
+
+ # catch individual validation errors to raise them later as
+ # a single error
+ try:
+ cls.clean_instance(info, instance, [])
+ except ValidationError as e:
+ msg = '. '.join(e.messages)
+ instance_errors.append(msg)
if not instance_errors:
instance.delete()
count += 1
- errors.extend(instance_errors)
+ else:
+ instance_errors_msg = '. '.join(instance_errors)
+ ValidationError({
+ node_id: instance_errors_msg}).update_error_dict(errors)
+
+ if errors:
+ errors = ValidationError(errors)
- return cls(count=count, errors=errors)
+ return count, errors
class CreateToken(ObtainJSONWebToken):
diff --git a/saleor/graphql/menu/mutations.py b/saleor/graphql/menu/mutations.py
index 0ccb1ecfcd..989c5bec86 100644
--- a/saleor/graphql/menu/mutations.py
+++ b/saleor/graphql/menu/mutations.py
@@ -215,6 +215,7 @@ class AssignNavigation(BaseMutation):
class Meta:
description = 'Assigns storefront\'s navigation menus.'
+ @classmethod
def user_is_allowed(cls, instance, input):
return instance.has_perms([
'menu.manage_menus', 'site.manage_settings'])
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index f668abc973..f3c8736172 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -215,11 +215,10 @@ class DraftOrderComplete(BaseMutation):
class DraftOrderLinesCreate(BaseMutation):
- order = graphene.Field(
- graphene.NonNull(Order), description='A related draft order.')
+ order = graphene.Field(Order, description='A related draft order.')
order_lines = graphene.List(
graphene.NonNull(OrderLine),
- description='List of newly added order lines.', required=True)
+ description='List of newly added order lines.')
class Arguments:
id = graphene.ID(
@@ -238,8 +237,7 @@ class DraftOrderLinesCreate(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, [], 'id', Order)
if order.status != OrderStatus.DRAFT:
raise ValidationError({'id': 'Only draft orders can be edited.'})
@@ -247,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, errors, 'variant_id', ProductVariant)
+ info, variant_id, [], 'variant_id', ProductVariant)
quantity = input_line['quantity']
if quantity > 0:
if variant:
@@ -255,12 +253,12 @@ class DraftOrderLinesCreate(BaseMutation):
order, variant, quantity, allow_overselling=True)
lines.append(line)
else:
- ValidationError({
- 'quantity': 'Ensure this value is greater than or equal to 1.'}).update_error_dict(errors)
+ raise ValidationError({
+ 'quantity':
+ 'Ensure this value is greater than or equal to 1.'})
recalculate_order(order)
- return DraftOrderLinesCreate(
- order=order, order_lines=lines, errors=errors)
+ return DraftOrderLinesCreate(order=order, order_lines=lines)
class DraftOrderLineDelete(BaseMutation):
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 2883a6ddac..f5ac610837 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -68,7 +68,6 @@ class FulfillmentCreate(BaseMutation):
@classmethod
def clean_lines(cls, order_lines, quantities, errors):
- errors = {}
for order_line, quantity in zip(order_lines, quantities):
if quantity > order_line.quantity_unfulfilled:
msg = npgettext_lazy(
@@ -78,12 +77,7 @@ class FulfillmentCreate(BaseMutation):
number='quantity') % {
'quantity': order_line.quantity_unfulfilled,
'order_line': order_line}
- ValidationError({
- 'order_line_id': msg}).update_error_dict(errors)
- ValidationError(msg).update_error_dict(errors)
- if errors:
- raise ValidationError(errors)
- return errors
+ raise ValidationError({'order_line_id': msg})
@classmethod
def clean_input(cls, input, errors):
@@ -207,7 +201,7 @@ class FulfillmentCancel(BaseMutation):
return user.has_perm('order.manage_orders')
@classmethod
- def perform_mutatation(cls, root, info, id, input):
+ def perform_mutation(cls, root, info, id, input):
restock = input.get('restock')
fulfillment = cls.get_node_or_error(info, id, [], 'id', Fulfillment)
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 66405991ee..44c5e30ee6 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -35,8 +35,9 @@ class AttributeUpdateInput(graphene.InputObjectType):
class AttributeMixin:
+
@classmethod
- def check_unique_values(cls, values_input, attribute, errors):
+ def check_unique_values(cls, values_input, attribute):
# Check values uniqueness in case of creating new attribute.
existing_values = attribute.values.values_list('slug', flat=True)
for value_data in values_input:
@@ -74,10 +75,9 @@ class AttributeMixin:
if field == 'attribute':
continue
for msg in validation_errors.message_dict[field]:
- # FIXME :HANDLE this
- raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: msg})
- cls.check_unique_values(values_input, attribute, errors)
- return errors
+ raise ValidationError({
+ cls.ATTRIBUTE_VALUES_FIELD: msg})
+ cls.check_unique_values(values_input, attribute)
@classmethod
def clean_attribute(
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index d7a8d2025c..b5995e23e6 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -6,6 +6,7 @@ import graphene
import pytest
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
+from django.core.exceptions import ValidationError
from django.core.files import File
from django.shortcuts import reverse
@@ -742,14 +743,14 @@ def test_customer_delete(
def test_customer_delete_errors(customer_user, admin_user, staff_user):
info = Mock(context=Mock(user=admin_user))
- errors = []
- CustomerDelete.clean_instance(info, staff_user, errors)
- assert errors[0].field == 'id'
- assert errors[0].message == 'Cannot delete a staff account.'
+ with pytest.raises(ValidationError) as e:
+ CustomerDelete.clean_instance(info, staff_user, [])
- errors = []
- CustomerDelete.clean_instance(info, customer_user, errors)
- assert errors == []
+ 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, [])
@patch('saleor.dashboard.emails.send_set_password_staff_email.delay')
@@ -876,49 +877,47 @@ 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))
- errors = []
- UserDelete.clean_instance(info, staff_user, errors)
- assert errors[0].field == 'id'
- assert errors[0].message == 'You cannot delete your own account.'
+ with pytest.raises(ValidationError) as e:
+ 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))
- errors = []
- UserDelete.clean_instance(info, admin_user, errors)
- assert errors[0].field == 'id'
- assert errors[0].message == 'Cannot delete this account.'
+ with pytest.raises(ValidationError) as e:
+ UserDelete.clean_instance(info, admin_user, [])
+
+ msg = 'Cannot delete this account.'
+ assert e.value.error_dict['id'][0].message == msg
def test_staff_delete_errors(staff_user, customer_user, admin_user):
info = Mock(context=Mock(user=staff_user))
- errors = []
- StaffDelete.clean_instance(info, customer_user, errors)
- assert errors[0].field == 'id'
- assert errors[0].message == 'Cannot delete a non-staff user.'
+ with pytest.raises(ValidationError) as e:
+ 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))
- errors = []
- StaffDelete.clean_instance(info, staff_user, errors)
- assert not errors
+ StaffDelete.clean_instance(info, staff_user, [])
def test_staff_update_errors(staff_user, customer_user, admin_user):
- errors = []
- StaffUpdate.clean_is_active(None, customer_user, staff_user, errors)
- assert not errors
+ StaffUpdate.clean_is_active(None, customer_user, staff_user)
- errors = []
- StaffUpdate.clean_is_active(False, staff_user, staff_user, errors)
- assert errors[0].field == 'isActive'
- assert errors[0].message == 'Cannot deactivate your own account.'
+ with pytest.raises(ValidationError) as e:
+ StaffUpdate.clean_is_active(False, staff_user, staff_user)
+ msg = 'Cannot deactivate your own account.'
+ assert e.value.error_dict['is_active'][0].message == msg
- errors = []
- StaffUpdate.clean_is_active(False, admin_user, staff_user, errors)
- assert errors[0].field == 'isActive'
- assert errors[0].message == 'Cannot deactivate superuser\'s account.'
+ with pytest.raises(ValidationError) as e:
+ StaffUpdate.clean_is_active(False, admin_user, staff_user)
+ msg = 'Cannot deactivate superuser\'s account.'
+ assert e.value.error_dict['is_active'][0].message == msg
- errors = []
- StaffUpdate.clean_is_active(False, customer_user, staff_user, errors)
- assert not errors
+ # shuold not raise any errors
+ StaffUpdate.clean_is_active(False, customer_user, staff_user)
def test_set_password(user_api_client, customer_user):
@@ -976,7 +975,7 @@ def test_password_reset_email(
query, variables, permissions=[permission_manage_users])
content = get_graphql_content(response)
data = content['data']['passwordReset']
- assert data is None
+ assert data == {'errors': []}
assert send_password_reset_mock.call_count == 1
args, kwargs = send_password_reset_mock.call_args
call_context = args[0]
diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.py
index 449417fa39..cceec3f5f8 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -467,7 +467,8 @@ def test_create_attribute_value_not_unique_name(
content = get_graphql_content(response)
data = content['data']['attributeValueCreate']
assert data['errors']
- assert data['errors'][0]['field'] == 'All'
+ assert data['errors'][0]['message']
+ assert not data['errors'][0]['field']
UPDATE_ATTRIBUTE_VALUE_QUERY = """
@@ -523,7 +524,8 @@ def test_update_attribute_value_name_not_unique(
content = get_graphql_content(response)
data = content['data']['attributeValueUpdate']
assert data['errors']
- assert data['errors'][0]['field'] == 'All'
+ assert data['errors'][0]['message']
+ assert not data['errors'][0]['field']
def test_update_same_attribute_value(
diff --git a/tests/api/test_base_mutation.py b/tests/api/test_base_mutation.py
index c44b8f444e..50c3afd54b 100644
--- a/tests/api/test_base_mutation.py
+++ b/tests/api/test_base_mutation.py
@@ -18,12 +18,10 @@ class Mutation(BaseMutation):
description = 'Base mutation'
@classmethod
- def mutate(cls, root, info, product_id):
+ def perform_mutation(cls, root, info, product_id):
errors = []
product = cls.get_node_or_error(
info, product_id, errors, 'product_id', product_types.Product)
- if errors:
- return Mutation(errors=errors)
return Mutation(name=product.name)
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 35bd16df8f..d7aa61816f 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -1,6 +1,7 @@
import uuid
from unittest.mock import ANY, patch
+from django.core.exceptions import ValidationError
import graphene
import pytest
@@ -1155,18 +1156,20 @@ def test_ready_to_place_order(
payment.currency = total.gross.currency
payment.checkout = checkout
payment.save()
- ready, error = clean_checkout(checkout, None, None)
- assert ready
- assert not error
+ # Shouldn't raise any errors
+ clean_checkout(checkout, None, None)
def test_ready_to_place_order_no_shipping_method(cart_with_item, address):
checkout = cart_with_item
checkout.shipping_address = address
checkout.save()
- ready, error = clean_checkout(checkout, None, None)
- assert not ready
- assert error == 'Shipping method is not set'
+
+ with pytest.raises(ValidationError) as e:
+ clean_checkout(checkout, None, None)
+
+ msg = 'Shipping method is not set'
+ assert e.value.error_list[0].message == msg
def test_ready_to_place_order_no_shipping_address(
@@ -1174,9 +1177,11 @@ def test_ready_to_place_order_no_shipping_address(
checkout = cart_with_item
checkout.shipping_method = shipping_method
checkout.save()
- ready, error = clean_checkout(checkout, None, None)
- assert not ready
- assert error == 'Shipping address is not set'
+
+ with pytest.raises(ValidationError) as e:
+ clean_checkout(checkout, None, None)
+ msg = 'Shipping address is not set'
+ assert e.value.error_list[0].message == msg
def test_ready_to_place_order_invalid_shipping_method(
@@ -1186,9 +1191,12 @@ def test_ready_to_place_order_invalid_shipping_method(
shipping_method = shipping_zone_without_countries.shipping_methods.first()
checkout.shipping_method = shipping_method
checkout.save()
- ready, error = clean_checkout(checkout, None, None)
- assert not ready
- assert error == 'Shipping method is not valid for your shipping address'
+
+ with pytest.raises(ValidationError) as e:
+ clean_checkout(checkout, None, None)
+
+ msg = 'Shipping method is not valid for your shipping address'
+ assert e.value.error_list[0].message == msg
def test_ready_to_place_order_no_billing_address(
@@ -1197,9 +1205,11 @@ def test_ready_to_place_order_no_billing_address(
checkout.shipping_address = address
checkout.shipping_method = shipping_method
checkout.save()
- ready, error = clean_checkout(checkout, None, None)
- assert not ready
- assert error == 'Billing address is not set'
+
+ with pytest.raises(ValidationError) as e:
+ clean_checkout(checkout, None, None)
+ msg = 'Billing address is not set'
+ assert e.value.error_list[0].message == msg
def test_ready_to_place_order_no_payment(
@@ -1209,11 +1219,12 @@ def test_ready_to_place_order_no_payment(
checkout.shipping_method = shipping_method
checkout.billing_address = address
checkout.save()
- ready, error = clean_checkout(checkout, None, None)
- assert not ready
- assert error == (
- 'Provided payment methods can not '
- 'cover the checkout\'s total amount')
+
+ with pytest.raises(ValidationError) as e:
+ clean_checkout(checkout, None, None)
+
+ msg = 'Provided payment methods can not cover the checkout\'s total amount'
+ assert e.value.error_list[0].message == msg
def test_is_fully_paid(cart_with_item, payment_dummy):
diff --git a/tests/api/test_fulfillment.py b/tests/api/test_fulfillment.py
index 31921a069f..15475d2506 100644
--- a/tests/api/test_fulfillment.py
+++ b/tests/api/test_fulfillment.py
@@ -109,13 +109,13 @@ def test_create_fulfillment_with_emtpy_quantity(
@pytest.mark.parametrize(
- 'quantity, error_message',
+ 'quantity, error_message, error_field',
(
- (0, 'Total quantity must be larger than 0.'),
- (100, 'Only 3 items remaining to fulfill.')))
+ (0, 'Total quantity must be larger than 0.', 'lines'),
+ (100, 'Only 3 items remaining to fulfill:', 'orderLineId')))
def test_create_fulfillment_not_sufficient_quantity(
staff_api_client, order_with_lines, staff_user, quantity,
- error_message, permission_manage_orders):
+ error_message, error_field, permission_manage_orders):
query = CREATE_FULFILLMENT_QUERY
order_line = order_with_lines.lines.first()
order_line_id = graphene.Node.to_global_id('OrderLine', order_line.id)
@@ -127,8 +127,8 @@ def test_create_fulfillment_not_sufficient_quantity(
content = get_graphql_content(response)
data = content['data']['orderFulfillmentCreate']
assert data['errors']
- assert data['errors'][0]['field'] in (str(order_line), 'lines')
- assert data['errors'][0]['message'] == error_message
+ assert data['errors'][0]['field'] == error_field
+ assert error_message in data['errors'][0]['message']
def test_create_fulfillment_with_invalid_input(
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index a9b8a8dc7c..a7e0a685ab 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -3,6 +3,7 @@ from unittest.mock import MagicMock, Mock, patch
import graphene
import pytest
+from django.core.exceptions import ValidationError
from saleor.core.utils.taxes import ZERO_TAXED_MONEY
from saleor.graphql.core.enums import ReportingPeriod
@@ -1121,24 +1122,30 @@ def test_order_mark_as_paid(
assert event_order_paid.user == staff_user
+ORDER_VOID = """
+ mutation voidOrder($id: ID!) {
+ orderVoid(id: $id) {
+ order {
+ paymentStatus
+ paymentStatusDisplay
+ }
+ errors {
+ field
+ message
+ }
+ }
+ }
+"""
+
+
def test_order_void(
staff_api_client, permission_manage_orders, payment_txn_preauth,
staff_user):
order = payment_txn_preauth.order
- query = """
- mutation voidOrder($id: ID!) {
- orderVoid(id: $id) {
- order {
- paymentStatus
- paymentStatusDisplay
- }
- }
- }
- """
order_id = graphene.Node.to_global_id('Order', order.id)
variables = {'id': order_id}
response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders])
+ ORDER_VOID, variables, permissions=[permission_manage_orders])
content = get_graphql_content(response)
data = content['data']['orderVoid']['order']
assert data['paymentStatus'] == PaymentChargeStatusEnum.NOT_CHARGED.name
@@ -1150,6 +1157,20 @@ def test_order_void(
assert event_payment_voided.user == staff_user
+def test_order_void_payment_error(staff_api_client, permission_manage_orders, payment_txn_preauth):
+ msg = 'error has happened'
+ order = payment_txn_preauth.order
+ order_id = graphene.Node.to_global_id('Order', order.id)
+ variables = {'id': order_id}
+ with patch('saleor.graphql.order.mutations.orders.gateway_void', side_effect=ValueError(msg)):
+ response = staff_api_client.post_graphql(
+ ORDER_VOID, variables, permissions=[permission_manage_orders])
+ content = get_graphql_content(response)
+ errors = content['data']['orderVoid']['errors']
+ assert errors[0]['field'] == 'payment'
+ assert errors[0]['message'] == msg
+
+
def test_order_refund(
staff_api_client, permission_manage_orders,
payment_txn_captured):
@@ -1189,45 +1210,45 @@ def test_order_refund(
def test_clean_order_void_payment():
payment = MagicMock(spec=Payment)
payment.is_active = False
- errors = clean_void_payment(payment, [])
- assert errors[0].field == 'payment'
- assert errors[0].message == 'Only pre-authorized payments can be voided'
+ with pytest.raises(ValidationError) as e:
+ clean_void_payment(payment)
- payment.is_active = True
- error_msg = 'error has happened.'
- with patch('saleor.graphql.order.mutations.orders.gateway_void',
- side_effect=ValueError(error_msg)):
- errors = clean_void_payment(payment, [])
- assert errors[0].field == 'payment'
- assert errors[0].message == error_msg
+ msg = 'Only pre-authorized payments can be voided'
+ assert e.value.error_dict['payment'][0].message == msg
def test_clean_order_refund_payment():
payment = MagicMock(spec=Payment)
payment.gateway = CustomPaymentChoices.MANUAL
amount = Mock(spec='string')
- errors = clean_refund_payment(payment, amount, [])
- assert errors[0].field == 'payment'
- assert errors[0].message == 'Manual payments can not be refunded.'
+ 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
def test_clean_order_capture():
amount = Mock(spec='string')
- errors = clean_order_capture(None, amount, [])
- assert errors[0].field == 'payment'
- assert errors[0].message == (
- 'There\'s no payment associated with the order.')
+ 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
def test_clean_order_cancel(order):
- assert clean_order_cancel(order, []) == []
+ # Shouldn't raise any errors
+ clean_order_cancel(order)
order.status = OrderStatus.DRAFT
order.save()
- errors = clean_order_cancel(order, [])
- assert errors[0].field == 'order'
- assert errors[0].message == 'This order can\'t be canceled.'
+ 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
ORDER_UPDATE_SHIPPING_QUERY = """
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index e4596510f9..6116cc35fb 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -715,8 +715,8 @@ def test_product_create_without_product_type(
query = """
mutation createProduct($categoryId: ID!) {
productCreate(input: {
- name: "Product",
- price: "2.5",
+ name: "Product",
+ price: "2.5",
productType: "",
category: $categoryId}) {
product {
@@ -1166,7 +1166,7 @@ def test_product_type_update_mutation(
assert data['name'] == product_type_name
assert data['hasVariants'] == has_variants
assert data['isShippingRequired'] == require_shipping
- assert len(data['productAttributes']) == 0
+ assert not data['productAttributes']
assert len(data['variantAttributes']) == (
variant_attributes.count())