Skip to content

ROSAENG-61173 | test: complete delete cluster command coverage#3372

Closed
olucasfreitas wants to merge 1 commit into
masterfrom
ROSAENG-61173
Closed

ROSAENG-61173 | test: complete delete cluster command coverage#3372
olucasfreitas wants to merge 1 commit into
masterfrom
ROSAENG-61173

Conversation

@olucasfreitas

@olucasfreitas olucasfreitas commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

PR Summary

Complete the remaining coverage for rosa delete cluster by adding command-level tests for the legacy delete flow and a small refactor that makes the command body testable without changing CLI behavior.

Detailed Description of the Issue

PR #3298 added helper coverage for handleClusterDelete() and buildCommands(), but the actual rosa delete cluster command flow was still untested. still required coverage for confirmation handling, best-effort output, STS cleanup messaging, uninstall log watching, and wrapper-level error propagation.

This change extracts a testable runWithRuntime(...) helper in cmd/dlt/cluster/cmd.go and adds focused Ginkgo coverage for the remaining command behaviors while preserving the existing Run: run entrypoint, flags, and user-facing flow.

Related Issues and PRs

Type of Change

  • feat - adds a new user-facing capability.
  • fix - resolves an incorrect behavior or bug.
  • docs - updates documentation only.
  • style - formatting or naming changes with no logic impact.
  • refactor - code restructuring with no behavior change.
  • test - adds or updates tests only.
  • chore - maintenance work (tooling, housekeeping, non-product code).
  • build - changes build system, packaging, or dependencies for build output.
  • ci - changes CI pipelines, jobs, or automation workflows.
  • perf - improves performance without changing intended behavior.

Previous Behavior

cmd/dlt/cluster had helper-level coverage, but the full command flow remained untested. Important behaviors like confirmation decline, --best-effort, STS cleanup output, --watch, and wrapper-level error handling were still gaps in Phase 2B.

Behavior After This Change

The delete-cluster command now has focused command-level coverage for:

  • non-STS happy path with uninstall-log suggestion output
  • STS happy path with operator role output, OIDC provider output, and cleanup commands
  • STS clusters with no operator roles
  • --best-effort warning and passthrough behavior
  • confirmation decline
  • already-uninstalling clusters
  • GetClusterState and DeleteCluster errors
  • --watch invoking uninstall logs while restoring the region deprecation warning flag

The command shape, flags, and user-facing behavior remain unchanged.

How to Test (Step-by-Step)

Preconditions

  • Go toolchain compatible with the version required by go.mod
  • If your shell exports GOTOOLCHAIN=local, use GOTOOLCHAIN=auto for the commands below

Test Steps

  1. GOTOOLCHAIN=auto make fmt
  2. GOTOOLCHAIN=auto go test ./cmd/dlt/cluster/... -count=1
  3. GOTOOLCHAIN=auto make lint
  4. GOTOOLCHAIN=auto make rosa
  5. GOTOOLCHAIN=auto make test

Expected Results

  • The cmd/dlt/cluster package tests pass
  • Lint passes with no issues
  • The rosa binary builds successfully
  • The full repo test suite passes

Proof of the Fix

  • Screenshots: N/A
  • Videos: N/A
  • Logs/CLI output:
    • GOTOOLCHAIN=auto go test ./cmd/dlt/cluster/... -count=1 passed
    • GOTOOLCHAIN=auto make lint passed
    • GOTOOLCHAIN=auto make rosa passed
    • GOTOOLCHAIN=auto make test passed
    • git push -u origin HEAD passed repo pre-push checks (format, build, lint, changed-files coverage, unit and integration tests)
  • Other artifacts:
    • cmd/dlt/cluster/cmd.go now uses a thin run() wrapper plus runWithRuntime(...)
    • cmd/dlt/cluster/cmd_test.go now covers the remaining Phase 2B command scenarios

Breaking Changes

  • No breaking changes
  • Yes, this PR introduces a breaking change (describe impact and migration plan below)

Breaking Change Details / Migration Plan

N/A

Developer Verification Checklist

  • Commit subject/title follows [JIRA-TICKET] | [TYPE]: <MESSAGE>.
  • PR description clearly explains both what changed and why.
  • Relevant Jira/GitHub issues and related PRs are linked.
  • make install-hooks has been run in this clone.
  • Tests were added/updated where appropriate.
  • I manually tested the change.
  • make test passes.
  • make lint passes.
  • make rosa passes.
  • Documentation or repo-local agent guidance was added/updated where appropriate.
  • Any risk, limitation, or follow-up work is documented.

Summary by CodeRabbit

  • Bug Fixes
    • Improved cluster deletion error handling and command exit behavior.
    • Added clearer guidance for monitoring uninstall logs when live watching is not enabled.
    • Preserved region warning settings while displaying uninstall logs.
    • Improved handling of confirmation prompts, already-uninstalling clusters, failed state checks, and forbidden deletion requests.
  • Tests
    • Expanded coverage for cluster deletion, cleanup guidance, warning behavior, log watching, and error scenarios.

@openshift-ci openshift-ci Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 14, 2026
@openshift-ci

openshift-ci Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The cluster deletion command now creates and cleans up its runtime in a wrapper, delegates deletion behavior to runWithRuntime, and reports returned errors consistently. Uninstall-log execution is extracted into runUninstallLogs, while watch mode continues to manage the region deprecation warning and non-watch mode prints guidance. Tests configure interactive and argument state and cover confirmation, best-effort warnings, STS cleanup messaging, watch behavior, existing uninstalling state, and error propagation.

Possibly related PRs

  • openshift/rosa#3367: Both changes modify the rosa dlt cluster deletion flow in cmd/dlt/cluster/cmd.go.

Suggested reviewers: ericponvelle


Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error, 1 warning)

Check name Status Explanation Resolution
No-Sensitive-Data-In-Logs ❌ Error The delete flow logs AWS account ID, role ARNs, and OIDC endpoint URLs in user-visible output, which can expose customer data/internal hostnames. Mask or omit account IDs, ARNs, and OIDC URLs from normal output; if needed, keep them only in debug logs with redaction.
Test Structure And Quality ⚠️ Warning cmd/dlt/cluster/cmd_test.go uses bare assertions, mixes multiple behaviors in specs (watch+flag restore), and the bestEffort test doesn’t actually verify request passthrough. Split multi-behavior specs, add meaningful assertion messages, and assert DeleteCluster receives bestEffort via a spy/request inspection; add AfterEach/DeferCleanup for shared globals.
✅ Passed checks (13 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Stable And Deterministic Test Names ✅ Passed All Ginkgo titles are static strings; no generated, time-based, or interpolated values appear in test names.
Microshift Test Compatibility ✅ Passed The added Ginkgo tests are command-level unit tests and only use OCM mocks; no MicroShift-blocked APIs, namespaces, or skip guards are needed.
Single Node Openshift (Sno) Test Compatibility ✅ Passed The added Ginkgo tests are command-level mocks using a fake runtime; they never inspect node counts/topology or require multi-node scheduling, so no SNO risk.
Topology-Aware Scheduling Compatibility ✅ Passed The PR only changes cmd/dlt/cluster CLI code and tests; no deployment manifests, operator code, controllers, or scheduling constraints were added.
Ote Binary Stdout Contract ✅ Passed No stdout writes appear in main/init/TestMain/RunSpecs setup; the only fmt.Print is inside runWithRuntime/test code, which is not process-level.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed The added Ginkgo tests are command-level and use local test fixtures only; I found no hardcoded IPv4 assumptions or external network dependencies.
No-Weak-Crypto ✅ Passed Touched cluster command files contain no weak crypto primitives, custom crypto, or secret/token comparisons; searches found no matches.
Container-Privileges ✅ Passed PR only changes cmd/dlt/cluster Go code/tests; no container/K8s manifests or privilege settings like privileged, hostPID, hostNetwork, hostIPC, or allowPrivilegeEscalation appear in the diff.
Title check ✅ Passed The title is specific, concise, and matches the main change: added delete-cluster command coverage.
Description check ✅ Passed The PR description follows the template and includes summary, issue context, related links, change type, testing, proof, and checklist items.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ROSAENG-61173

Comment @coderabbitai help to get the list of available commands.

@openshift-ci

openshift-ci Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: olucasfreitas

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ci openshift-ci Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Jul 14, 2026
@olucasfreitas

Copy link
Copy Markdown
Contributor Author

Closing: PR was incorrectly opened from the main repo instead of the fork. Will reopen from the fork.

@olucasfreitas
olucasfreitas deleted the ROSAENG-61173 branch July 14, 2026 16:35

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
cmd/dlt/cluster/cmd_test.go (1)

35-42: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Restore package-level test seams with DeferCleanup.

confirmDelete and runUninstallLogs remain stubbed after each spec, allowing later package tests to inherit behavior based on execution order. Capture and restore these variables, along with modified global flags, in cleanup.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/dlt/cluster/cmd_test.go` around lines 35 - 42, Update the BeforeEach
setup to register DeferCleanup callbacks that restore confirmDelete,
runUninstallLogs, and the modified global flags to their original values after
each spec. Capture each original value before overriding it, while preserving
the existing per-spec test setup and isolation.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/dlt/cluster/cmd_test.go`:
- Around line 84-107: Strengthen the test around runWithRuntime so the mocked
delete request inspects its payload or query and asserts that bestEffort is
true, rather than accepting any request. Keep the existing warning, success, and
uninstall-output assertions, and ensure the test fails if DeleteCluster does not
receive the flag.

In `@cmd/dlt/cluster/cmd.go`:
- Around line 110-112: Update the error handling around handleClusterDelete to
wrap the returned error with descriptive cluster-deletion operation context
using %w, preserving the original error for unwrapping.

---

Nitpick comments:
In `@cmd/dlt/cluster/cmd_test.go`:
- Around line 35-42: Update the BeforeEach setup to register DeferCleanup
callbacks that restore confirmDelete, runUninstallLogs, and the modified global
flags to their original values after each spec. Capture each original value
before overriding it, while preserving the existing per-spec test setup and
isolation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: a3a5eaaf-84b7-4dc0-954e-feb42ff85d87

📥 Commits

Reviewing files that changed from the base of the PR and between e4eecdd and 85ab16a.

📒 Files selected for processing (2)
  • cmd/dlt/cluster/cmd.go
  • cmd/dlt/cluster/cmd_test.go

Comment on lines +84 to +107
It("prints the best-effort warning and passes the flag through", func() {
clusterReady := test.MockCluster(func(c *cmv1.ClusterBuilder) {
c.State(cmv1.ClusterStateReady)
c.AWS(cmv1.NewAWS().STS(cmv1.NewSTS()))
})
t.SetCluster(clusterId, clusterReady)
args.bestEffort = true

statusBody := fmt.Sprintf(`{
"kind": "ClusterStatus",
"id": "%s",
"state": "ready"
}`, clusterId)
t.ApiServer.AppendHandlers(RespondWithJSON(http.StatusOK, statusBody))
t.ApiServer.AppendHandlers(RespondWithJSON(
http.StatusOK, test.FormatClusterList([]*cmv1.Cluster{clusterReady})))
t.ApiServer.AppendHandlers(RespondWithJSON(http.StatusOK, ""))

stdout, stderr, err := test.RunWithOutputCaptureAndArgv(runWithRuntime, t.RosaRuntime, Cmd, &argv)
Expect(err).NotTo(HaveOccurred())
Expect(stderr).To(ContainSubstring("best effort"))
Expect(stderr).To(ContainSubstring("certain resources may be left behind"))
Expect(stdout).To(ContainSubstring("will start uninstalling"))
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that bestEffort reaches the delete request.

This test only verifies warning output and a successful response; the mock handler accepts the request regardless of the flag. Inspect the request in the handler or use a spy so the test fails unless DeleteCluster receives bestEffort=true.

As per path instructions, “Flag weak tests that only restate implementation or changes that weaken existing assertions.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/dlt/cluster/cmd_test.go` around lines 84 - 107, Strengthen the test
around runWithRuntime so the mocked delete request inspects its payload or query
and asserts that bestEffort is true, rather than accepting any request. Keep the
existing warning, success, and uninstall-output assertions, and ensure the test
fails if DeleteCluster does not receive the flag.

Source: Path instructions

Comment thread cmd/dlt/cluster/cmd.go
Comment on lines 110 to +112
err := handleClusterDelete(r, cluster, clusterKey, args.bestEffort)
if err != nil {
r.Reporter.Errorf("%s", err)
os.Exit(1)
return err

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Wrap deletion errors with operation context.

Returning the raw SDK error makes the command failure harder to diagnose. Preserve it with %w while identifying the failed cluster operation.

Proposed fix
 	err := handleClusterDelete(r, cluster, clusterKey, args.bestEffort)
 	if err != nil {
-		return err
+		return fmt.Errorf("failed to delete cluster %q: %w", clusterKey, err)
 	}

As per coding guidelines, “Wrap returned errors with context using %w; do not drop the original error.”

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
err := handleClusterDelete(r, cluster, clusterKey, args.bestEffort)
if err != nil {
r.Reporter.Errorf("%s", err)
os.Exit(1)
return err
err := handleClusterDelete(r, cluster, clusterKey, args.bestEffort)
if err != nil {
return fmt.Errorf("failed to delete cluster %q: %w", clusterKey, err)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/dlt/cluster/cmd.go` around lines 110 - 112, Update the error handling
around handleClusterDelete to wrap the returned error with descriptive
cluster-deletion operation context using %w, preserving the original error for
unwrapping.

Source: Coding guidelines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. dco-signoff: yes do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant