Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
simplify logic of manager. Add tests for default values and calling plugin logic
Maciej Korycinski0c43bf16fd1f
diff --git a/saleor/core/extensions/checks.py b/saleor/core/extensions/checks.pyindex 9b77f10efe..3b5cde6b87 100644--- a/saleor/core/extensions/checks.py+++ b/saleor/core/extensions/checks.py@@ -11,9 +11,10 @@ def check_extensions(app_configs, **kwargs):errors = []check_manager(errors)- plugins = settings.PLUGINS- if plugins:- check_plugins(errors, plugins)+ plugins = settings.PLUGINS or []++ for plugin_path in plugins:+ check_single_plugin(plugin_path, errors)return errors@@ -22,8 +23,7 @@ def check_manager(errors: List[Error]):if not hasattr(settings, "EXTENSIONS_MANAGER") or not settings.EXTENSIONS_MANAGER:errors.append(Error("Settings should contain EXTENSIONS_MANAGER env"))return- manager_path = settings.EXTENSIONS_MANAGER- manager_path, _, manager_name = manager_path.rpartition(".")+ manager_path, _, manager_name = settings.EXTENSIONS_MANAGER.rpartition(".")try:manager_module = importlib.import_module(manager_path)except ModuleNotFoundError:@@ -39,11 +39,6 @@ def check_manager(errors: List[Error]):)-def check_plugins(errors: List[Error], plugins: List[str]):- for plugin_path in plugins:- check_single_plugin(plugin_path, errors)--def check_single_plugin(plugin_path: str, errors: List[Error]):if not plugin_path:errors.append(Error("Wrong plugin_path %s" % plugin_path))diff --git a/saleor/core/extensions/manager.py b/saleor/core/extensions/manager.pyindex 7275878cc7..4751115936 100644--- a/saleor/core/extensions/manager.py+++ b/saleor/core/extensions/manager.py@@ -12,9 +12,10 @@ if TYPE_CHECKING:from ...product.models import Productfrom ...account.models import Addressfrom ...order.models import OrderLine, Order+ from .plugin import BasePlugin-class BaseManager:+class ExtensionsManager:"""Base manager for handling a plugins logic"""plugins = None@@ -27,17 +28,38 @@ class BaseManager:plugin_class = getattr(plugin_module, plugin_name)self.plugins.append(plugin_class())- def run_plugin_method(self, name: str, default_value: Any, *args, **kwargs):+ def __run_method_on_plugins(+ self, method_name: str, default_value: Any, *args, **kwargs+ ):+ """It takes all declared plugins and tries to run method with the given name on+ each plugin"""value = default_value- for p in self.plugins:- plugin_value = getattr(p, name, NotImplemented)(- *args, **kwargs, previous_value=value+ for plugin in self.plugins:+ value = self.__run_method_on_single_plugin(+ plugin, method_name, value, *args, **kwargs)- if plugin_value == NotImplemented:- continue- value = plugin_valuereturn value+ def __run_method_on_single_plugin(+ self,+ plugin: "BasePlugin",+ method_name: str,+ previous_value: Any,+ *args,+ **kwargs,+ ) -> Any:+ """Run method_name on plugin. Method will return value returned from plugin's+ method. If plugin doesn't have own implementation of expected method_name, it+ will return previous_value."""+ plugin_method = getattr(plugin, method_name, NotImplemented)+ if plugin_method == NotImplemented:+ return previous_value++ returned_value = plugin_method(*args, **kwargs, previous_value=previous_value)+ if returned_value == NotImplemented:+ return previous_value+ return returned_value+def calculate_checkout_total(self, checkout: "Checkout", discounts: List["DiscountInfo"]) -> TaxedMoney:@@ -45,7 +67,7 @@ class BaseManager:default_value = quantize_price(TaxedMoney(net=total, gross=total), total.currency)- return self.run_plugin_method(+ return self.__run_method_on_plugins("calculate_checkout_total", default_value, checkout, discounts)@@ -56,7 +78,7 @@ class BaseManager:default_value = quantize_price(TaxedMoney(net=subtotal, gross=subtotal), subtotal.currency)- return self.run_plugin_method(+ return self.__run_method_on_plugins("calculate_checkout_subtotal", default_value, checkout, discounts)@@ -66,7 +88,7 @@ class BaseManager:total = checkout.get_shipping_price()total = TaxedMoney(net=total, gross=total)default_value = quantize_price(total, total.currency)- return self.run_plugin_method(+ return self.__run_method_on_plugins("calculate_checkout_shipping", default_value, checkout, discounts)@@ -76,7 +98,9 @@ class BaseManager:TaxedMoney(net=shipping_price, gross=shipping_price),shipping_price.currency,)- return self.run_plugin_method("calculate_order_shipping", default_value, order)+ return self.__run_method_on_plugins(+ "calculate_order_shipping", default_value, order+ )def calculate_checkout_line_total(self, checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]@@ -85,29 +109,29 @@ class BaseManager:default_value = quantize_price(TaxedMoney(net=total, gross=total), total.currency)- return self.run_plugin_method(+ return self.__run_method_on_plugins("calculate_checkout_line_total", default_value, checkout_line, discounts)def calculate_order_line_unit(self, order_line: "OrderLine"):unit_price = order_line.unit_pricedefault_value = quantize_price(unit_price, unit_price.currency)- return self.run_plugin_method(+ return self.__run_method_on_plugins("calculate_order_line_unit", default_value, order_line)def get_tax_rate_type_choices(self) -> List[TaxType]:default_value = []- return self.run_plugin_method("get_tax_rate_type_choices", default_value)+ return self.__run_method_on_plugins("get_tax_rate_type_choices", default_value)def show_taxes_on_storefront(self) -> bool:default_value = False- return self.run_plugin_method("show_taxes_on_storefront", default_value)+ return self.__run_method_on_plugins("show_taxes_on_storefront", default_value)def taxes_are_enabled(self) -> bool:default_value = False- return self.run_plugin_method("taxes_are_enabled", default_value)+ return self.__run_method_on_plugins("taxes_are_enabled", default_value)def apply_taxes_to_product(self, product: "Product", price: Money, country: Country, **kwargs@@ -115,7 +139,7 @@ class BaseManager:default_value = quantize_price(TaxedMoney(net=price, gross=price), price.currency)- return self.run_plugin_method(+ return self.__run_method_on_plugins("apply_taxes_to_product", default_value, product, price, country, **kwargs)@@ -125,7 +149,7 @@ class BaseManager:default_value = quantize_price(TaxedMoney(net=price, gross=price), price.currency)- return self.run_plugin_method(+ return self.__run_method_on_plugins("apply_taxes_to_shipping", default_value, price, shipping_address)@@ -135,7 +159,7 @@ class BaseManager:default_value = quantize_price(TaxedMoneyRange(start=start, stop=stop), start.currency)- return self.run_plugin_method(+ return self.__run_method_on_plugins("apply_taxes_to_shipping_price_range", default_value, prices, country)@@ -143,13 +167,13 @@ class BaseManager:self, checkout: "Checkout", discounts: List["DiscountInfo"]):default_value = None- return self.run_plugin_method(+ return self.__run_method_on_plugins("preprocess_order_creation", default_value, checkout, discounts)def postprocess_order_creation(self, order: "Order"):default_value = None- return self.run_plugin_method(+ return self.__run_method_on_plugins("postprocess_order_creation", default_value, order)@@ -158,7 +182,7 @@ class BaseManager:self, obj: Union["Product", "ProductType"], tax_code: str):default_value = None- return self.run_plugin_method(+ return self.__run_method_on_plugins("assign_tax_code_to_object_meta", default_value, obj, tax_code)@@ -166,7 +190,7 @@ class BaseManager:self, obj: Union["Product", "ProductType"]) -> TaxType:default_value = TaxType(code="", description="")- return self.run_plugin_method(+ return self.__run_method_on_plugins("get_tax_code_from_object_meta", default_value, obj)@@ -174,7 +198,7 @@ class BaseManager:def get_extensions_manager(manager_path: str = settings.EXTENSIONS_MANAGER,plugins: List[str] = settings.PLUGINS,-) -> BaseManager:+) -> ExtensionsManager:manager_path, _, manager_name = manager_path.rpartition(".")manager_module = importlib.import_module(manager_path)manager_class = getattr(manager_module, manager_name, None)diff --git a/saleor/settings.py b/saleor/settings.pyindex bb262f8b87..becf9e452c 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -664,6 +664,6 @@ GRAPHENE = {"RELAY_CONNECTION_MAX_LIMIT": 100,}-EXTENSIONS_MANAGER = "saleor.core.extensions.manager.BaseManager"+EXTENSIONS_MANAGER = "saleor.core.extensions.manager.ExtensionsManager"PLUGINS = os.environ.get("PLUGINS", [])diff --git a/tests/extensions/test_manager.py b/tests/extensions/test_manager.pyindex 6d4e45d5a3..cad7ab0a33 100644--- a/tests/extensions/test_manager.py+++ b/tests/extensions/test_manager.py@@ -1,14 +1,217 @@-from saleor.core.extensions.manager import BaseManager, get_extensions_manager+import pytest+from django_countries.fields import Country+from prices import Money, TaxedMoney++from saleor.core.extensions.manager import ExtensionsManager, get_extensions_managerfrom saleor.core.extensions.plugin import BasePlugin+from saleor.core.taxes import TaxTypeclass TestPlugin(BasePlugin):""""""+ def calculate_checkout_total(self, checkout, discounts, previous_value):+ total = Money("1.0", currency=checkout.get_total().currency)+ return TaxedMoney(total, total)++ def calculate_checkout_subtotal(self, checkout, discounts, previous_value):+ subtotal = Money("1.0", currency=checkout.get_total().currency)+ return TaxedMoney(subtotal, subtotal)++ def calculate_checkout_shipping(self, checkout, discounts, previous_value):+ price = Money("1.0", currency=checkout.get_total().currency)+ return TaxedMoney(price, price)++ def calculate_order_shipping(self, order, previous_value):+ price = Money("1.0", currency=order.total.currency)+ return TaxedMoney(price, price)++ def calculate_checkout_line_total(self, checkout_line, discounts, previous_value):+ price = Money("1.0", currency=checkout_line.get_total().currency)+ return TaxedMoney(price, price)++ def calculate_order_line_unit(self, order_line, previous_value):+ currency = order_line.unit_price.currency+ price = Money("1.0", currency)+ return TaxedMoney(price, price)++ def get_tax_rate_type_choices(self, previous_value):+ return [TaxType(code="123", description="abc")]++ def show_taxes_on_storefront(self, previous_value: bool) -> bool:+ return True++ def taxes_are_enabled(self, previous_value: bool) -> bool:+ return True++ def apply_taxes_to_product(self, product, price, country, previous_value, **kwargs):+ price = Money("1.0", price.currency)+ return TaxedMoney(price, price)++ def apply_taxes_to_shipping(+ self, price, shipping_address, previous_value+ ) -> TaxedMoney:+ price = Money("1.0", price.currency)+ return TaxedMoney(price, price)+def test_get_extensions_manager():- manager_path = "saleor.core.extensions.manager.BaseManager"+ manager_path = "saleor.core.extensions.manager.ExtensionsManager"plugin_path = "tests.extensions.test_manager.TestPlugin"manager = get_extensions_manager(manager_path=manager_path, plugins=[plugin_path])- assert isinstance(manager, BaseManager)+ assert isinstance(manager, ExtensionsManager)assert len(manager.plugins) == 1+++ "plugins, total_amount",+ [(["tests.extensions.test_manager.TestPlugin"], "1.0"), ([], "15.0")],+)+def test_manager_calculates_checkout_total(+ checkout_with_item, discount_info, plugins, total_amount+):+ currency = checkout_with_item.get_total().currency+ expected_total = Money(total_amount, currency)+ manager = ExtensionsManager(plugins=plugins)+ taxed_total = manager.calculate_checkout_total(checkout_with_item, [discount_info])+ assert TaxedMoney(expected_total, expected_total) == taxed_total+++ "plugins, subtotal_amount",+ [(["tests.extensions.test_manager.TestPlugin"], "1.0"), ([], "15.0")],+)+def test_manager_calculates_checkout_subtotal(+ checkout_with_item, discount_info, plugins, subtotal_amount+):+ currency = checkout_with_item.get_total().currency+ expected_subtotal = Money(subtotal_amount, currency)+ taxed_subtotal = ExtensionsManager(plugins=plugins).calculate_checkout_subtotal(+ checkout_with_item, [discount_info]+ )+ assert TaxedMoney(expected_subtotal, expected_subtotal) == taxed_subtotal+++ "plugins, shipping_amount",+ [(["tests.extensions.test_manager.TestPlugin"], "1.0"), ([], "0.0")],+)+def test_manager_calculates_checkout_shipping(+ checkout_with_item, discount_info, plugins, shipping_amount+):+ currency = checkout_with_item.get_total().currency+ expected_shipping_price = Money(shipping_amount, currency)+ taxed_shipping_price = ExtensionsManager(+ plugins=plugins+ ).calculate_checkout_shipping(checkout_with_item, [discount_info])+ assert (+ TaxedMoney(expected_shipping_price, expected_shipping_price)+ == taxed_shipping_price+ )+++ "plugins, shipping_amount",+ [(["tests.extensions.test_manager.TestPlugin"], "1.0"), ([], "10.0")],+)+def test_manager_calculates_order_shipping(order_with_lines, plugins, shipping_amount):+ currency = order_with_lines.total.currency+ expected_shipping_price = Money(shipping_amount, currency)++ taxed_shipping_price = ExtensionsManager(plugins=plugins).calculate_order_shipping(+ order_with_lines+ )+ assert (+ TaxedMoney(expected_shipping_price, expected_shipping_price)+ == taxed_shipping_price+ )+++ "plugins, amount",+ [(["tests.extensions.test_manager.TestPlugin"], "1.0"), ([], "15.0")],+)+def test_manager_calculates_checkout_line_total(+ checkout_with_item, discount_info, plugins, amount+):+ line = checkout_with_item.lines.all()[0]+ currency = line.get_total().currency+ expected_total = Money(amount, currency)+ taxed_total = ExtensionsManager(plugins=plugins).calculate_checkout_line_total(+ line, [discount_info]+ )+ assert TaxedMoney(expected_total, expected_total) == taxed_total+++ "plugins, amount",+ [(["tests.extensions.test_manager.TestPlugin"], "1.0"), ([], "12.30")],+)+def test_manager_calculates_order_line(order_line, plugins, amount):+ currency = order_line.unit_price.currency+ expected_price = Money(amount, currency)+ unit_price = ExtensionsManager(plugins=plugins).calculate_order_line_unit(+ order_line+ )+ assert expected_price == unit_price.gross+++ "plugins, tax_rate_list",+ [+ (+ ["tests.extensions.test_manager.TestPlugin"],+ [TaxType(code="123", description="abc")],+ ),+ ([], []),+ ],+)+def test_manager_uses_get_tax_rate_choices(plugins, tax_rate_list):+ assert (+ tax_rate_list == ExtensionsManager(plugins=plugins).get_tax_rate_type_choices()+ )+++ "plugins, show_taxes",+ [(["tests.extensions.test_manager.TestPlugin"], True), ([], False)],+)+def test_manager_show_taxes_on_storefront(plugins, show_taxes):+ assert show_taxes == ExtensionsManager(plugins=plugins).show_taxes_on_storefront()+++ "plugins, taxes_enabled",+ [(["tests.extensions.test_manager.TestPlugin"], True), ([], False)],+)+def test_manager_taxes_are_enabled(plugins, taxes_enabled):+ assert taxes_enabled == ExtensionsManager(plugins=plugins).taxes_are_enabled()+++ "plugins, price",+ [(["tests.extensions.test_manager.TestPlugin"], "1.0"), ([], "10.0")],+)+def test_manager_apply_taxes_to_product(product, plugins, price):+ country = Country("PL")+ variant = product.variants.all()[0]+ currency = variant.get_price().currency+ expected_price = Money(price, currency)+ taxed_price = ExtensionsManager(plugins=plugins).apply_taxes_to_product(+ product, variant.get_price(), country+ )+ assert TaxedMoney(expected_price, expected_price) == taxed_price+++ "plugins, price_amount",+ [(["tests.extensions.test_manager.TestPlugin"], "1.0"), ([], "10.0")],+)+def test_manager_apply_taxes_to_shipping(+ shipping_method, address, plugins, price_amount+):+ expected_price = Money(price_amount, "USD")+ taxed_price = ExtensionsManager(plugins=plugins).apply_taxes_to_shipping(+ shipping_method.price, address+ )+ assert TaxedMoney(expected_price, expected_price) == taxed_price