Skip to content

Commit

Permalink
feat(services): add service setup method
Browse files Browse the repository at this point in the history
Service classes can override the `setup` method to run custom
preparation before service execution, such as downloading additional
assets or performing consistency checks.

Signed-off-by: Claudio Matsuoka <[email protected]>
  • Loading branch information
cmatsuoka committed Sep 7, 2023
1 parent 6a9f2c6 commit bd77044
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
3 changes: 3 additions & 0 deletions craft_application/services/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@ class BaseService(metaclass=abc.ABCMeta): # noqa: B024
def __init__(self, app: AppMetadata, project: models.Project) -> None:
self._app = app
self._project = project

def setup(self) -> None:
"""Application-specific service preparation."""
1 change: 1 addition & 0 deletions craft_application/services/service_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ def __getattr__(self, service: str) -> services.BaseService:
if issubclass(cls, services.BaseService):
kwargs = self._service_kwargs.get(service, {})
instance = cls(self.app, self.project, **kwargs)
instance.setup()
setattr(self, service, instance)
# Mypy and pyright interpret this differently.
# Pyright
Expand Down
14 changes: 14 additions & 0 deletions tests/unit/services/test_service_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import pytest
import pytest_check
from craft_application import errors, services
from craft_cli import emit


@pytest.fixture()
Expand Down Expand Up @@ -116,3 +117,16 @@ def test_getattr_project_none(app_metadata, fake_package_service_class):

with pytest.raises(errors.ApplicationError):
_ = factory.package


def test_service_setup(app_metadata, fake_project, fake_package_service_class, emitter):
class FakePackageService(fake_package_service_class):
def setup(self) -> None:
emit.debug("setting up package service")

factory = services.ServiceFactory(
app_metadata, project=fake_project, PackageClass=FakePackageService
)
_ = factory.package

assert emitter.assert_debug("setting up package service")

0 comments on commit bd77044

Please sign in to comment.