diff --git a/plinth/app.py b/plinth/app.py index a1c8e4247..e18a824be 100644 --- a/plinth/app.py +++ b/plinth/app.py @@ -463,6 +463,33 @@ class Info(FollowerComponent): clients_module.validate(clients) +class EnableState(LeaderComponent): + """A component to hold the enable state of an app using a simple flag.""" + + @property + def key(self): + """Return the storage key.""" + if not self.app_id: + raise KeyError('Component must be added to an app before use.') + + return f'{self.app_id}_enable' + + def is_enabled(self): + """Return whether the app/component is enabled.""" + from plinth import kvstore + return kvstore.get_default(self.key, False) + + def enable(self): + """Store that the app/component is enabled.""" + from plinth import kvstore + kvstore.set(self.key, True) + + def disable(self): + """Store that the app/component is enabled.""" + from plinth import kvstore + kvstore.set(self.key, False) + + def apps_init(): """Create apps by constructing them with components.""" from . import module_loader # noqa # Avoid circular import diff --git a/plinth/tests/test_app.py b/plinth/tests/test_app.py index a7603622f..3ce28e5fc 100644 --- a/plinth/tests/test_app.py +++ b/plinth/tests/test_app.py @@ -9,7 +9,7 @@ from unittest.mock import Mock, call, patch import pytest -from plinth.app import (App, Component, FollowerComponent, Info, +from plinth.app import (App, Component, EnableState, FollowerComponent, Info, LeaderComponent, apps_init) # pylint: disable=protected-access @@ -427,6 +427,28 @@ def test_info_clients_validation(): Info('test-app', 3, clients=clients) +def test_enable_state_key(app_with_components): + """Test getting the storage key for enable state component.""" + component = EnableState('enable-state-1') + with pytest.raises(KeyError): + assert component.key + + app_with_components.add(component) + assert component.key == app_with_components.app_id + '_enable' + + +@pytest.mark.django_db +def test_enable_state_enable_disable(app_with_components): + """Test enabling/disabling enable state component.""" + component = EnableState('enable-state-1') + app_with_components.add(component) + assert not component.is_enabled() + component.enable() + assert component.is_enabled() + component.disable() + assert not component.is_enabled() + + class ModuleTest1: """A test module with an app."""