示例#1
0
    def _calculate_single_discount(self, discount_name, products_quantity,
                                   product_price):
        """Calculates a discount for a single offer

        :param discount_name: name of a discount (one of the supported in DCN_TYP_REGEXPS mapping)
        :param products_quantity: quantity of products
        :param product_price: price of a single product
        :return: calculated discount
        :rtype: Decimal
        :raises ValueError: if a discount_name is not supported (not in DCN_TYP_REGEXPS)
        """

        calculated_discount = Decimal("0.00")
        for discount_type, regex in self.DCN_TYP_REGEXPS.items():
            discount_name_match = re.match(regex, discount_name)
            if discount_name_match:
                x = int(discount_name_match.group(1))
                try:
                    y = int(discount_name_match.group(2))
                except IndexError:
                    calculated_discount = x_percent_calculator(
                        x, products_quantity, product_price)
                else:
                    if discount_type == "X_FOR_Y":
                        calculated_discount = x_for_y_calculator(
                            x, y, products_quantity, product_price)
                    elif discount_type == "X_GET_Y":
                        calculated_discount = x_get_y_calculator(
                            x, y, products_quantity, product_price)
                    else:
                        raise ValueError(
                            f"Unsupported discount type: {discount_type}")

        return calculated_discount
 def test_two_for_three_2(self):
     with pytest.raises(ValueError):
         x_for_y_calculator(2, 3, 2, 1.00)
 def test_three_for_one_4(self):
     assert x_for_y_calculator(3, 1, 4, 1.22) == Decimal("2.44")
 def test_three_for_two_4(self):
     assert x_for_y_calculator(3, 2, 4, 1) == Decimal("1.00")
 def test_two_for_one_5(self):
     assert x_for_y_calculator(2, 1, 5, 1.00) == Decimal("2.00")