Skip to content

test(plugin): raise register.go coverage - #2195

Merged
hami-robot[bot] merged 6 commits into
Project-HAMi:masterfrom
adity1raut:test/register-nvml-coverage
Aug 7, 2026
Merged

test(plugin): raise register.go coverage #2195
hami-robot[bot] merged 6 commits into
Project-HAMi:masterfrom
adity1raut:test/register-nvml-coverage

Conversation

@adity1raut

@adity1raut adity1raut commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

/kind feature

What this PR does / why we need it:

  • Adds tests for pkg/device-plugin/nvidiadevice/nvinternal/plugin/register.go:
  • GetNumaNode's two deterministic error branches (PCI info lookup failure,
    and the sysfs numa_node read failure — the code strips the PCI domain
    prefix before building the path, so it never matches a real sysfs
    directory).
  • A test pinning down getAPIDevices' existing panic-on-no-driver behavior
    via recover().
    Which issue(s) this PR fixes:
    Fixes #

Special notes for your reviewer:

Does this PR introduce a user-facing change?:

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of NVIDIA driver initialization failures to avoid incorrect cleanup.
    • Improved NUMA node detection when PCI or system information is unavailable.
    • Ensured proper cleanup after successful NVIDIA initialization.
  • Tests

    • Added coverage for NUMA detection failure scenarios.
    • Added validation for device discovery during NVIDIA initialization failures and successes.
    • Added checks confirming resources are released correctly.

@github-actions github-actions Bot removed the kind/feature new function label Jul 29, 2026
@hami-robot hami-robot Bot added the size/M label Jul 29, 2026
@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds an injectable NVML initialization hook. Shutdown runs only after successful initialization. Tests cover NVML failure and success paths, PCI information errors, and missing sysfs NUMA data.

Changes

NVML plugin tests

Layer / File(s) Summary
NVML initialization handling
pkg/device-plugin/nvidiadevice/nvinternal/plugin/register.go, pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go
getAPIDevices() uses an injectable initializer and defers shutdown after successful initialization. Tests verify panic on initialization failure and shutdown with an empty, non-nil device slice on success.
NUMA lookup failure coverage
pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go
Tests PCI information failures and missing sysfs numa_node files. Both cases return hasNode=false and node=0.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested labels: enhancement

Suggested reviewers: dsfans2014, ouyangluwei163, shouren

Poem

A rabbit checks the NVML gate,
Tests NUMA paths before it waits.
Failed starts panic on cue,
Successful starts shut down too.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding tests to increase coverage for register.go.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai
coderabbitai Bot requested a review from Shouren July 29, 2026 10:57

@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: 1

🤖 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 `@pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go`:
- Around line 123-138: Make getAPIDevices use an injectable NVML initialization
function or interface, defaulting to the real nvml.Init implementation in
production. Update TestGetAPIDevices_PanicsWithoutNVMLDriver to inject a stub
that returns an explicit NVML initialization error, then verify getAPIDevices
panics without depending on host GPU hardware.
🪄 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 Plus

Run ID: e79360be-4b95-40ab-b672-790ea955b2b2

📥 Commits

Reviewing files that changed from the base of the PR and between c8fdb12 and 9c4fd1b.

📒 Files selected for processing (1)
  • pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go

Comment thread pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go Outdated
Comment thread pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go Outdated
@mesutoezdil

Copy link
Copy Markdown
Contributor

no ai assistance disclosure is present. if any ai tool was used, it must be disclosed per CONTRIBUTING.md: https://github.com/Project-HAMi/HAMi/blob/master/CONTRIBUTING.md#ai-assistance-notice

@adity1raut

Copy link
Copy Markdown
Contributor Author

no ai assistance disclosure is present. if any ai tool was used, it must be disclosed per CONTRIBUTING.md: https://github.com/Project-HAMi/HAMi/blob/master/CONTRIBUTING.md#ai-assistance-notice

I am updating this in the description

@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: 1

Caution

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

⚠️ Outside diff range comments (1)
pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go (1)

134-149: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Verify that the panic comes from the NVML initialization branch.

The deferred recover accepts any panic. plugin.Devices() runs before nvmlInit() in register.go Lines [95-97]. If that call or the mock panics, this test passes without exercising the intended branch. Record that the injected function was called and assert it before accepting the panic.

Proposed test adjustment
 func TestGetAPIDevices_PanicsOnNVMLInitFailure(t *testing.T) {
+	called := false
 	origInit := nvmlInit
-	nvmlInit = func() nvml.Return { return nvml.ERROR_LIBRARY_NOT_FOUND }
+	nvmlInit = func() nvml.Return {
+		called = true
+		return nvml.ERROR_LIBRARY_NOT_FOUND
+	}
 	defer func() { nvmlInit = origInit }()

 	// ...

 	defer func() {
+		if !called {
+			t.Fatal("nvmlInit was not called")
+		}
 		if r := recover(); r == nil {
 			t.Fatal("expected getAPIDevices to panic when nvml.Init fails")
 		}
 	}()
🤖 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 `@pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go` around
lines 134 - 149, Update TestGetAPIDevices_PanicsOnNVMLInitFailure to track
whether the injected nvmlInit function runs, then require that flag to be set
before accepting the recovered panic. Keep the existing panic assertion, but
fail if recovery occurs without nvmlInit having been called so the test
specifically validates the NVML initialization branch.
🤖 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 `@pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go`:
- Around line 105-114: Update the mock.Device fixture in the GetNumaNode test so
its NVML BusId resolves to an impossible PCI address, such as 00000000:ff:ff.0,
ensuring the sysfs lookup is missing on every host. Preserve the existing
coverage of domain-prefix trimming without relying on the host’s actual PCI
devices.

---

Outside diff comments:
In `@pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go`:
- Around line 134-149: Update TestGetAPIDevices_PanicsOnNVMLInitFailure to track
whether the injected nvmlInit function runs, then require that flag to be set
before accepting the recovered panic. Keep the existing panic assertion, but
fail if recovery occurs without nvmlInit having been called so the test
specifically validates the NVML initialization branch.
🪄 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 Plus

Run ID: 19941657-f0ad-4f49-9b04-0cbb51a5da2e

📥 Commits

Reviewing files that changed from the base of the PR and between 9c4fd1b and 5a1cd13.

📒 Files selected for processing (2)
  • pkg/device-plugin/nvidiadevice/nvinternal/plugin/register.go
  • pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go

Comment thread pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go Outdated
@codecov

codecov Bot commented Jul 31, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Flag Coverage Δ
unittests 63.56% <100.00%> (+0.18%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...-plugin/nvidiadevice/nvinternal/plugin/register.go 24.84% <100.00%> (+10.90%) ⬆️

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread pkg/device-plugin/nvidiadevice/nvinternal/plugin/register.go Outdated
@adity1raut

Copy link
Copy Markdown
Contributor Author

@archlitchi PTAL. This PR ready to merged

Comment thread pkg/device-plugin/nvidiadevice/nvinternal/plugin/register.go Outdated
Comment thread pkg/device-plugin/nvidiadevice/nvinternal/plugin/register_test.go Outdated
@archlitchi

Copy link
Copy Markdown
Member

/assign

Add tests for GetNumaNode's two deterministic error branches (PCI
info lookup failure, and the numa_node sysfs read failure that always
occurs since the domain prefix is stripped before building the path)
and a test that pins down getAPIDevices' existing panic-on-no-driver
behavior via recover().

getAPIDevices, RegisterInAnnotation, and most of WatchAndRegister's
active branch remain uncovered: getAPIDevices calls the real
nvml.Init() directly (not an injectable interface), which fails and
panics on any machine without an NVIDIA driver - this one included -
so exercising their actual logic isn't possible without either real
GPU hardware or refactoring nvml access behind an interface, which is
out of scope for this test-only change.

Signed-off-by: Aditya Raut <araut7798@gmail.com>
nvml.Shutdown() was deferred before checking whether nvml.Init()
succeeded. On a host with no NVML library at all, Init fails
gracefully, but the deferred Shutdown() still runs during the
panic(0) unwind and crashes the whole process with a dynamic symbol
lookup error, since the library was never loaded. Defer Shutdown
only after a successful Init.

Also route Init through a package-level nvmlInit var so
TestGetAPIDevices_PanicsOnNVMLInitFailure can simulate an init
failure directly instead of depending on the test host's driver
state, and fix the numa_node mock/comment to use NVML's real
8-digit-domain BusId format per review feedback.

Signed-off-by: Aditya Raut <araut7798@gmail.com>
The only existing getAPIDevices test forces nvmlInit to fail, so the
defer nvml.Shutdown() moved after the success check in 5a1cd13 was
never exercised, leaving codecov/patch failing on that line. Add a
success-path test that stubs both nvmlInit and nvml.Shutdown (both are
reassignable package vars) so it never touches the real, unloaded NVML
library on this host.

Signed-off-by: Aditya Raut <araut7798@gmail.com>
Signed-off-by: Aditya Raut <araut7798@gmail.com>
archlitchi asked for unnecessary comments to be removed from
register.go and register_test.go, with method/test doc comments
trimmed to one sentence describing what the code does. Also fixes a
comment above defer nvml.Shutdown() that was missing its lead-in
clause ("succeeded: calling it after a failed Init crashes the
process...") and read as a sentence fragment.

Signed-off-by: Aditya Raut <araut7798@gmail.com>
Project-HAMi#2313 added a LimitSet flag that FitQuota now gates on instead of
Limit != 0, and updated TestFitResourceQuota's fixture accordingly,
but missed three sibling tests in the same file that also build
device.Quota directly: TestFitResourceQuotaNonNvidia,
TestFitResourceQuotaCountsEveryDevice, and
TestFitResourceQuotaAscendMemoryFactor. Their fixtures defaulted to
LimitSet: false, so FitQuota treated the configured limits as unset
and admitted every pod, failing the denial assertions in all three
tests on current master.

Set LimitSet: true on the five affected fixture entries to match what
AddQuota produces, mirroring the fix already applied to
TestFitResourceQuota.

Signed-off-by: Aditya Raut <araut7798@gmail.com>

@archlitchi archlitchi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

/lgtm

@hami-robot hami-robot Bot added the lgtm label Aug 7, 2026
@hami-robot

hami-robot Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: adity1raut, archlitchi

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants