Skip to content

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

Add tests for extension manager

Maciej Korycinskice05ea8deb2f
diff --git a/saleor/core/extensions/checks.py b/saleor/core/extensions/checks.py
index ca658dfe81..00174958dd 100644
--- a/saleor/core/extensions/checks.py
+++ b/saleor/core/extensions/checks.py
@@ -19,30 +19,42 @@ def check_extensions(app_configs, **kwargs):
def check_manager(errors: List[Error]):
- if not settings.EXTENSION_MANAGER:
- return []
+ if not hasattr(settings, "EXTENSION_MANAGER") or not settings.EXTENSION_MANAGER:
+ errors.append(Error("Settings should contain EXTENSION_MANAGER env"))
+ return
manager_path = settings.EXTENSION_MANAGER
manager_path, _, manager_name = manager_path.rpartition(".")
- manager_module = importlib.import_module(manager_path)
- manager_class = getattr(manager_module, manager_name, None)
- if not manager_class:
- errors.append(
- Error(
- "Extension Manager %s doesn't exists in specific path %s"
- % (manager_name, str(manager_module))
+ try:
+ manager_module = importlib.import_module(manager_path)
+ except ModuleNotFoundError:
+ errors.append(Error("Extension Manager path: %s doesn't exist" % manager_path))
+ else:
+ manager_class = getattr(manager_module, manager_name, None)
+ if not manager_class:
+ errors.append(
+ Error(
+ "Extension Manager %s doesn't exists in specific path %s"
+ % (manager_name, str(manager_module))
+ )
)
- )
def check_plugins(errors: List[Error], plugins: List[str]):
for plugin_path in plugins:
+ if not plugin_path:
+ errors.append(Error("Wrong plugin_path %s" % plugin_path))
+ continue
plugin_path, _, plugin_name = plugin_path.rpartition(".")
- plugin_module = importlib.import_module(plugin_path)
- plugin_class = getattr(plugin_module, plugin_name, None)
- if not plugin_class:
- errors.append(
- Error(
- "Plugin %s doesn't exists in specific path %s"
- % (plugin_name, str(plugin_module))
+ try:
+ plugin_module = importlib.import_module(plugin_path)
+ except ModuleNotFoundError:
+ errors.append(Error("Plugin with path: %s doesn't exist" % plugin_path))
+ else:
+ plugin_class = getattr(plugin_module, plugin_name, None)
+ if not plugin_class:
+ errors.append(
+ Error(
+ "Plugin %s doesn't exists in specific path %s"
+ % (plugin_name, str(plugin_module))
+ )
)
- )
diff --git a/saleor/core/extensions/dummy_plugin.py b/saleor/core/extensions/dummy_plugin.py
new file mode 100644
index 0000000000..13ad4a25b4
--- /dev/null
+++ b/saleor/core/extensions/dummy_plugin.py
@@ -0,0 +1,95 @@
+from typing import TYPE_CHECKING, List, Union
+
+from django_countries.fields import Country
+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
+
+from ..taxes import TaxType, quantize_price
+
+if TYPE_CHECKING:
+ from ...checkout.models import Checkout, CheckoutLine
+ from ...product.models import Product
+ from ...account.models import Address
+ from ...order.models import OrderLine, Order
+
+
+class DummyPlugin:
+ """Dummy plugin class which overwrites all base plugin methods. It should be used
+ when any other plugins are enabled"""
+
+ def calculate_checkout_total(
+ self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ ) -> TaxedMoney:
+ total = checkout.get_total(discounts)
+ return quantize_price(TaxedMoney(net=total, gross=total), total.currency)
+
+ def calculate_checkout_subtotal(
+ self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ ) -> TaxedMoney:
+ subtotal = checkout.get_subtotal(discounts)
+ return quantize_price(
+ TaxedMoney(net=subtotal, gross=subtotal), subtotal.currency
+ )
+
+ def calculate_checkout_shipping(
+ self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ ) -> TaxedMoney:
+ total = checkout.get_shipping_price()
+ total = TaxedMoney(net=total, gross=total)
+ return quantize_price(total, total.currency)
+
+ def calculate_order_shipping(self, order: "Order") -> TaxedMoney:
+ shipping_price = order.shipping_method.price
+ return quantize_price(
+ TaxedMoney(net=shipping_price, gross=shipping_price),
+ shipping_price.currency,
+ )
+
+ def apply_taxes_to_shipping(
+ self, price: Money, shipping_address: "Address"
+ ) -> TaxedMoney:
+ return quantize_price(TaxedMoney(net=price, gross=price), price.currency)
+
+ def get_tax_rate_type_choices(self) -> List[TaxType]:
+ return []
+
+ def calculate_checkout_line_total(
+ self, checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]
+ ):
+ total = checkout_line.get_total(discounts)
+ return quantize_price(TaxedMoney(net=total, gross=total), total.currency)
+
+ def calculate_order_line_unit(self, order_line: "OrderLine"):
+ unit_price = order_line.unit_price
+ return quantize_price(unit_price, unit_price.currency)
+
+ def apply_taxes_to_product(
+ self, product: "Product", price: Money, country: Country, **kwargs
+ ):
+ return quantize_price(TaxedMoney(net=price, gross=price), price.currency)
+
+ def show_taxes_on_storefront(self) -> bool:
+ return False
+
+ def taxes_are_enabled(self) -> bool:
+ return False
+
+ def apply_taxes_to_shipping_price_range(self, prices: MoneyRange, country: Country):
+ start = TaxedMoney(net=prices.start, gross=prices.start)
+ stop = TaxedMoney(net=prices.stop, gross=prices.stop)
+ return quantize_price(TaxedMoneyRange(start=start, stop=stop), start.currency)
+
+ def preprocess_order_creation(
+ self, checkout: "Checkout", discounts: List["DiscountInfo"]
+ ):
+ return
+
+ def postprocess_order_creation(self, order: "Order"):
+ return
+
+ def assign_tax_to_object_meta(
+ self, obj: Union["Product", "ProductType"], tax_code: str
+ ):
+ return
+
+ def get_tax_from_object_meta(self, obj: Union["Product", "ProductType"]) -> TaxType:
+ return TaxType(code="", description="")
diff --git a/saleor/core/extensions/manager.py b/saleor/core/extensions/manager.py
index 5bfc360219..4777dacb7f 100644
--- a/saleor/core/extensions/manager.py
+++ b/saleor/core/extensions/manager.py
@@ -6,10 +6,6 @@ from django.conf import settings
from .plugin import BasePlugin
-class PluginError(BaseException):
- """ Default plugin exception """
-
-
class BaseManager(BasePlugin):
"""Base manager for handling a plugins logic. It inherits BasePlugin to support
IDEs' hints"""
@@ -22,7 +18,7 @@ class BaseManager(BasePlugin):
plugin_path, _, plugin_name = plugin_path.rpartition(".")
plugin_module = importlib.import_module(plugin_path)
plugin_class = getattr(plugin_module, plugin_name)
- self.plugins.append(plugin_class)
+ self.plugins.append(plugin_class())
def __getattribute__(self, item: str):
for name, func in vars(BasePlugin).items():
@@ -39,8 +35,10 @@ class BaseManager(BasePlugin):
value = None
for p in self.plugins:
try:
- value = getattr(p, name)(p, *args, **kwargs)
- print(value)
+ plugin_value = getattr(p, name)(*args, **kwargs)
+ # FIXME
+ if plugin_value:
+ value = plugin_value
except NotImplementedError:
continue
except AttributeError:
@@ -50,8 +48,11 @@ class BaseManager(BasePlugin):
return run_plugin_method
-def get_enabled_manager(manager_path: str = settings.EXTENSION_MANAGER) -> BaseManager:
+def get_extensions_manager(
+ manager_path: str = settings.EXTENSIONS_MANAGER,
+ plugins: List[str] = settings.PLUGINS,
+) -> BaseManager:
manager_path, _, manager_name = manager_path.rpartition(".")
manager_module = importlib.import_module(manager_path)
manager_class = getattr(manager_module, manager_name, None)
- return manager_class()
+ return manager_class(plugins)
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index ca26915d95..b33b8248df 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -23,7 +23,7 @@ from django_countries.fields import Country
from ..discount.utils import fetch_discounts
from . import analytics
-from .extensions.manager import get_enabled_manager
+from .extensions.manager import get_extensions_manager
from .utils import get_client_ip, get_country_by_ip, get_currency_for_country
logger = logging.getLogger(__name__)
@@ -182,7 +182,7 @@ def extensions(get_response):
"""Assign extensions manager"""
def _get_manager():
- return get_enabled_manager()
+ return get_extensions_manager()
def middleware(request):
request.extensions = SimpleLazyObject(_get_manager)
diff --git a/tests/extensions/test_checks.py b/tests/extensions/test_checks.py
new file mode 100644
index 0000000000..74a8238e34
--- /dev/null
+++ b/tests/extensions/test_checks.py
@@ -0,0 +1,21 @@
+import pytest
+
+from saleor.core.extensions.checks import check_extensions
+
+
+ "manager_path", [None, "", "saleor.core.extension.wrong_path.Manager"]
+)
+def test_check_extensions_missing_manager(manager_path, settings):
+ settings.EXTENSION_MANAGER = manager_path
+ errors = check_extensions({})
+ assert errors
+
+
+ "plugin_path", [None, "", "saleor.core.extension.wrong_path.Plugin"]
+)
+def test_check_extensions_plugins(plugin_path, settings):
+ settings.PLUGINS = [plugin_path]
+ errors = check_extensions({})
+ assert errors
diff --git a/tests/extensions/test_manager.py b/tests/extensions/test_manager.py
new file mode 100644
index 0000000000..5da3afccb0
--- /dev/null
+++ b/tests/extensions/test_manager.py
@@ -0,0 +1,26 @@
+from unittest.mock import patch
+
+from saleor.core.extensions.dummy_plugin import DummyPlugin
+from saleor.core.extensions.manager import BaseManager, get_extensions_manager
+
+
+def test_get_extensions_manager():
+ manager_path = "saleor.core.extensions.manager.BaseManager"
+ dummy_plugin_path = "saleor.core.extensions.dummy_plugin.DummyPlugin"
+ manager = get_extensions_manager(
+ manager_path=manager_path, plugins=[dummy_plugin_path]
+ )
+ assert isinstance(manager, BaseManager)
+ assert len(manager.plugins) == 1
+ assert isinstance(manager.plugins[0], DummyPlugin)
+
+
[email protected](DummyPlugin, "calculate_checkout_total")
+def test_manager_can_run_plugin_methods(
+ mock_calculate, checkout_with_item, discount_info
+):
+ dummy_plugin_path = "saleor.core.extensions.dummy_plugin.DummyPlugin"
+ manager = BaseManager(plugins=[dummy_plugin_path])
+ discounts = [discount_info]
+ manager.calculate_checkout_total(checkout_with_item, discounts)
+ assert mock_calculate.called