diff --git a/.github/workflows/qc_checks.yaml b/.github/workflows/qc_checks.yaml index e73a1e8f98..93b208451b 100644 --- a/.github/workflows/qc_checks.yaml +++ b/.github/workflows/qc_checks.yaml @@ -153,6 +153,7 @@ jobs: invoke delete-data -f invoke import-fixtures invoke server -a 127.0.0.1:12345 & + invoke wait - name: Run Tests run: | cd ${{ env.wrapper_name }} diff --git a/InvenTree/InvenTree/ready.py b/InvenTree/InvenTree/ready.py index 9f5ad0ea49..e93972cf2e 100644 --- a/InvenTree/InvenTree/ready.py +++ b/InvenTree/InvenTree/ready.py @@ -39,7 +39,8 @@ def canAppAccessDatabase(allow_test=False): 'createsuperuser', 'wait_for_db', 'prerender', - 'rebuild', + 'rebuild_models', + 'rebuild_thumbnails', 'collectstatic', 'makemessages', 'compilemessages', diff --git a/InvenTree/InvenTree/tests.py b/InvenTree/InvenTree/tests.py index 501eed0834..26b50a0eca 100644 --- a/InvenTree/InvenTree/tests.py +++ b/InvenTree/InvenTree/tests.py @@ -1,5 +1,6 @@ import json import os +import time from unittest import mock @@ -406,11 +407,23 @@ class CurrencyTests(TestCase): with self.assertRaises(MissingRate): convert_money(Money(100, 'AUD'), 'USD') - InvenTree.tasks.update_exchange_rates() + update_successful = False - rates = Rate.objects.all() + # Note: the update sometimes fails in CI, let's give it a few chances + for idx in range(10): + InvenTree.tasks.update_exchange_rates() - self.assertEqual(rates.count(), len(currency_codes())) + rates = Rate.objects.all() + + if rates.count() == len(currency_codes()): + update_successful = True + break + + else: + print("Exchange rate update failed - retrying") + time.sleep(1) + + self.assertTrue(update_successful) # Now that we have some exchange rate information, we can perform conversions diff --git a/InvenTree/plugin/apps.py b/InvenTree/plugin/apps.py index 233f037ec7..c0e894fef1 100644 --- a/InvenTree/plugin/apps.py +++ b/InvenTree/plugin/apps.py @@ -7,7 +7,7 @@ from django.utils.translation import gettext_lazy as _ from maintenance_mode.core import set_maintenance_mode -from InvenTree.ready import isImportingData +from InvenTree.ready import canAppAccessDatabase from plugin import registry from plugin.helpers import check_git_version, log_error @@ -20,9 +20,8 @@ class PluginAppConfig(AppConfig): def ready(self): if settings.PLUGINS_ENABLED: - - if isImportingData(): # pragma: no cover - logger.info('Skipping plugin loading for data import') + if not canAppAccessDatabase(allow_test=True): + logger.info("Skipping plugin loading sequence") else: logger.info('Loading InvenTree plugins') @@ -48,3 +47,6 @@ class PluginAppConfig(AppConfig): registry.git_is_modern = check_git_version() if not registry.git_is_modern: # pragma: no cover # simulating old git seems not worth it for coverage log_error(_('Your enviroment has an outdated git version. This prevents InvenTree from loading plugin details.'), 'load') + + else: + logger.info("Plugins not enabled - skipping loading sequence") diff --git a/InvenTree/plugin/base/integration/mixins.py b/InvenTree/plugin/base/integration/mixins.py index 64de5df22b..6977ef3dd9 100644 --- a/InvenTree/plugin/base/integration/mixins.py +++ b/InvenTree/plugin/base/integration/mixins.py @@ -11,7 +11,8 @@ from django.db.utils import OperationalError, ProgrammingError import InvenTree.helpers -from plugin.helpers import MixinImplementationError, MixinNotImplementedError, render_template +from plugin.helpers import MixinImplementationError, MixinNotImplementedError +from plugin.helpers import render_template, render_text from plugin.models import PluginConfig, PluginSetting from plugin.registry import registry from plugin.urls import PLUGIN_BASE @@ -59,6 +60,7 @@ class SettingsMixin: if not plugin: # Cannot find associated plugin model, return + logger.error(f"Plugin configuration not found for plugin '{self.slug}'") return # pragma: no cover PluginSetting.set_setting(key, value, user, plugin=plugin) @@ -578,10 +580,16 @@ class PanelMixin: if content_template: # Render content template to HTML panel['content'] = render_template(self, content_template, ctx) + else: + # Render content string to HTML + panel['content'] = render_text(panel.get('content', ''), ctx) if javascript_template: # Render javascript template to HTML panel['javascript'] = render_template(self, javascript_template, ctx) + else: + # Render javascript string to HTML + panel['javascript'] = render_text(panel.get('javascript', ''), ctx) # Check for required keys required_keys = ['title', 'content'] diff --git a/InvenTree/plugin/base/integration/test_mixins.py b/InvenTree/plugin/base/integration/test_mixins.py index ef3f7062e3..c1afa39fc2 100644 --- a/InvenTree/plugin/base/integration/test_mixins.py +++ b/InvenTree/plugin/base/integration/test_mixins.py @@ -2,14 +2,19 @@ from django.test import TestCase from django.conf import settings -from django.urls import include, re_path +from django.urls import include, re_path, reverse from django.contrib.auth import get_user_model +from django.contrib.auth.models import Group + +from error_report.models import Error from plugin import InvenTreePlugin from plugin.mixins import AppMixin, SettingsMixin, UrlsMixin, NavigationMixin, APICallMixin from plugin.urls import PLUGIN_BASE from plugin.helpers import MixinNotImplementedError +from plugin.registry import registry + class BaseMixinDefinition: def test_mixin_name(self): @@ -244,3 +249,161 @@ class APICallMixinTest(BaseMixinDefinition, TestCase): # cover wrong token setting with self.assertRaises(MixinNotImplementedError): self.mixin_wrong2.has_api_call() + + +class PanelMixinTests(TestCase): + """Test that the PanelMixin plugin operates correctly""" + + fixtures = [ + 'category', + 'part', + 'location', + 'stock', + ] + + def setUp(self): + super().setUp() + + # Create a user which has all the privelages + user = get_user_model() + + self.user = user.objects.create_user( + username='username', + email='user@email.com', + password='password' + ) + + # Put the user into a group with the correct permissions + group = Group.objects.create(name='mygroup') + self.user.groups.add(group) + + # Give the group *all* the permissions! + for rule in group.rule_sets.all(): + rule.can_view = True + rule.can_change = True + rule.can_add = True + rule.can_delete = True + + rule.save() + + self.client.login(username='username', password='password') + + def test_installed(self): + """Test that the sample panel plugin is installed""" + + plugins = registry.with_mixin('panel') + + self.assertTrue(len(plugins) > 0) + + self.assertIn('samplepanel', [p.slug for p in plugins]) + + plugins = registry.with_mixin('panel', active=True) + + self.assertEqual(len(plugins), 0) + + def test_disabled(self): + """Test that the panels *do not load* if the plugin is not enabled""" + + plugin = registry.get_plugin('samplepanel') + + plugin.set_setting('ENABLE_HELLO_WORLD', True) + plugin.set_setting('ENABLE_BROKEN_PANEL', True) + + # Ensure that the plugin is *not* enabled + config = plugin.plugin_config() + + self.assertFalse(config.active) + + # Load some pages, ensure that the panel content is *not* loaded + for url in [ + reverse('part-detail', kwargs={'pk': 1}), + reverse('stock-item-detail', kwargs={'pk': 2}), + reverse('stock-location-detail', kwargs={'pk': 1}), + ]: + response = self.client.get( + url + ) + + self.assertEqual(response.status_code, 200) + + # Test that these panels have *not* been loaded + self.assertNotIn('No Content', str(response.content)) + self.assertNotIn('Hello world', str(response.content)) + self.assertNotIn('Custom Part Panel', str(response.content)) + + def test_enabled(self): + """ + Test that the panels *do* load if the plugin is enabled + """ + + plugin = registry.get_plugin('samplepanel') + + self.assertEqual(len(registry.with_mixin('panel', active=True)), 0) + + # Ensure that the plugin is enabled + config = plugin.plugin_config() + config.active = True + config.save() + + self.assertTrue(config.active) + self.assertEqual(len(registry.with_mixin('panel', active=True)), 1) + + # Load some pages, ensure that the panel content is *not* loaded + urls = [ + reverse('part-detail', kwargs={'pk': 1}), + reverse('stock-item-detail', kwargs={'pk': 2}), + reverse('stock-location-detail', kwargs={'pk': 1}), + ] + + plugin.set_setting('ENABLE_HELLO_WORLD', False) + plugin.set_setting('ENABLE_BROKEN_PANEL', False) + + for url in urls: + response = self.client.get(url) + + self.assertEqual(response.status_code, 200) + + self.assertIn('No Content', str(response.content)) + + # This panel is disabled by plugin setting + self.assertNotIn('Hello world!', str(response.content)) + + # This panel is only active for the "Part" view + if url == urls[0]: + self.assertIn('Custom Part Panel', str(response.content)) + else: + self.assertNotIn('Custom Part Panel', str(response.content)) + + # Enable the 'Hello World' panel + plugin.set_setting('ENABLE_HELLO_WORLD', True) + + for url in urls: + response = self.client.get(url) + + self.assertEqual(response.status_code, 200) + + self.assertIn('Hello world!', str(response.content)) + + # The 'Custom Part' panel should still be there, too + if url == urls[0]: + self.assertIn('Custom Part Panel', str(response.content)) + else: + self.assertNotIn('Custom Part Panel', str(response.content)) + + # Enable the 'broken panel' setting - this will cause all panels to not render + plugin.set_setting('ENABLE_BROKEN_PANEL', True) + + n_errors = Error.objects.count() + + for url in urls: + response = self.client.get(url) + self.assertEqual(response.status_code, 200) + + # No custom panels should have been loaded + self.assertNotIn('No Content', str(response.content)) + self.assertNotIn('Hello world!', str(response.content)) + self.assertNotIn('Broken Panel', str(response.content)) + self.assertNotIn('Custom Part Panel', str(response.content)) + + # Assert that each request threw an error + self.assertEqual(Error.objects.count(), n_errors + len(urls)) diff --git a/InvenTree/plugin/helpers.py b/InvenTree/plugin/helpers.py index 1217fa4d47..90ffe61478 100644 --- a/InvenTree/plugin/helpers.py +++ b/InvenTree/plugin/helpers.py @@ -245,4 +245,15 @@ def render_template(plugin, template_file, context=None): html = tmp.render(context) return html + + +def render_text(text, context=None): + """ + Locate a raw string with provided context + """ + + ctx = template.Context(context) + + return template.Template(text).render(ctx) + # endregion diff --git a/InvenTree/plugin/registry.py b/InvenTree/plugin/registry.py index 3d58634340..1ec5adb161 100644 --- a/InvenTree/plugin/registry.py +++ b/InvenTree/plugin/registry.py @@ -243,7 +243,7 @@ class PluginsRegistry: # endregion # region registry functions - def with_mixin(self, mixin: str): + def with_mixin(self, mixin: str, active=None): """ Returns reference to all plugins that have a specified mixin enabled """ @@ -251,6 +251,14 @@ class PluginsRegistry: for plugin in self.plugins.values(): if plugin.mixin_enabled(mixin): + + if active is not None: + # Filter by 'enabled' status + config = plugin.plugin_config() + + if config.active != active: + continue + result.append(plugin) return result diff --git a/InvenTree/plugin/samples/event/event_sample.py b/InvenTree/plugin/samples/event/event_sample.py index 5411781e05..bea21c3ea0 100644 --- a/InvenTree/plugin/samples/event/event_sample.py +++ b/InvenTree/plugin/samples/event/event_sample.py @@ -12,7 +12,7 @@ class EventPluginSample(EventMixin, InvenTreePlugin): """ NAME = "EventPlugin" - SLUG = "event" + SLUG = "sampleevent" TITLE = "Triggered Events" def process_event(self, event, *args, **kwargs): diff --git a/InvenTree/plugin/samples/integration/custom_panel_sample.py b/InvenTree/plugin/samples/integration/custom_panel_sample.py index 0203fc4e04..3d44bc0c5b 100644 --- a/InvenTree/plugin/samples/integration/custom_panel_sample.py +++ b/InvenTree/plugin/samples/integration/custom_panel_sample.py @@ -15,17 +15,23 @@ class CustomPanelSample(PanelMixin, SettingsMixin, InvenTreePlugin): """ NAME = "CustomPanelExample" - SLUG = "panel" + SLUG = "samplepanel" TITLE = "Custom Panel Example" DESCRIPTION = "An example plugin demonstrating how custom panels can be added to the user interface" VERSION = "0.1" SETTINGS = { 'ENABLE_HELLO_WORLD': { - 'name': 'Hello World', + 'name': 'Enable Hello World', 'description': 'Enable a custom hello world panel on every page', 'default': False, 'validator': bool, + }, + 'ENABLE_BROKEN_PANEL': { + 'name': 'Enable Broken Panel', + 'description': 'Enable a panel with rendering issues', + 'default': False, + 'validator': bool, } } @@ -52,21 +58,48 @@ class CustomPanelSample(PanelMixin, SettingsMixin, InvenTreePlugin): panels = [ { - # This panel will not be displayed, as it is missing the 'content' key + # Simple panel without any actual content 'title': 'No Content', } ] if self.get_setting('ENABLE_HELLO_WORLD'): + + # We can use template rendering in the raw content + content = """ + Hello world! +
Path | {{ request.path }} |
User | {{ user.username }} |