From 0fc049f921b2a503d5820fc479cd202be883ac6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADtor=20Zeni?= Date: Fri, 13 Nov 2026 10:46:44 -0300 Subject: [PATCH 1/2] fix(juju): raise JujuException when get_app_config fails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When `juju config` failed for any reason other than the application not being found, get_app_config built its error message from config_value, which is only set on success. The f-string raised UnboundLocalError instead of the intended JujuException, so callers catching JujuException crashed. test_get_app_config_fail set up the failing `juju config` call but then called get_secret, so this path was never tested. Point it at get_app_config; it fails with UnboundLocalError without the fix. The ubuntu-pro enable step now reads the application config, and relies on this raising JujuException. Jira: OPEN-4916 Assisted-By: Claude Code (Claude Opus 5.5) Related-Bug: #2158218 Signed-off-by: Vítor Zeni --- sunbeam-python/sunbeam/core/juju.py | 2 +- sunbeam-python/tests/unit/sunbeam/core/test_juju.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sunbeam-python/sunbeam/core/juju.py b/sunbeam-python/sunbeam/core/juju.py index c0163c1ea..e7c856843 100644 --- a/sunbeam-python/sunbeam/core/juju.py +++ b/sunbeam-python/sunbeam/core/juju.py @@ -1010,7 +1010,7 @@ def get_app_config(self, app: str, model: str) -> Mapping: if "not found" in e.stderr: raise ApplicationNotFoundException(f"App {app!r} not found") from e raise JujuException( - f"Failed to get config {config_value!r} from application {app!r}" + f"Failed to get config from application {app!r}" ) from e return config_value diff --git a/sunbeam-python/tests/unit/sunbeam/core/test_juju.py b/sunbeam-python/tests/unit/sunbeam/core/test_juju.py index 0822e4410..a20b54978 100644 --- a/sunbeam-python/tests/unit/sunbeam/core/test_juju.py +++ b/sunbeam-python/tests/unit/sunbeam/core/test_juju.py @@ -659,7 +659,7 @@ def test_get_app_config_not_found(jhelper, juju): def test_get_app_config_fail(jhelper, juju): juju.config.side_effect = jubilant.CLIError(1, "config", stderr="fail") with pytest.raises(jujulib.JujuException): - jhelper.get_secret("test-app", "test-model") + jhelper.get_app_config("test-app", "test-model") def test_jhelper_add_k8s_cloud(jhelper: jujulib.JujuHelper): From f5f4aa64edf73d6f199f1e0dcaee5aa0ac6cac0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADtor=20Zeni?= Date: Wed, 11 Nov 2026 16:23:38 -0300 Subject: [PATCH 2/2] fix(pro): detach machines from Ubuntu Pro before removing the charm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `sunbeam disable pro` removed the ubuntu-pro application, but the machines stayed attached to the Pro subscription and kept using seats. The charm only detaches a machine in config-changed, when its token goes from set to empty. Its stop, remove and juju-info relation hooks do nothing, so removing the application (which a single terraform apply with token="" does, because the resource count depends on the token) leaves every machine attached. Add a DetachUbuntuProStep that runs before the terraform removal. It empties the token through Juju and waits until every ubuntu-pro unit reports Blocked "No token configured". The application name and the token key are the same for the legacy ubuntu-advantage charm, so this also works on clusters deployed with it. If a unit does not detach within the timeout, disable fails and keeps the application, naming the units and the manual `pro detach` fallback. Running disable again is safe. Add JujuHelper.wait_subordinate_units_status. The existing waits only check a subordinate's application status, which turns blocked as soon as one unit does, so they cannot tell when all machines have detached. While the subordinate is related to the principal, a principal unit without a subordinate unit counts as pending, and a missing principal application raises JujuException, so the removal cannot run while a machine may still be attached. If disable fails after the detach, the token is empty in Juju but Terraform state still holds the old one: the provider only reads back non-default config values, and the charm's token default is "". A later `enable pro` with the same token would then change nothing. The enable step now compares the live token after the apply, sets it again if it differs and waits for the units to become active. set_app_config now always sends the values as YAML on stdin (`juju config --file -`) instead of as command-line arguments, so the token does not show in the process list or in jubilant's command log. Jira: OPEN-4916 Assisted-By: Claude Code (Claude Opus 5.5) Related-Bug: #2158218 Signed-off-by: Vítor Zeni --- sunbeam-python/sunbeam/core/juju.py | 112 ++++++++- .../sunbeam/features/pro/feature.py | 90 +++++++- .../tests/unit/sunbeam/core/test_juju.py | 212 +++++++++++++++++- .../tests/unit/sunbeam/features/test_pro.py | 168 +++++++++++++- 4 files changed, 572 insertions(+), 10 deletions(-) diff --git a/sunbeam-python/sunbeam/core/juju.py b/sunbeam-python/sunbeam/core/juju.py index e7c856843..0abbbe1d7 100644 --- a/sunbeam-python/sunbeam/core/juju.py +++ b/sunbeam-python/sunbeam/core/juju.py @@ -1017,13 +1017,19 @@ def get_app_config(self, app: str, model: str) -> Mapping: def set_app_config(self, app: str, model: str, config: dict) -> None: """Set charm config for an application. + The values are sent as YAML on stdin (`juju config --file -`), + not as command-line arguments, so they don't show in the process + list or in jubilant's command log. + :app: Name of the application. :model: Name of the model. :config: Dictionary of config key-value pairs to set. """ with self._model(model) as juju: try: - juju.config(app, config) + juju.cli( + "config", app, "--file", "-", stdin=yaml.safe_dump({app: config}) + ) except jubilant.CLIError as e: if "not found" in e.stderr: raise ApplicationNotFoundException(f"App {app!r} not found") from e @@ -1593,6 +1599,110 @@ def _wait_until_status(status: "jubilant.statustypes.Status"): timeout=timeout, ) + @staticmethod + def _pending_subordinate_units( + status: "jubilant.statustypes.Status", + principal_app: str, + subordinate_app: str, + expected_status: Collection[str], + expected_workload_status_message: Collection[str] | None = None, + ) -> dict[str, str]: + """Return the subordinate units not yet in the expected workload status. + + Subordinate units are listed under their principal unit, not under + the subordinate application, so they are collected from there. While + the subordinate is related to the principal, every principal unit + must have one; a principal unit without it is pending. + + :return: Mapping of unit name to its current "status: message". + :raises JujuException: if the principal application is not in the status. + """ + subordinate = status.apps.get(subordinate_app) + if subordinate is None or principal_app not in subordinate.subordinate_to: + # Not deployed, or not related: there are no subordinate units. + return {} + + principal = status.apps.get(principal_app) + if principal is None: + raise JujuException( + f"Application {principal_app!r} not found, cannot check the " + f"{subordinate_app!r} units" + ) + + pending: dict[str, str] = {} + for principal_name, unit in principal.units.items(): + subs = { + name: sub + for name, sub in unit.subordinates.items() + if name.startswith(f"{subordinate_app}/") + } + if not subs: + pending[principal_name] = f"no {subordinate_app} unit" + for name, sub in subs.items(): + current = sub.workload_status.current + message = sub.workload_status.message + if current not in expected_status or ( + expected_workload_status_message is not None + and message not in expected_workload_status_message + ): + pending[name] = f"{current}: {message}" if message else current + return pending + + def wait_subordinate_units_status( + self, + model: str, + principal_app: str, + subordinate_app: str, + status: list[str], + workload_status_message: list[str] | None = None, + timeout: int = 10 * 60, + ) -> None: + """Wait for every unit of a subordinate app to reach a workload status. + + The status of a subordinate application only reflects the most severe + status among its units, so every subordinate unit is checked instead. + While the subordinate is related to the principal, a principal unit + without the subordinate is waited for too. + + :model: Name of the model. + :principal_app: Principal application the subordinate is related to. + :subordinate_app: Subordinate application to check the units of. + :status: Accepted workload status values. + :workload_status_message: Accepted workload status messages, any if None. + :timeout: Waiting timeout in seconds. + :raises TimeoutError: naming the units not in the expected status. + :raises JujuException: if the principal application is missing. + """ + last_pending: dict[str, str] = {} + + def _ready(juju_status: "jubilant.statustypes.Status") -> bool: + nonlocal last_pending + last_pending = self._pending_subordinate_units( + juju_status, + principal_app, + subordinate_app, + status, + workload_status_message, + ) + return not last_pending + + LOG.debug( + "Waiting for %r units under %r to be %r with message %r", + subordinate_app, + principal_app, + status, + workload_status_message, + ) + with self._model(model) as juju: + try: + self._wait(_ready, juju, delay=MODEL_DELAY, timeout=timeout) + except TimeoutError as e: + units = ", ".join(f"{u} ({s})" for u, s in sorted(last_pending.items())) + raise TimeoutError( + f"Timed out after {timeout} seconds waiting for {subordinate_app} " + f"units: {units or 'status unknown'}" + ) from e + def is_k8s_model(self, model: str) -> bool: """Return True if the model is a k8s (CAAS) model. diff --git a/sunbeam-python/sunbeam/features/pro/feature.py b/sunbeam-python/sunbeam/features/pro/feature.py index 592310cd7..eabcb3fc8 100644 --- a/sunbeam-python/sunbeam/features/pro/feature.py +++ b/sunbeam-python/sunbeam/features/pro/feature.py @@ -16,7 +16,12 @@ from sunbeam.clusterd.client import Client from sunbeam.core.common import BaseStep, Result, ResultType, StepContext, run_plan from sunbeam.core.deployment import Deployment -from sunbeam.core.juju import JujuException, JujuHelper, JujuStepHelper +from sunbeam.core.juju import ( + ApplicationNotFoundException, + JujuException, + JujuHelper, + JujuStepHelper, +) from sunbeam.core.manifest import ( AddManifestStep, CharmManifest, @@ -44,6 +49,11 @@ UBUNTU_PRO_CHANNEL = "latest/stable" APP_TIMEOUT = 300 # 5 minutes, managing the application should be fast UNIT_TIMEOUT = 1200 # 15 minutes, adding / removing units can take a long time +PRINCIPAL_APPLICATION = "sunbeam-machine" +# The charm runs `pro detach` when its token is emptied, and then reports +# this message. Removing the application does not detach the machines. +DETACHED_MESSAGE = "No token configured" +DETACH_TIMEOUT = 600 # 10 minutes, one config-changed hook per machine class ProFeatureConfig(FeatureConfig): @@ -101,6 +111,27 @@ def run(self, context: StepContext) -> Result: except (JujuException, TerraformException, TerraformStateLockedException) as e: return Result(ResultType.FAILED, str(e)) + # Disable empties the token through Juju, outside Terraform. If disable + # failed after that, Terraform state still holds the old token, so the + # apply above changes nothing. Set the token again in that case. + try: + live_config = self.jhelper.get_app_config(APPLICATION, self.model) + if live_config.get("token") != self.token: + self.jhelper.set_app_config( + APPLICATION, self.model, {"token": self.token} + ) + # The units still report "No token configured" until the + # charm runs, so wait for them to attach first. + self.jhelper.wait_subordinate_units_status( + self.model, + PRINCIPAL_APPLICATION, + APPLICATION, + status=["active"], + timeout=APP_TIMEOUT, + ) + except (JujuException, TimeoutError) as e: + return Result(ResultType.FAILED, str(e)) + # Note(gboutry): application is in state unknown when it's deployed # without units try: @@ -130,6 +161,62 @@ def run(self, context: StepContext) -> Result: return Result(ResultType.COMPLETED) +class DetachUbuntuProStep(BaseStep, JujuStepHelper): + """Detach the machines from Ubuntu Pro before the charm is removed. + + The charm only detaches a machine when its token is emptied, so this + must run before the application is removed. + """ + + def __init__(self, jhelper: JujuHelper, model: str): + super().__init__( + "Detach Ubuntu Pro", "Detaching machines from Ubuntu Pro subscription" + ) + self.jhelper = jhelper + self.model = model + + def is_skip(self, context: StepContext) -> Result: + """Skip when the application is not deployed.""" + try: + self.jhelper.get_application(APPLICATION, self.model) + except ApplicationNotFoundException: + LOG.debug("%s is not deployed, nothing to detach", APPLICATION) + return Result(ResultType.SKIPPED) + except JujuException as e: + return Result(ResultType.FAILED, str(e)) + return Result(ResultType.COMPLETED) + + def run(self, context: StepContext) -> Result: + """Empty the token and wait for every unit to detach.""" + try: + self.jhelper.set_app_config(APPLICATION, self.model, {"token": ""}) + except ApplicationNotFoundException: + return Result(ResultType.COMPLETED) + except JujuException as e: + return Result(ResultType.FAILED, str(e)) + + try: + self.jhelper.wait_subordinate_units_status( + self.model, + PRINCIPAL_APPLICATION, + APPLICATION, + status=["blocked"], + workload_status_message=[DETACHED_MESSAGE], + timeout=DETACH_TIMEOUT, + ) + except TimeoutError as e: + return Result( + ResultType.FAILED, + f"{e}. {APPLICATION} was not removed. Run 'sunbeam disable pro' " + "again, or run 'sudo pro detach --assume-yes' on the machines " + "listed.", + ) + except JujuException as e: + return Result(ResultType.FAILED, str(e)) + + return Result(ResultType.COMPLETED) + + class DisableUbuntuProApplicationStep(BaseStep, JujuStepHelper): """Disable Ubuntu Pro application using Terraform.""" @@ -270,6 +357,7 @@ def run_disable_plans(self, deployment: Deployment, show_hints: bool): jhelper = JujuHelper(deployment.juju_controller) plan = [ TerraformInitStep(tfhelper), + DetachUbuntuProStep(jhelper, deployment.openstack_machines_model), DisableUbuntuProApplicationStep( deployment.get_client(), tfhelper, diff --git a/sunbeam-python/tests/unit/sunbeam/core/test_juju.py b/sunbeam-python/tests/unit/sunbeam/core/test_juju.py index a20b54978..2adfc9bfd 100644 --- a/sunbeam-python/tests/unit/sunbeam/core/test_juju.py +++ b/sunbeam-python/tests/unit/sunbeam/core/test_juju.py @@ -818,22 +818,38 @@ def test_get_available_charm_revisions_malformed_channel( def test_set_app_config(jhelper: jujulib.JujuHelper, juju): - """set_app_config passes config values to jubilant.""" - config = {"key1": "value1", "key2": 42} - jhelper.set_app_config("nova", "test-model", config) - juju.config.assert_called_once_with("nova", config) + """set_app_config sends the values as YAML on stdin, not as arguments.""" + config = {"token": "s3cr3t", "key2": 42, "key3": True} + + jhelper.set_app_config("ubuntu-pro", "test-model", config) + + juju.config.assert_not_called() + juju.cli.assert_called_once() + args = juju.cli.call_args.args + assert args == ("config", "ubuntu-pro", "--file", "-") + assert not any("s3cr3t" in arg for arg in args) + stdin = juju.cli.call_args.kwargs["stdin"] + assert yaml.safe_load(stdin) == {"ubuntu-pro": config} + + +def test_set_app_config_empty_value(jhelper: jujulib.JujuHelper, juju): + """An empty string is kept as a value, not dropped or turned into null.""" + jhelper.set_app_config("ubuntu-pro", "test-model", {"token": ""}) + + stdin = juju.cli.call_args.kwargs["stdin"] + assert yaml.safe_load(stdin) == {"ubuntu-pro": {"token": ""}} def test_set_app_config_app_not_found(jhelper: jujulib.JujuHelper, juju): """set_app_config raises ApplicationNotFoundException for missing app.""" - juju.config.side_effect = jubilant.CLIError(1, ["config"], "", "not found") + juju.cli.side_effect = jubilant.CLIError(1, ["config"], "", "not found") with pytest.raises(jujulib.ApplicationNotFoundException): jhelper.set_app_config("missing-app", "test-model", {"key": "val"}) def test_set_app_config_juju_error(jhelper: jujulib.JujuHelper, juju): """set_app_config raises JujuException for other CLI errors.""" - juju.config.side_effect = jubilant.CLIError(1, ["config"], "", "some error") + juju.cli.side_effect = jubilant.CLIError(1, ["config"], "", "some error") with pytest.raises(jujulib.JujuException): jhelper.set_app_config("nova", "test-model", {"key": "val"}) @@ -1433,3 +1449,187 @@ def test_snapshot_workload_status_mixed_present_and_absent(jhelper, status): status.apps["present"] = app_mock result = jhelper.snapshot_workload_status("test-model", ["present", "absent"]) assert result == {"present": "active"} + + +def _machine_app(charm: str, **extra) -> dict: + """Minimal machine-model application status, as `juju status` reports it.""" + return { + "charm": charm, + "charm-origin": "charmhub", + "charm-name": charm, + "charm-rev": 1, + "exposed": False, + **extra, + } + + +def _machine_status(subordinates_by_principal: dict) -> jubilant.statustypes.Status: + """Build a status where sunbeam-machine units carry ubuntu-pro subordinates. + + :subordinates_by_principal: principal unit -> {sub unit: (status, message)} + """ + units = { + principal: { + "machine": str(i), + "subordinates": { + name: {"workload-status": {"current": current, "message": message}} + for name, (current, message) in subs.items() + }, + } + for i, (principal, subs) in enumerate(subordinates_by_principal.items()) + } + return jubilant.statustypes.Status._from_dict( + { + "model": { + "name": "test-model", + "controller": "test-controller", + "cloud": "localhost", + "version": "3.6.29", + "type": "iaas", + "model-status": {}, + }, + "machines": {}, + "applications": { + "sunbeam-machine": _machine_app("sunbeam-machine", units=units), + "ubuntu-pro": _machine_app( + "ubuntu-pro", **{"subordinate-to": ["sunbeam-machine"]} + ), + }, + } + ) + + +DETACHED = ("blocked", "No token configured") + + +@pytest.mark.parametrize( + "subordinates, expected", + [ + ( + { + "sunbeam-machine/0": {"ubuntu-pro/0": DETACHED}, + "sunbeam-machine/1": {"ubuntu-pro/1": DETACHED}, + }, + {}, + ), + ( + { + "sunbeam-machine/0": {"ubuntu-pro/0": DETACHED}, + "sunbeam-machine/1": { + "ubuntu-pro/1": ("active", "Attached (esm-infra)") + }, + }, + {"ubuntu-pro/1": "active: Attached (esm-infra)"}, + ), + ( + # Blocked for another reason, e.g. a failed attach before the hook ran + {"sunbeam-machine/0": {"ubuntu-pro/0": ("blocked", "attach failed")}}, + {"ubuntu-pro/0": "blocked: attach failed"}, + ), + ( + # Other subordinates on the same machine are ignored + { + "sunbeam-machine/0": { + "ubuntu-pro/0": DETACHED, + "openstack-hypervisor/0": ("active", ""), + } + }, + {}, + ), + ( + # While related, every principal unit must have the subordinate + { + "sunbeam-machine/0": {"ubuntu-pro/0": DETACHED}, + "sunbeam-machine/1": {}, + }, + {"sunbeam-machine/1": "no ubuntu-pro unit"}, + ), + ], +) +def test_pending_subordinate_units(subordinates, expected): + status = _machine_status(subordinates) + + pending = jujulib.JujuHelper._pending_subordinate_units( + status, + "sunbeam-machine", + "ubuntu-pro", + ["blocked"], + ["No token configured"], + ) + + assert pending == expected + + +def test_pending_subordinate_units_missing_principal(): + status = _machine_status({"sunbeam-machine/0": {"ubuntu-pro/0": DETACHED}}) + status.apps.pop("sunbeam-machine") + + with pytest.raises(jujulib.JujuException, match="'sunbeam-machine' not found"): + jujulib.JujuHelper._pending_subordinate_units( + status, "sunbeam-machine", "ubuntu-pro", ["blocked"] + ) + + +@pytest.mark.parametrize("change", ["unrelated", "removed"]) +def test_pending_subordinate_units_without_units(change): + """No subordinate units exist when it is unrelated or removed.""" + status = _machine_status({"sunbeam-machine/0": {}}) + if change == "unrelated": + status.apps["ubuntu-pro"].subordinate_to.clear() + else: + status.apps.pop("ubuntu-pro") + + assert ( + jujulib.JujuHelper._pending_subordinate_units( + status, "sunbeam-machine", "ubuntu-pro", ["blocked"] + ) + == {} + ) + + +def test_wait_subordinate_units_status_ready(jhelper: jujulib.JujuHelper, juju): + status = _machine_status({"sunbeam-machine/0": {"ubuntu-pro/0": DETACHED}}) + + def _wait(ready, **kwargs): + assert ready(status) + + juju.wait.side_effect = _wait + + jhelper.wait_subordinate_units_status( + "test-model", + "sunbeam-machine", + "ubuntu-pro", + ["blocked"], + ["No token configured"], + timeout=60, + ) + + juju.wait.assert_called_once() + + +def test_wait_subordinate_units_status_timeout(jhelper: jujulib.JujuHelper, juju): + status = _machine_status( + { + "sunbeam-machine/0": {"ubuntu-pro/0": DETACHED}, + "sunbeam-machine/1": {"ubuntu-pro/1": ("active", "Attached (esm-infra)")}, + } + ) + + def _wait(ready, **kwargs): + assert not ready(status) + raise TimeoutError("jubilant timeout") + + juju.wait.side_effect = _wait + + with pytest.raises(TimeoutError) as exc: + jhelper.wait_subordinate_units_status( + "test-model", + "sunbeam-machine", + "ubuntu-pro", + ["blocked"], + ["No token configured"], + timeout=60, + ) + + assert "ubuntu-pro/1 (active: Attached (esm-infra))" in str(exc.value) + assert "ubuntu-pro/0" not in str(exc.value) diff --git a/sunbeam-python/tests/unit/sunbeam/features/test_pro.py b/sunbeam-python/tests/unit/sunbeam/features/test_pro.py index e7e1b03a9..20d555d62 100644 --- a/sunbeam-python/tests/unit/sunbeam/features/test_pro.py +++ b/sunbeam-python/tests/unit/sunbeam/features/test_pro.py @@ -3,13 +3,17 @@ import re from pathlib import Path -from unittest.mock import Mock +from unittest.mock import Mock, patch import pytest import yaml from sunbeam.core.common import ResultType -from sunbeam.core.juju import JujuException, ModelNotFoundException +from sunbeam.core.juju import ( + ApplicationNotFoundException, + JujuException, + ModelNotFoundException, +) from sunbeam.core.manifest import AddManifestStep, FeatureManifest, Manifest from sunbeam.core.terraform import ( TerraformException, @@ -19,6 +23,7 @@ ) from sunbeam.features.pro import feature as pro_feature from sunbeam.features.pro.feature import ( + DetachUbuntuProStep, DisableUbuntuProApplicationStep, EnableUbuntuProApplicationStep, ) @@ -38,6 +43,7 @@ def enable_step( test_token, ): """Enable Ubuntu Pro step instance for testing.""" + basic_jhelper.get_app_config.return_value = {"token": test_token} return EnableUbuntuProApplicationStep( basic_client, basic_tfhelper, @@ -106,6 +112,58 @@ def test_enable_model_lookup_failed( assert result.result_type == ResultType.FAILED assert result.message == str(error) + def test_enable_live_token_matches( + self, enable_step, basic_jhelper, test_model, step_context + ): + result = enable_step.run(step_context) + + basic_jhelper.get_app_config.assert_called_once_with("ubuntu-pro", test_model) + basic_jhelper.set_app_config.assert_not_called() + basic_jhelper.wait_subordinate_units_status.assert_not_called() + assert result.result_type == ResultType.COMPLETED + + def test_enable_resets_token_emptied_by_failed_disable( + self, enable_step, basic_jhelper, test_model, test_token, step_context + ): + basic_jhelper.get_app_config.return_value = {"token": ""} + + result = enable_step.run(step_context) + + basic_jhelper.set_app_config.assert_called_once_with( + "ubuntu-pro", test_model, {"token": test_token} + ) + basic_jhelper.wait_subordinate_units_status.assert_called_once_with( + test_model, + "sunbeam-machine", + "ubuntu-pro", + status=["active"], + timeout=pro_feature.APP_TIMEOUT, + ) + assert result.result_type == ResultType.COMPLETED + + def test_enable_reset_token_timed_out( + self, enable_step, basic_jhelper, step_context + ): + basic_jhelper.get_app_config.return_value = {"token": ""} + basic_jhelper.wait_subordinate_units_status.side_effect = TimeoutError( + "ubuntu-pro/0 (blocked: attach failed)" + ) + + result = enable_step.run(step_context) + + basic_jhelper.wait_application_ready.assert_not_called() + assert result.result_type == ResultType.FAILED + assert result.message == "ubuntu-pro/0 (blocked: attach failed)" + + def test_enable_read_config_failed(self, enable_step, basic_jhelper, step_context): + basic_jhelper.get_app_config.side_effect = JujuException("config failed") + + result = enable_step.run(step_context) + + basic_jhelper.set_app_config.assert_not_called() + assert result.result_type == ResultType.FAILED + assert result.message == "config failed" + def test_enable_waiting_timed_out(self, enable_step, basic_jhelper, step_context): basic_jhelper.wait_application_ready.side_effect = TimeoutError("timed out") @@ -149,6 +207,112 @@ def test_enable_blocked_without_stderr( assert result.message == "No token configured" +class TestDetachUbuntuProStep: + @pytest.fixture + def detach_step(self, basic_jhelper, test_model): + """Detach Ubuntu Pro step instance for testing.""" + return DetachUbuntuProStep(basic_jhelper, test_model) + + def test_is_skip_app_deployed(self, detach_step, step_context): + result = detach_step.is_skip(step_context) + assert result.result_type == ResultType.COMPLETED + + def test_is_skip_app_missing(self, detach_step, basic_jhelper, step_context): + basic_jhelper.get_application.side_effect = ApplicationNotFoundException( + "missing" + ) + + result = detach_step.is_skip(step_context) + + assert result.result_type == ResultType.SKIPPED + + def test_is_skip_status_failed(self, detach_step, basic_jhelper, step_context): + basic_jhelper.get_application.side_effect = JujuException("status failed") + + result = detach_step.is_skip(step_context) + + assert result.result_type == ResultType.FAILED + assert result.message == "status failed" + + def test_detach(self, detach_step, basic_jhelper, test_model, step_context): + result = detach_step.run(step_context) + + basic_jhelper.set_app_config.assert_called_once_with( + "ubuntu-pro", test_model, {"token": ""} + ) + basic_jhelper.wait_subordinate_units_status.assert_called_once_with( + test_model, + "sunbeam-machine", + "ubuntu-pro", + status=["blocked"], + workload_status_message=["No token configured"], + timeout=pro_feature.DETACH_TIMEOUT, + ) + assert result.result_type == ResultType.COMPLETED + + def test_detach_app_gone_meanwhile(self, detach_step, basic_jhelper, step_context): + basic_jhelper.set_app_config.side_effect = ApplicationNotFoundException( + "missing" + ) + + result = detach_step.run(step_context) + + basic_jhelper.wait_subordinate_units_status.assert_not_called() + assert result.result_type == ResultType.COMPLETED + + def test_detach_set_config_failed(self, detach_step, basic_jhelper, step_context): + basic_jhelper.set_app_config.side_effect = JujuException("config failed") + + result = detach_step.run(step_context) + + basic_jhelper.wait_subordinate_units_status.assert_not_called() + assert result.result_type == ResultType.FAILED + assert result.message == "config failed" + + def test_detach_timed_out(self, detach_step, basic_jhelper, step_context): + basic_jhelper.wait_subordinate_units_status.side_effect = TimeoutError( + "Timed out waiting for ubuntu-pro units: ubuntu-pro/1 (active: Attached)" + ) + + result = detach_step.run(step_context) + + assert result.result_type == ResultType.FAILED + assert "ubuntu-pro/1 (active: Attached)" in result.message + assert "was not removed" in result.message + assert "pro detach" in result.message + + def test_detach_wait_failed(self, detach_step, basic_jhelper, step_context): + basic_jhelper.wait_subordinate_units_status.side_effect = JujuException( + "Application 'sunbeam-machine' not found" + ) + + result = detach_step.run(step_context) + + assert result.result_type == ResultType.FAILED + assert result.message == "Application 'sunbeam-machine' not found" + + +class TestRunDisablePlans: + def test_detach_runs_before_removal(self): + deployment = Mock() + with ( + patch.object(pro_feature, "Snap"), + patch.object(pro_feature, "JujuHelper"), + patch.object(pro_feature, "run_plan") as run_plan, + patch.object(pro_feature.click, "echo"), + ): + feature = pro_feature.ProFeature() + feature._manifest = Mock() + feature.run_disable_plans(deployment, show_hints=False) + + plan = run_plan.call_args.args[0] + assert [type(step) for step in plan] == [ + TerraformInitStep, + DetachUbuntuProStep, + DisableUbuntuProApplicationStep, + ] + + class TestDisableUbuntuProApplicationStep: @pytest.fixture def disable_step(