Skip to content

Add tests to improve code coverage in oshi-common - #3239

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:improve-test-coverage
May 9, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:improve-test-coverage

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Add 49 new tests across 4 test classes targeting low-coverage areas identified via Codecov API analysis.

Coverage Improvements (local JaCoCo, Linux)

File Before After Delta
PrivilegedUtil.java 49.5% 91.1% +41.6%
LinuxCgroupInfo.java 64.1% 84.0% +19.9%
LinuxOSFileStore.java 36.5% 96.2% +59.7%
Sysfs.java 47.2% 71.7% +24.5%

New Test Classes

  • PrivilegedUtilEscalationTest (14 tests): Tests privileged file reading escalation paths including buildCatCommand, getKeyValueMapFromFilePrivileged, and allowlist/prefix configuration interactions.

  • LinuxCgroupInfoV1DispatchTest (17 tests): Tests cgroup v1 limit/quota/period edge cases and v2 edge cases (empty files, single-token cpu.max, zero values mapping to unlimited).

  • LinuxOSFileStoreTest (3 tests): Tests updateAttributes() with null-statvfs fallback and zero-totalSpace JVM File fallback paths.

  • SysfsExtendedTest (15 tests): Exercises all Sysfs query methods including biosVersion revision suffix logic and null/empty return paths.

Verification

  • All 717 tests in oshi-common pass (703 successful, 14 skipped for non-Linux platforms)
  • spotless:apply ✅
  • checkstyle:check ✅
  • forbiddenapis:check ✅
  • javadoc:javadoc ✅

Summary by CodeRabbit

  • Tests
    • Enhanced test coverage for Linux cgroup parsing (v1/v2) including limit/usage edge cases and dispatch behavior.
    • Added Linux file store tests to validate attribute updates and fallback handling for root mounts.
    • Expanded privileged-file-access tests covering escalation, allowlist parsing, and read behaviors.
    • Added Sysfs/BIOS/product/vendor verification tests to validate system information queries.

@coderabbitai

coderabbitai Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6a31eb9a-650d-4ddf-a105-78f37d9036a9

📥 Commits

Reviewing files that changed from the base of the PR and between d2a5d3b and b9e3e67.

📒 Files selected for processing (4)
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoV1DispatchTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxOSFileStoreTest.java
  • oshi-common/src/test/java/oshi/util/PrivilegedUtilEscalationTest.java
  • oshi-common/src/test/java/oshi/util/driver/linux/SysfsExtendedTest.java
🚧 Files skipped from review as they are similar to previous changes (4)
  • oshi-common/src/test/java/oshi/util/driver/linux/SysfsExtendedTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoV1DispatchTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxOSFileStoreTest.java
  • oshi-common/src/test/java/oshi/util/PrivilegedUtilEscalationTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)

📝 Walkthrough

Walkthrough

This PR introduces four new Linux-focused test classes that exercise cgroup v1/v2 parsing dispatch, file store attribute fallback paths, privileged file read escalation scenarios, and sysfs system metadata queries, validating correct numeric parsing, special-case mappings, fallback behavior, and output constraints.

Changes

Linux System Test Coverage Expansion

Layer / File(s) Summary
Cgroup Dispatch Tests
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoV1DispatchTest.java
Tests for cgroup v1 quota/period, memory/PID limits, and CPU/memory usage parsing with special-case handling where 0 maps to UNLIMITED or defaults; v2 edge cases for cpu.max, memory.max, pids.max, cpu.stat, and empty usage files.
File Store Fallback Tests
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxOSFileStoreTest.java
Tests for OSFileStore.updateAttributes() with null queryStatvfs returns and zero-value space arrays, verifying JVM fallback path yields positive totalSpace; also validates root mount metadata fields and space metrics.
Privileged Utility Escalation Tests
oshi-common/src/test/java/oshi/util/PrivilegedUtilEscalationTest.java
Tests for readFilePrivileged, readAllBytesPrivileged, and helper methods (getKeyValueMapFromFilePrivileged, getStringFromFilePrivileged) with allowlist validation, escalation paths, error reporting, and glob pattern matching via isFileAllowed.
Sysfs Query Tests
oshi-common/src/test/java/oshi/util/driver/linux/SysfsExtendedTest.java
Tests for system vendor, product, serial, UUID, and BIOS-related queries, asserting null-or-non-empty behavior with revision-dependent formatting validation for BIOS version and conditional checks for BIOS release date.

Estimated Code Review Effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly Related PRs

  • oshi/oshi#3225: Introduces LinuxCgroupInfo v1/v2 parsing implementation directly exercised by the new cgroup dispatch tests in this PR.
  • oshi/oshi#3119: Fixes flaky PrivilegedUtil test and cache clearing behavior; related to the PrivilegedUtilEscalationTest setup/teardown and cache management strategy.
  • oshi/oshi#3140: Related to Linux class relocations (oshi.software.common) used by the new Linux-focused tests.

Poem

🐰 Four test files hop along the way,
Cgroup parsing gets its Linux day,
File stores fallback, privileges escalate,
Sysfs queries validate—no data to abate! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.77% 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 summarizes the main change: adding tests to improve code coverage in the oshi-common module, which is exactly what the changeset delivers.
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.

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

✨ 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 and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
oshi-common/src/test/java/oshi/util/driver/linux/SysfsExtendedTest.java (1)

29-29: 💤 Low value

Prefer idiomatic Hamcrest not(emptyString()) over .isEmpty() assertions.

The pattern assertThat(x.isEmpty(), is(false)) is used in 11 places. The idiomatic Hamcrest equivalent is cleaner and produces better failure messages.

♻️ Example refactor (same pattern applies to all similar sites)
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.emptyString;

-    assertThat(vendor.isEmpty(), is(false));
+    assertThat(vendor, not(emptyString()));

Also applies to: 37-37, 55-55, 64-64, 72-72, 80-80, 88-88, 96-96, 111-111, 119-119, 127-127, 144-144

🤖 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 `@oshi-common/src/test/java/oshi/util/driver/linux/SysfsExtendedTest.java` at
line 29, Replace assertions of the form assertThat(X.isEmpty(), is(false)) with
the idiomatic Hamcrest form assertThat(X, not(emptyString())); specifically
update the vendor assertion in SysfsExtendedTest (and the other listed places)
to use assertThat(vendor, not(emptyString())), and ensure the Hamcrest static
matchers not and emptyString are imported so the tests compile and produce
better failure messages.
🤖 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
`@oshi-common/src/test/java/oshi/software/common/os/linux/LinuxOSFileStoreTest.java`:
- Around line 54-63: The test loop in LinuxOSFileStoreTest iterates over
"stores" and breaks when store.getMount() == "/" but never asserts that such a
root mount was actually found, allowing a false-positive pass; add a boolean
flag (e.g., foundRoot) set when "/".equals(store.getMount()) and after the loop
assert that foundRoot is true to ensure the root mount was located before
relying on updateAttributes assertions; apply the same pattern to the other two
similar loops referenced (the blocks around the store.updateAttributes() checks
at the other two locations).

In `@oshi-common/src/test/java/oshi/util/driver/linux/SysfsExtendedTest.java`:
- Around line 54-56: Remove the redundant null-check assertion inside the
guarded block: delete the assertion assertThat(serial, is(notNullValue())) that
follows the if (serial != null) guard in SysfsExtendedTest so only the
meaningful assertion remains (e.g., assertThat(serial.isEmpty(), is(false))).
This keeps the null guard and the non-empty check for the variable serial and
avoids the tautological assertion.

In `@oshi-common/src/test/java/oshi/util/PrivilegedUtilEscalationTest.java`:
- Around line 96-97: The three escalation-path tests in
PrivilegedUtilEscalationTest (testReadFilePrivilegedEscalationPath,
testReadAllBytesPrivilegedEscalationPath,
testReadAllBytesPrivilegedEscalationWithReportError) call
testFile.toFile().setReadable(false) but ignore the boolean result and don't
restore permissions; update each test to assert the precondition and guard
cleanup by: call setReadable(false) and use assumeFalse(returnValue) or
assumeTrue(!returnValue) to skip when unreadable could not be enforced, then
wrap the escalation test logic in a try-finally and in finally restore
readability with testFile.toFile().setReadable(true) so permission is restored;
reference the methods testFile.toFile().setReadable and the three test method
names when making the changes.

---

Nitpick comments:
In `@oshi-common/src/test/java/oshi/util/driver/linux/SysfsExtendedTest.java`:
- Line 29: Replace assertions of the form assertThat(X.isEmpty(), is(false))
with the idiomatic Hamcrest form assertThat(X, not(emptyString())); specifically
update the vendor assertion in SysfsExtendedTest (and the other listed places)
to use assertThat(vendor, not(emptyString())), and ensure the Hamcrest static
matchers not and emptyString are imported so the tests compile and produce
better failure messages.
🪄 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 UI

Review profile: CHILL

Plan: Pro

Run ID: fecd6788-de19-455b-8e1a-4c33589abf50

📥 Commits

Reviewing files that changed from the base of the PR and between 714f122 and d2a5d3b.

📒 Files selected for processing (4)
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoV1DispatchTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxOSFileStoreTest.java
  • oshi-common/src/test/java/oshi/util/PrivilegedUtilEscalationTest.java
  • oshi-common/src/test/java/oshi/util/driver/linux/SysfsExtendedTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (12)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🔇 Additional comments (2)
oshi-common/src/test/java/oshi/software/common/os/linux/LinuxCgroupInfoV1DispatchTest.java (1)

29-135: Strong coverage additions for v1/v2 cgroup dispatch edge cases.

These tests are focused, deterministic, and validate the key fallback/unlimited mappings and parsing edge cases called out in the PR goals. Nice improvement.

oshi-common/src/test/java/oshi/util/driver/linux/SysfsExtendedTest.java (1)

100-105: No action needed—test assertion correctly matches implementation behavior.

The queryBiosVendor() implementation intentionally returns null when the file contains non-empty content and returns an empty string when the file is empty or missing. This inverted logic (unusual though it may be) means the method can never return a non-empty string, so the test assertion anyOf(is(nullValue()), is("")) will always pass correctly and the test will not fail on real hardware. The comment accurately describes this behavior.

Add 49 new tests across 4 test classes targeting low-coverage areas
identified via Codecov analysis:

- PrivilegedUtilEscalationTest: Tests privileged file reading escalation
  paths including buildCatCommand, getKeyValueMapFromFilePrivileged,
  and allowlist/prefix configuration interactions.

- LinuxCgroupInfoV1DispatchTest: Tests cgroup v1 limit/quota/period
  edge cases and v2 edge cases (empty files, single-token cpu.max,
  zero values mapping to unlimited).

- LinuxOSFileStoreTest: Tests updateAttributes() with null-statvfs
  fallback and zero-totalSpace JVM File fallback paths.

- SysfsExtendedTest: Exercises all Sysfs query methods including
  biosVersion revision suffix logic and null/empty return paths.

Coverage improvements (local JaCoCo):
- PrivilegedUtil: 49.5% -> 91.1%
- LinuxCgroupInfo: 64.1% -> 84.0%
- LinuxOSFileStore: 36.5% -> 96.2%
- Sysfs: 47.2% -> 71.7%
@dbwiddis
dbwiddis force-pushed the improve-test-coverage branch from d2a5d3b to b9e3e67 Compare May 9, 2026 01:32
@dbwiddis
dbwiddis merged commit 2240ba9 into oshi:master May 9, 2026
16 of 18 checks passed
@dbwiddis
dbwiddis deleted the improve-test-coverage branch May 9, 2026 01:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant