Skip to content

Move BMC and BIOS Version CRDs unit test to go mock server#829

Merged
afritzler merged 5 commits into
mainfrom
testmockVersions
Apr 24, 2026
Merged

Move BMC and BIOS Version CRDs unit test to go mock server#829
afritzler merged 5 commits into
mainfrom
testmockVersions

Conversation

@nagadeesh-nagaraja
Copy link
Copy Markdown
Contributor

@nagadeesh-nagaraja nagadeesh-nagaraja commented Apr 23, 2026

Fixes #828

Summary by CodeRabbit

  • New Features

    • Realistic firmware upgrade simulation with step-by-step task progression, failure and success sequences, and automatic application of provided image URIs to firmware versions.
    • New endpoint behavior to create and monitor asynchronous upgrade tasks with reset capability.
  • Chores

    • Test infrastructure updated to use multiple mock servers and to reset per-server upgrade/task state during teardown.

@nagadeesh-nagaraja nagadeesh-nagaraja self-assigned this Apr 23, 2026
@nagadeesh-nagaraja nagadeesh-nagaraja requested a review from a team as a code owner April 23, 2026 12:14
@nagadeesh-nagaraja nagadeesh-nagaraja changed the title Testmock versions Move BMC and BIOS Version CRDs unit test to go mock server Apr 23, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 23, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b35c46a4-a7e5-4bd0-82a0-7f9ee4ee8bcd

📥 Commits

Reviewing files that changed from the base of the PR and between a0ead8a and 01b4030.

📒 Files selected for processing (3)
  • bmc/mock/server/server.go
  • internal/controller/biossettings_controller_test.go
  • internal/controller/bmcsettings_controller_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/controller/biossettings_controller_test.go
  • bmc/mock/server/server.go

📝 Walkthrough

Walkthrough

Adds mock Redfish firmware-upgrade task resources and implements asynchronous upgrade progression in the Go mock server, refactors RedfishLocalBMC upgrade/version methods to shared helpers and updates task parsing, and migrates test suite to use a slice of mock servers with per-server reset hooks.

Changes

Cohort / File(s) Summary
Upgrade Mock Data
bmc/mock/server/data/TaskService/Tasks/upgrade/index.json, bmc/mock/server/data/TaskService/Tasks/upgrade/steps.json, bmc/mock/server/data/TaskService/Tasks/upgrade/steps-fail.json
Adds a new Redfish Task mock and two step-sequence templates (success and failure) describing TaskState/TaskStatus/PercentComplete progression.
Mock Server Upgrade Logic
bmc/mock/server/server.go
Replaces static 202 behavior for SimpleUpdate with request parsing, embedded task/template loading, goroutine-driven async step progression guarded by a generation counter, dynamic resource version updates on completion, and adds ResetUpgradeTask(...).
Client Refactor: Upgrade Flow
bmc/redfish_local.go
Removes cached Get*Version methods and old mock progression; consolidates BIOS/BMC upgrade/get-task logic into shared helpers with local callbacks for request construction, Location/@odata.id task extraction, and task parsing; updates mock task URI constant.
Test Suite: multi-server support
internal/controller/suite_test.go
Replaces global mockServer with mockServers []*server.MockServer; creates and starts one MockServer per address or a single-element slice for default case; fixes runnable startup capture.
Test Cleanups: BIOS & BMC
internal/controller/biossettings_controller_test.go, internal/controller/biossettingsset_controller_test.go, internal/controller/biosversion_controller_test.go, internal/controller/biosversionset_controller_test.go, internal/controller/bmcsettings_controller_test.go, internal/controller/bmcsettingsset_controller_test.go, internal/controller/bmcversion_controller_test.go, internal/controller/bmcversionset_controller_test.go
Replaces global/fixture reset calls with per-server resets (mockServers[0] or iterating mockServers) and removes reliance on bmc.UnitTestMockUps global reset hooks; adjusts assertions to read from mockServers[0] where applicable.

Sequence Diagram(s)

sequenceDiagram
    actor Client
    participant MockServer
    participant TaskSvc as Task Service
    participant Resources as System/Manager Resources

    Client->>MockServer: POST SimpleUpdate (ImageURI, Targets)
    activate MockServer
    MockServer->>TaskSvc: Load initial task template (`index.json`)
    MockServer->>Client: 202 + Location (task monitor URI)
    deactivate MockServer

    note over MockServer: launch goroutine (generation guarded)

    loop async progression
        MockServer->>TaskSvc: Merge next step from `steps.json` / `steps-fail.json`
        MockServer->>MockServer: Update stored override
    end

    alt Completed terminal step
        MockServer->>Resources: Resolve RelatedItem targets
        MockServer->>Resources: Write ImageURI to BIOS/BMC version fields
        MockServer->>MockServer: Record updated resources
    else Exception terminal step
        note over MockServer: No resource version update
    end

    Client->>MockServer: GET task monitor URI (poll)
    activate MockServer
    MockServer->>Client: Return current task state JSON
    deactivate MockServer
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

enhancement, size/XL, area/metal-automation

Suggested reviewers

  • afritzler
  • xkonni
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The pull request description is minimal and only references the linked issue without elaborating on the changes made or their scope. Expand the description to include the proposed changes, such as the refactored mock server setup, removal of global state, and key test file updates for better clarity.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and clearly describes the main change: refactoring BMC and BIOS Version unit tests to use a Go mock server, which aligns with the primary objective of the pull request.
Linked Issues check ✅ Passed The pull request successfully addresses issue #828 by refactoring unit tests to use a Go mock server, removing global state dependencies, and improving test isolation through mock server instances.
Out of Scope Changes check ✅ Passed All changes are within scope: mock server enhancements support upgrade task progression, mock data files enable version testing, and test files are updated to use the new mock server infrastructure.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 testmockVersions

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/controller/bmcsettings_controller_test.go (1)

86-95: ⚠️ Potential issue | 🟡 Minor

Reset BMC mock state after cleanup, not before it.

Line 87 clears the mock while the BMC/server and any failed-spec leftovers may still reconcile. A later reconcile can reapply settings after the reset, leaving stale mock state for the next test. Move this after EnsureCleanState().

Suggested teardown ordering
-		mockServers[0].ResetBMCSettings("BMC")
-
 		Expect(k8sClient.Delete(ctx, bmc)).To(Succeed())
 		Eventually(UpdateStatus(server, func() {
 			server.Status.State = metalv1alpha1.ServerStateAvailable
 		})).To(Succeed())
 		Expect(k8sClient.Delete(ctx, server)).To(Succeed())
 		Expect(k8sClient.Delete(ctx, bmcSecret)).To(Succeed())
 		EnsureCleanState()
+		mockServers[0].ResetBMCSettings("BMC")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/controller/bmcsettings_controller_test.go` around lines 86 - 95, The
ResetBMCSettings call is happening too early and can be undone by later
reconciles; move mockServers[0].ResetBMCSettings("BMC") to the end of the
AfterEach teardown, after EnsureCleanState() so the mock is reset only once all
Kubernetes deletes and the EnsureCleanState() check complete; update the
AfterEach block that contains ResetBMCSettings, EnsureCleanState, UpdateStatus,
and k8sClient.Delete calls accordingly.
internal/controller/biossettings_controller_test.go (1)

78-83: ⚠️ Potential issue | 🟡 Minor

Move the mock BIOS reset after Kubernetes cleanup.

These AfterEach blocks reset the Redfish mock before deleting resources and before EnsureCleanState(). If a spec fails early, remaining BIOSSettings/controllers can reconcile after the reset and write state back into the mock, leaking into the next spec. Move the reset after EnsureCleanState().

Suggested teardown ordering
-		mockServers[0].ResetBIOSSettings(path.Base(server.Spec.SystemURI))
-
 		Expect(k8sClient.Delete(ctx, bmcSecret)).To(Succeed())
 		Expect(k8sClient.Delete(ctx, server)).To(Succeed())
 		EnsureCleanState()
+		mockServers[0].ResetBIOSSettings(path.Base(server.Spec.SystemURI))

Apply the same ordering to the other two AfterEach blocks in this file.

Also applies to: 1058-1064, 1387-1392

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/controller/biossettings_controller_test.go` around lines 78 - 83,
The teardown resets the Redfish mock (mockServers[0].ResetBIOSSettings(...))
before cleaning up k8s resources and calling EnsureCleanState(), which can allow
controllers to reconcile and write back into the mock when a spec fails; move
the mockServers[0].ResetBIOSSettings(...) call to after EnsureCleanState() and
after deleting bmcSecret and server (the k8sClient.Delete calls) inside the
AfterEach blocks (including the other two AfterEach blocks that mirror this
pattern) so the cluster is fully cleaned before the mock is reset.
🧹 Nitpick comments (1)
internal/controller/biosversion_controller_test.go (1)

76-81: Prefer a full upgrade-task reset in teardown.

These AfterEach blocks depend on the local server.Spec.SystemURI being populated. If a spec fails before the server object is refreshed, the scoped reset may miss the in-flight task. Since set tests already use the no-arg reset, consider using ResetUpgradeTask() here too.

Suggested teardown reset
-		mockServers[0].ResetUpgradeTask(server.Spec.SystemURI)
+		mockServers[0].ResetUpgradeTask()

Also applies to: 476-481

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/controller/biosversion_controller_test.go` around lines 76 - 81, In
the AfterEach teardown in biosversion_controller_test.go replace the scoped
reset call that uses server.Spec.SystemURI with the no-arg reset to ensure any
in-flight upgrade tasks are cleared even if server.Spec wasn't populated;
specifically update the mockServers[0].ResetUpgradeTask(server.Spec.SystemURI)
calls (present in the AfterEach blocks around the test and again at lines
~476-481) to mockServers[0].ResetUpgradeTask() so the teardown performs a full
reset.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@bmc/mock/server/server.go`:
- Around line 369-374: handleSimpleUpdate currently ignores json.Unmarshal
errors, allowing malformed payloads to be treated as valid; update the function
(handleSimpleUpdate) to check the error returned from json.Unmarshal(body, &req)
and if non-nil write an appropriate HTTP error (e.g., http.Error with status 400
Bad Request) and return instead of proceeding to accept the request; ensure the
error path logs or includes the unmarshal error context so tests and callers see
the failure.

---

Outside diff comments:
In `@internal/controller/biossettings_controller_test.go`:
- Around line 78-83: The teardown resets the Redfish mock
(mockServers[0].ResetBIOSSettings(...)) before cleaning up k8s resources and
calling EnsureCleanState(), which can allow controllers to reconcile and write
back into the mock when a spec fails; move the
mockServers[0].ResetBIOSSettings(...) call to after EnsureCleanState() and after
deleting bmcSecret and server (the k8sClient.Delete calls) inside the AfterEach
blocks (including the other two AfterEach blocks that mirror this pattern) so
the cluster is fully cleaned before the mock is reset.

In `@internal/controller/bmcsettings_controller_test.go`:
- Around line 86-95: The ResetBMCSettings call is happening too early and can be
undone by later reconciles; move mockServers[0].ResetBMCSettings("BMC") to the
end of the AfterEach teardown, after EnsureCleanState() so the mock is reset
only once all Kubernetes deletes and the EnsureCleanState() check complete;
update the AfterEach block that contains ResetBMCSettings, EnsureCleanState,
UpdateStatus, and k8sClient.Delete calls accordingly.

---

Nitpick comments:
In `@internal/controller/biosversion_controller_test.go`:
- Around line 76-81: In the AfterEach teardown in biosversion_controller_test.go
replace the scoped reset call that uses server.Spec.SystemURI with the no-arg
reset to ensure any in-flight upgrade tasks are cleared even if server.Spec
wasn't populated; specifically update the
mockServers[0].ResetUpgradeTask(server.Spec.SystemURI) calls (present in the
AfterEach blocks around the test and again at lines ~476-481) to
mockServers[0].ResetUpgradeTask() so the teardown performs a full reset.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b7b462d3-6431-4ab4-92e0-6268433ad604

📥 Commits

Reviewing files that changed from the base of the PR and between 66996aa and a0ead8a.

📒 Files selected for processing (14)
  • bmc/mock/server/data/TaskService/Tasks/upgrade/index.json
  • bmc/mock/server/data/TaskService/Tasks/upgrade/steps-fail.json
  • bmc/mock/server/data/TaskService/Tasks/upgrade/steps.json
  • bmc/mock/server/server.go
  • bmc/redfish_local.go
  • internal/controller/biossettings_controller_test.go
  • internal/controller/biossettingsset_controller_test.go
  • internal/controller/biosversion_controller_test.go
  • internal/controller/biosversionset_controller_test.go
  • internal/controller/bmcsettings_controller_test.go
  • internal/controller/bmcsettingsset_controller_test.go
  • internal/controller/bmcversion_controller_test.go
  • internal/controller/bmcversionset_controller_test.go
  • internal/controller/suite_test.go

Comment thread bmc/mock/server/server.go Outdated
@afritzler afritzler added the enhancement New feature or request label Apr 24, 2026
@afritzler afritzler merged commit 2abe9d7 into main Apr 24, 2026
20 checks passed
@afritzler afritzler deleted the testmockVersions branch April 24, 2026 08:59
@github-project-automation github-project-automation Bot moved this to Done in Roadmap Apr 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

BMCVersion and BIOSVersion unit testing to move to go mock server

3 participants