app: component: Add app_id and app properties

- So that with a component at hand, it's app can be easily retrieved.

- Don't create circular dependencies.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: Veiko Aasa <veiko17@disroot.org>
This commit is contained in:
Sunil Mohan Adapa 2020-09-28 15:46:37 -07:00 committed by Veiko Aasa
parent d45cc00981
commit 734e4fea9a
No known key found for this signature in database
GPG Key ID: 478539CAE680674E
2 changed files with 33 additions and 1 deletions

View File

@ -53,12 +53,14 @@ class App:
def add(self, component):
"""Add a component to an app."""
component.app_id = self.app_id
self.components[component.component_id] = component
return self
def remove(self, component_id):
"""Remove a component from the app."""
component = self.components[component_id]
component.app_id = None
del self.components[component_id]
return component
@ -167,7 +169,13 @@ class App:
class Component:
"""Interface for an app component."""
"""Interface for an app component.
`app_id` is a string which is set to the value of the application's app_id
to which this component belongs. It is set when the component is added to
an app. When the component is removed from an app, it set to None.
"""
is_leader = False
@ -177,6 +185,16 @@ class Component:
raise ValueError('Invalid component ID')
self.component_id = component_id
self.app_id = None
@property
def app(self):
"""Return the app this component is part of.
Raises KeyError if this component is not part of any app.
"""
return App.get(self.app_id)
def enable(self):
"""Run operations to enable the component."""

View File

@ -71,6 +71,7 @@ def test_app_add():
return_value = app.add(component)
assert len(app.components) == 1
assert app.components['test-component'] == component
assert component.app_id == app.app_id
assert return_value == app
@ -79,6 +80,7 @@ def test_app_remove(app_with_components):
app = app_with_components
component = app.components['test-leader-1']
assert app.remove('test-leader-1') == component
assert component.app_id is None
assert 'test-leader-1' not in app.components
@ -206,6 +208,18 @@ def test_component_initialization():
assert not component.is_leader
def test_component_app_property():
"""Test component's app property."""
component = Component('test-component')
assert component.app_id is None
with pytest.raises(KeyError):
assert not component.app
app = AppTest()
app.add(component)
assert component.app == app
def test_component_diagnose():
"""Test running diagnostics on component."""
component = Component('test-component')