Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add check to validate plugin methods. Clean up after review
Maciej Korycinski7d255a5dc795
diff --git a/saleor/core/extensions/checks.py b/saleor/core/extensions/checks.pyindex 58dfe1908c..19ababd17c 100644--- a/saleor/core/extensions/checks.py+++ b/saleor/core/extensions/checks.py@@ -1,9 +1,11 @@import importlib-from typing import List+from typing import List, Setfrom django.conf import settingsfrom django.core.checks import Error, register+from .plugin import BasePlugin+@register()def check_extensions(app_configs, **kwargs):@@ -40,21 +42,44 @@ def check_manager(errors: List[Error]):def check_plugins(errors: List[Error], plugins: List[str]):+ base_methods = set([name for name in vars(BasePlugin) if not name.startswith("_")])+ plugins_methods = set()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(".")- 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))- )+ check_single_plugin(plugin_path, errors, plugins_methods)++ if not errors:+ missing_methods = base_methods.difference(plugins_methods)+ for missing_method in missing_methods:+ errors.append(+ Error(+ "Implementation of base method %s not found in plugin classes"+ % missing_method)+ )+++def check_single_plugin(+ plugin_path: str, errors: List[Error], plugins_methods: Set[str]+):+ if not plugin_path:+ errors.append(Error("Wrong plugin_path %s" % plugin_path))+ return+ plugin_path, _, plugin_name = plugin_path.rpartition(".")+ 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))+ )+ )+ else:+ for method_name in vars(plugin_class):+ if method_name.startswith("_"):+ continue+ plugins_methods.add(method_name)diff --git a/saleor/core/extensions/dummy_plugin.py b/saleor/core/extensions/default_plugin.pysimilarity index 94%rename from saleor/core/extensions/dummy_plugin.pyrename to saleor/core/extensions/default_plugin.pyindex 3cea1e928c..f7caf8ec27 100644--- a/saleor/core/extensions/dummy_plugin.py+++ b/saleor/core/extensions/default_plugin.py@@ -13,9 +13,10 @@ if TYPE_CHECKING:from ...order.models import OrderLine, Order-class DummyPlugin(BasePlugin):- """Dummy plugin class which overwrites all base plugin methods. It should be used- when any other plugins are disabled"""+class DefaultPlugin(BasePlugin):+ """Default plugin class - overwrites all base plugin methods.+ It should be enabled to cover all base methods in case when+ implementation doesn't use custom plugins"""def calculate_checkout_total(self, checkout: "Checkout", discounts: List["DiscountInfo"]@@ -45,14 +46,6 @@ class DummyPlugin(BasePlugin):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"]):@@ -63,10 +56,8 @@ class DummyPlugin(BasePlugin):unit_price = order_line.unit_pricereturn 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 get_tax_rate_type_choices(self) -> List[TaxType]:+ return []def show_taxes_on_storefront(self) -> bool:return False@@ -74,6 +65,16 @@ class DummyPlugin(BasePlugin):def taxes_are_enabled(self) -> bool:return False+ def apply_taxes_to_product(+ self, product: "Product", price: Money, country: Country, **kwargs+ ):+ return quantize_price(TaxedMoney(net=price, gross=price), 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 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)diff --git a/saleor/core/extensions/plugin.py b/saleor/core/extensions/plugin.pyindex ebc79486e0..fe936580ff 100644--- a/saleor/core/extensions/plugin.py+++ b/saleor/core/extensions/plugin.py@@ -3,9 +3,8 @@ from typing import TYPE_CHECKING, List, Unionfrom django_countries.fields import Countryfrom prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange-from ..taxes import TaxType-if TYPE_CHECKING:+ from ..taxes import TaxTypefrom ...checkout.models import Checkout, CheckoutLinefrom ...product.models import Productfrom ...account.models import Address@@ -33,14 +32,6 @@ class BasePlugin:def calculate_order_shipping(self, order: "Order") -> TaxedMoney:raise NotImplementedError()- def apply_taxes_to_shipping(- self, price: Money, shipping_address: "Address"- ) -> TaxedMoney:- raise NotImplementedError()-- def get_tax_rate_type_choices(self) -> List[TaxType]:- raise NotImplementedError()-def calculate_checkout_line_total(self, checkout_line: "CheckoutLine", discounts: List["DiscountInfo"]) -> TaxedMoney:@@ -49,9 +40,7 @@ class BasePlugin:def calculate_order_line_unit(self, order_line: "OrderLine") -> TaxedMoney:raise NotImplementedError()- def apply_taxes_to_product(- self, product: "Product", price: Money, country: Country, **kwargs- ):+ def get_tax_rate_type_choices(self) -> List["TaxType"]:raise NotImplementedError()def show_taxes_on_storefront(self) -> bool:@@ -65,6 +54,16 @@ class BasePlugin:) -> TaxedMoneyRange:raise NotImplementedError()+ def apply_taxes_to_shipping(+ self, price: Money, shipping_address: "Address"+ ) -> TaxedMoney:+ raise NotImplementedError()++ def apply_taxes_to_product(+ self, product: "Product", price: Money, country: Country, **kwargs+ ):+ raise NotImplementedError()+def preprocess_order_creation(self, checkout: "Checkout", discounts: List["DiscountInfo"]):@@ -80,5 +79,5 @@ class BasePlugin:def get_data_from_object_meta(self, obj: Union["Product", "ProductType"]- ) -> TaxType:+ ) -> "TaxType":raise NotImplementedError()diff --git a/tests/extensions/test_checks.py b/tests/extensions/test_checks.pyindex d0933167ad..b84980bf03 100644--- a/tests/extensions/test_checks.py+++ b/tests/extensions/test_checks.py@@ -1,6 +1,11 @@import pytestfrom saleor.core.extensions.checks import check_extensions+from saleor.core.extensions.plugin import BasePlugin+++class Test(BasePlugin):+ """"""@pytest.mark.parametrize(@@ -15,7 +20,13 @@ def test_check_extensions_missing_manager(manager_path, settings):@pytest.mark.parametrize("plugin_path", [None, "", "saleor.core.extension.wrong_path.Plugin"])-def test_check_extensions_plugins(plugin_path, settings):+def test_check_extensions_wrong_declaration_of_plugins(plugin_path, settings):settings.PLUGINS = [plugin_path]errors = check_extensions({})assert errors+++def test_check_extensions_missing_implementation_of_base_methods(settings):+ settings.PLUGINS = ["tests.extensions.test_checks.Test"]+ errors = check_extensions({})+ assert errorsdiff --git a/tests/extensions/test_dummy_plugin.py b/tests/extensions/test_dummy_plugin.pydeleted file mode 100644index f2f659237a..0000000000--- a/tests/extensions/test_dummy_plugin.py+++ /dev/null@@ -1,11 +0,0 @@-from saleor.core.extensions.dummy_plugin import DummyPlugin-from saleor.core.extensions.plugin import BasePlugin---def test_dummy_plugin_overwrites_all_base_plugin_methods():- assert isinstance(BasePlugin(), DummyPlugin.__bases__[0])- dummy_vars = vars(DummyPlugin)- for name in vars(BasePlugin):- if name.startswith("__"):- continue- assert name in dummy_varsdiff --git a/tests/extensions/test_manager.py b/tests/extensions/test_manager.pyindex 5da3afccb0..ed5a5d4b50 100644--- a/tests/extensions/test_manager.py+++ b/tests/extensions/test_manager.py@@ -1,25 +1,25 @@from unittest.mock import patch-from saleor.core.extensions.dummy_plugin import DummyPlugin+from saleor.core.extensions.default_plugin import DefaultPluginfrom saleor.core.extensions.manager import BaseManager, get_extensions_managerdef test_get_extensions_manager():manager_path = "saleor.core.extensions.manager.BaseManager"- dummy_plugin_path = "saleor.core.extensions.dummy_plugin.DummyPlugin"+ dummy_plugin_path = "saleor.core.extensions.default_plugin.DefaultPlugin"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)+ assert isinstance(manager.plugins[0], DefaultPlugin)[email protected](DummyPlugin, "calculate_checkout_total")[email protected](DefaultPlugin, "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"+ dummy_plugin_path = "saleor.core.extensions.default_plugin.DefaultPlugin"manager = BaseManager(plugins=[dummy_plugin_path])discounts = [discount_info]manager.calculate_checkout_total(checkout_with_item, discounts)diff --git a/tests/extensions/test_standard_plugin.py b/tests/extensions/test_standard_plugin.pynew file mode 100644index 0000000000..73521edffb--- /dev/null+++ b/tests/extensions/test_standard_plugin.py@@ -0,0 +1,11 @@+from saleor.core.extensions.default_plugin import DefaultPlugin+from saleor.core.extensions.plugin import BasePlugin+++def test_standard_plugin_overwrites_all_base_plugin_methods():+ assert isinstance(BasePlugin(), DefaultPlugin.__bases__[0])+ dummy_vars = vars(DefaultPlugin)+ for name in vars(BasePlugin):+ if name.startswith("__"):+ continue+ assert name in dummy_vars