Skip to content

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

Attribute association utilities now validate the values

NyanKiyoshib6a23cac3e84
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 36b7cf824d..40bc7b38aa 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -485,7 +485,7 @@ class AttributeAssignmentMixin:
"""
@classmethod
- def _get_attribute_nodes(
+ def _resolve_attribute_nodes(
cls,
qs: QuerySet,
*,
@@ -596,7 +596,9 @@ class AttributeAssignmentMixin:
"""Resolve and prepare the input for further checks.
:param raw_input: The user's attributes input.
- :param attributes_qs: A queryset of attributes, must prefetch attribute values.
+ :param attributes_qs:
+ A queryset of attributes, the attribute values must be prefetched.
+ Prefetch is needed by ``_pre_save_values`` during save.
:param is_variant: Whether the input is for a variant or a product.
:raises ValidationError: contain the message.
@@ -624,7 +626,7 @@ class AttributeAssignmentMixin:
else:
raise ValidationError("You must whether supply an ID or a slug")
- attributes = cls._get_attribute_nodes(
+ attributes = cls._resolve_attribute_nodes(
attributes_qs, global_ids=global_ids, pks=pks.keys(), slugs=slugs.keys()
)
cleaned_input = []
@@ -745,7 +747,8 @@ class ProductCreate(ModelMutation):
# Prefetches needed by AttributeAssignmentMixin and
# associate_attribute_values_to_instance
qs = cls.Meta.model.objects.prefetch_related(
- "product_type__product_attributes", "product_type__attributeproduct"
+ "product_type__product_attributes__values",
+ "product_type__attributeproduct",
)
return cls.get_node_or_error(info, object_id, only_type="Product", qs=qs)
@@ -972,7 +975,7 @@ class ProductVariantCreate(ModelMutation):
# Prefetches needed by AttributeAssignmentMixin and
# associate_attribute_values_to_instance
qs = cls.Meta.model.objects.prefetch_related(
- "product__product_type__variant_attributes",
+ "product__product_type__variant_attributes__values",
"product__product_type__attributevariant",
)
return cls.get_node_or_error(
@@ -984,7 +987,6 @@ class ProductVariantCreate(ModelMutation):
@classmethod
@transaction.atomic()
def save(cls, info, instance, cleaned_input):
- # FIXME: get_node should prefetch
instance.save()
# Recalculate the "minimal variant price" for the parent product
update_product_minimal_variant_price_task.delay(instance.product_id)
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 7a7bed9e87..5269016186 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -532,7 +532,23 @@ class BaseAttributeQuerySet(models.QuerySet):
return self.get_public_attributes()
-class AssignedProductAttribute(models.Model):
+class BaseAssignedAttribute(models.Model):
+ assignment = None
+ values = models.ManyToManyField("AttributeValue")
+
+ class Meta:
+ abstract = True
+
+ @property
+ def attribute(self):
+ return self.assignment.attribute
+
+ @property
+ def attribute_pk(self):
+ return self.assignment.attribute_id
+
+
+class AssignedProductAttribute(BaseAssignedAttribute):
"""Associate a product type attribute and selected values to a given product."""
product = models.ForeignKey(
@@ -541,18 +557,12 @@ class AssignedProductAttribute(models.Model):
assignment = models.ForeignKey(
"AttributeProduct", on_delete=models.CASCADE, related_name="productassignments"
)
- values = models.ManyToManyField("AttributeValue")
class Meta:
unique_together = (("product", "assignment"),)
- @property
- def attribute(self):
- """Return the attribute assigned to this relation."""
- return self.assignment.attribute
-
-class AssignedVariantAttribute(models.Model):
+class AssignedVariantAttribute(BaseAssignedAttribute):
"""Associate a product type attribute and selected values to a given variant."""
variant = models.ForeignKey(
@@ -561,19 +571,10 @@ class AssignedVariantAttribute(models.Model):
assignment = models.ForeignKey(
"AttributeVariant", on_delete=models.CASCADE, related_name="variantassignments"
)
- values = models.ManyToManyField("AttributeValue")
class Meta:
unique_together = (("variant", "assignment"),)
- @property
- def attribute(self):
- return self.assignment.attribute
-
- @property
- def attribute_pk(self):
- return self.assignment.attribute_id
-
class AssociatedAttributeQuerySet(BaseAttributeQuerySet):
def get_public_attributes(self):
diff --git a/saleor/product/utils/attributes.py b/saleor/product/utils/attributes.py
index f6d2084be3..c162fb1bdb 100644
--- a/saleor/product/utils/attributes.py
+++ b/saleor/product/utils/attributes.py
@@ -1,4 +1,4 @@
-from typing import Union
+from typing import Set, Union
from ..models import (
AssignedProductAttribute,
@@ -50,6 +50,17 @@ def _associate_attribute_to_instance(
return assignment
+def validate_attribute_owns_values(attribute: Attribute, value_ids: Set[int]) -> None:
+ """Check given value IDs are belonging to the given attribute.
+
+ :raise: AssertionError
+ """
+ attribute_actual_value_ids = set(attribute.values.values_list("pk", flat=True))
+ found_associated_ids = attribute_actual_value_ids & value_ids
+ if found_associated_ids != value_ids:
+ raise AssertionError("Some values are not from the provided attribute.")
+
+
def associate_attribute_values_to_instance(
instance: Union[Product, ProductVariant],
attribute: Attribute,
@@ -61,6 +72,12 @@ def associate_attribute_values_to_instance(
attribute association. Meaning any values already assigned or concurrently
assigned will be overridden by this call.
"""
+ values_ids = {value.pk for value in values}
+
+ # Ensure the values are actually form the given attribute
+ validate_attribute_owns_values(attribute, values_ids)
+
+ # Associate the attribute and the passed values
assignment = _associate_attribute_to_instance(instance, attribute.pk)
assignment.values.set(values)
return assignment
diff --git a/tests/test_product_attributes.py b/tests/test_product_attributes.py
index cca7f471f0..2eaaa054c4 100644
--- a/tests/test_product_attributes.py
+++ b/tests/test_product_attributes.py
@@ -4,13 +4,7 @@ import pytest
from prices import Money
from saleor.product import AttributeInputType
-from saleor.product.models import (
- Attribute,
- AttributeValue,
- Product,
- ProductType,
- ProductVariant,
-)
+from saleor.product.models import AttributeValue, Product, ProductType, ProductVariant
from saleor.product.tasks import _update_variants_names
from saleor.product.utils.attributes import (
associate_attribute_values_to_instance,
@@ -101,12 +95,44 @@ def test_update_variants_changed_does_nothing_with_no_attributes():
assert _update_variants_names(product_type, saved_attributes) is None
-def test_associate_attribute_to_non_product_instance():
+def test_associate_attribute_to_non_product_instance(color_attribute):
instance = ProductType()
- attribute = Attribute()
- value = AttributeValue()
+ attribute = color_attribute
+ value = color_attribute.values.first()
with pytest.raises(AssertionError) as exc:
- associate_attribute_values_to_instance(instance, attribute, value)
+ associate_attribute_values_to_instance(instance, attribute, value) # noqa
assert exc.value.args == ("ProductType is unsupported",)
+
+
+def test_associate_attribute_to_product_instance_from_different_attribute(
+ product, color_attribute, size_attribute
+):
+ """Ensure an assertion error is raised when one tries to associate attribute values
+ to an object that don't belong to the supplied attribute.
+ """
+ instance = product
+ attribute = color_attribute
+ value = size_attribute.values.first()
+
+ with pytest.raises(AssertionError) as exc:
+ associate_attribute_values_to_instance(instance, attribute, value)
+
+ assert exc.value.args == ("Some values are not from the provided attribute.",)
+
+
+def test_associate_attribute_to_product_instance_without_values(product):
+ """Ensure clearing the values from a product is properly working."""
+ old_assignment = product.attributes.first()
+ assert old_assignment is not None, "The product doesn't have attribute-values"
+ assert old_assignment.values.count() == 1
+
+ attribute = old_assignment.attribute
+
+ # Clear the values
+ new_assignment = associate_attribute_values_to_instance(product, attribute)
+
+ # Ensure the values were cleared and no new assignment entry was created
+ assert new_assignment.pk == old_assignment.pk
+ assert new_assignment.values.count() == 0