Skip to content

Add updateAttributes() comparison tests for all native APIs - #3288

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:add-updateAttributes-comparison-tests
May 23, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:add-updateAttributes-comparison-tests

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 23, 2026 •

Copy link
Copy Markdown
Member

Add JNA vs FFM comparison tests exercising updateAttributes() on all interfaces that define it: OSProcess, OSThread, HWDiskStore, NetworkIF, OSFileStore, and PowerSource.

Each test snapshots values, sleeps briefly, calls updateAttributes() on both JNA and FFM instances, then verifies:

  • updateAttributes() returns true
  • Monotonically nondecreasing counters have not decreased (kernel/user time, disk reads/writes, network bytes sent/received)
  • Static values remain consistent between JNA and FFM

Also narrows the Linux disk test skip: instead of disabling the entire diskStores() test on Linux, only skip the partition name comparison which is affected by the JNA UdevDevice.getSysname() bug fixed in java-native-access/jna#1715 (not yet released past 5.18.1).

Motivated by #3287 where patch coverage showed updateAttributes() was not being exercised.

Summary by CodeRabbit

  • Tests
    • Restored disk-store comparisons on Linux with platform-conditional expectations for partition equality.
    • Expanded attribute-update validation to processes, threads, disk stores, network interfaces, file stores, and power sources.
    • Added assertions that update calls succeed; counters/times are monotonic/nondecreasing; identity, total/max capacity remain equal after refresh.
    • Verifies usable/remaining capacities are non-negative and handles empty or unmatched platform data gracefully.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

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: d1105784-641a-40a1-989d-81d75f5c889b

📥 Commits

Reviewing files that changed from the base of the PR and between 145fdea and 7bdf5d9.

📒 Files selected for processing (4)
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-core/src/test/java/oshi/hardware/platform/shared/PowerSourceTest.java
  • oshi-core/src/test/java/oshi/software/os/shared/FileSystemTest.java
  • oshi-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.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). (13)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: JMH Benchmarks, macos-latest
🔇 Additional comments (5)
oshi-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.java (2)

193-203: Current-thread refresh check can still silently pass on failure.

Line 198 gates all assertions on currentThread.updateAttributes() and allows a no-op pass when it returns false; this is the same unresolved concern already raised in earlier review feedback.


52-52: LGTM!

Also applies to: 176-184

oshi-core/src/test/java/oshi/hardware/platform/shared/PowerSourceTest.java (1)

40-46: LGTM!

oshi-core/src/test/java/oshi/software/os/shared/FileSystemTest.java (1)

66-72: LGTM!

oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)

48-48: LGTM!

Also applies to: 266-271, 412-432, 434-459, 461-492, 494-529, 531-557, 559-579


📝 Walkthrough

Walkthrough

Removes a global Linux skip for disk store tests, moves partition equality behind a non-Linux guard, and adds updateAttributes() refresh tests for process, thread, disk, network, file store, and power source with monotonicity and consistency assertions.

Changes

updateAttributes() Test Coverage Expansion

Layer / File(s) Summary
Disk store test platform-conditional refactoring
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
Removes @DisabledIf("isLinux") and the DisabledIf import; adds oshi.util.Util import; runs partition equality assertion only on non-Linux platforms.
Enhanced process updateAttributes testing
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
currentProcessUpdateAttributes() snapshots kernel/user times, sleeps, calls updateAttributes() on both implementations, and asserts times are nondecreasing after refresh and identity fields align.
Thread updateAttributes test
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
Adds currentThreadUpdateAttributes() which snapshots thread times for JNA/FFM, sleeps, calls updateAttributes(), asserts JNA/FFM boolean result agreement, and—if updated—asserts nondecreasing times.
Disk store counters updateAttributes test
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
Adds diskStoreUpdateAttributes() to match disks by name, snapshot read/write counters, sleep, refresh, and assert counters are nondecreasing; requires at least one match.
Network interface updateAttributes test
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
Adds networkIfUpdateAttributes() to match interfaces by name, snapshot bytes sent/received, sleep, refresh, and assert nondecreasing counters; requires at least one match.
File store updateAttributes test
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
Adds fileStoreUpdateAttributes() to match file stores by mount, sleep, refresh, assert total space equality across implementations and nonnegative usable space; requires at least one match.
Power source updateAttributes test
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
Adds powerSourceUpdateAttributes() that handles empty-power-sources or refreshes matched power sources and asserts maxCapacity remains equal after update.
Core PowerSource post-update assertions
oshi-core/src/test/java/oshi/hardware/platform/shared/PowerSourceTest.java
Asserts ps.updateAttributes() returns true, getMaxCapacity() is unchanged, and remaining capacity percent is nonnegative after update.
Core FileSystem updateAttributes assertions
oshi-core/src/test/java/oshi/software/os/shared/FileSystemTest.java
For each OSFileStore, captures totalSpace, asserts updateAttributes() succeeds, verifies totalSpace unchanged, and usableSpace >= 0 after update.
Core OperatingSystem process/thread tests
oshi-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.java
Adds oshi.util.Util import; process test sleeps, calls proc.updateAttributes(), and asserts kernel/user times are nondecreasing; threads test exercises currentThread.updateAttributes() when supported.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • oshi/oshi#3150: Prior benchmark test-suite changes that this PR extends and refines.
  • oshi/oshi#3195: Adds updateAttributes() fast-path work for OSFileStore/OSProcessHandle that these tests exercise.
  • oshi/oshi#3211: Overlaps edits to NativeComparisonTest.java, including updateAttributes() assertions and Linux-conditional logic.

Poem

🐰 I watched counters creep and timers climb,

I sniffed the tests in quiet benchmark time,
No blanket Linux skip—just guarded checks,
I hopped through disks, nets, threads, and specs,
A floppy-nosed cheer for updateAttributes' fine.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% 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 directly and clearly summarizes the main change: adding updateAttributes() comparison tests across all native APIs mentioned in the changeset.
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.

@codecov

codecov Bot commented May 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 75.59%. Comparing base (08592d3) to head (7bdf5d9).
⚠️ Report is 5 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3288      +/-   ##
============================================
+ Coverage     74.83%   75.59%   +0.75%     
  Complexity       76       76              
============================================
  Files           410      410              
  Lines         15901    15826      -75     
  Branches       2534     2518      -16     
============================================
+ Hits          11899    11963      +64     
+ Misses         2544     2393     -151     
- Partials       1458     1470      +12     
Flag Coverage Δ
linux 40.09% <ø> (+0.24%) ⬆️
macos 40.91% <ø> (+0.40%) ⬆️
windows 48.62% <ø> (+0.43%) ⬆️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

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

🤖 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-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`:
- Around line 465-467: The new tests in NativeComparisonTest silently skip cases
when a matching entity isn't found; add a matched counter in each test loop that
checks paired JNA/FFM updateAttributes() calls (increment matched each time you
actually call updateAttributes() on a matching pair in the loop inside methods
that reference updateAttributes()), and after the loop assert matched > 0 so the
test fails if nothing was exercised; for the power-source test that currently
returns early when JNA power sources are empty, change that branch to assert
that both JNA and FFM power source lists are empty before returning (i.e., only
return early if both sides are empty), otherwise proceed to find matches and
increment/assert matched > 0.
- Around line 447-448: The test unconditionally asserts
jnaThread.updateAttributes() and ffmThread.updateAttributes() are true, but
OSThread#updateAttributes() is not implemented on macOS (MacOSThread uses the
default false), so modify NativeComparisonTest to detect macOS (e.g., via a
Platform/OS check or System.getProperty("os.name") contains "Mac") and guard
these assertions: on macOS assertFalse for jnaThread.updateAttributes() and
ffmThread.updateAttributes(), otherwise keep the existing assertTrue;
alternatively skip the checks on macOS—locate the assertions in
NativeComparisonTest and adjust the logic around jnaThread and ffmThread
accordingly, referencing OSThread#updateAttributes(), MacOSThread, and
MacOperatingSystem#getCurrentThread.
🪄 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: 2981d7ec-0958-4d4c-8637-1f7a13fd9b5d

📥 Commits

Reviewing files that changed from the base of the PR and between 41285de and 2deee08.

📒 Files selected for processing (1)
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🔇 Additional comments (2)
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (2)

265-270: LGTM!


405-431: LGTM!

@dbwiddis
dbwiddis force-pushed the add-updateAttributes-comparison-tests branch from 2deee08 to bb81991 Compare May 23, 2026 18:41

@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.

🧹 Nitpick comments (1)
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)

569-577: ⚡ Quick win

Consider matching power sources by name for robustness.

The test iterates by index, assuming JNA and FFM return power sources in the same order. For consistency with the disk/network/file store update tests and to guard against implementation-specific ordering variations, consider matching power sources by name (e.g., building a Map<String, PowerSource> keyed by getName()).

That said, the static powerSources() test at lines 225-241 also uses index-based iteration, which suggests ordering is consistent in practice.

♻️ Optional refactor to match by name
     `@Test`
     void powerSourceUpdateAttributes() throws InterruptedException {
         List<PowerSource> jna = jnaHal.getPowerSources();
         List<PowerSource> ffm = ffmHal.getPowerSources();
         if (jna.isEmpty()) {
             assertThat(ffm).as("both JNA and FFM should be empty").isEmpty();
             return;
         }
         assertThat(ffm).hasSameSizeAs(jna);
+        Map<String, PowerSource> ffmByName = ffm.stream()
+                .collect(Collectors.toMap(PowerSource::getName, Function.identity()));
         // Delay before refresh
         Thread.sleep(100);
-        for (int i = 0; i < jna.size(); i++) {
-            PowerSource j = jna.get(i);
-            PowerSource f = ffm.get(i);
+        int matched = 0;
+        for (PowerSource j : jna) {
+            PowerSource f = ffmByName.get(j.getName());
+            if (f == null) {
+                continue;
+            }
+            matched++;
             assertThat(j.updateAttributes()).as("JNA powerSource %s updateAttributes", j.getName()).isTrue();
             assertThat(f.updateAttributes()).as("FFM powerSource %s updateAttributes", f.getName()).isTrue();
             // After refresh, names should still match and capacity should be valid
             assertThat(f.getName()).isEqualTo(j.getName());
             assertThat(f.getMaxCapacity()).as("FFM maxCapacity(%s)", f.getName()).isEqualTo(j.getMaxCapacity());
         }
+        assertThat(matched).as("matched power sources").isGreaterThan(0);
     }
🤖 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-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`
around lines 569 - 577, The test currently iterates jna and ffm lists by index
which assumes identical ordering; instead, build a Map<String, PowerSource> for
one of the providers keyed by getName() (e.g., mapJna by j.getName()), then
iterate the other list (ffm) and for each f use mapJna.get(f.getName()) to find
the matching PowerSource, assert the match exists, call updateAttributes() on
both PowerSource instances, and compare names and getMaxCapacity() as before
(refer to methods PowerSource.getName(), PowerSource.updateAttributes(),
PowerSource.getMaxCapacity() and variables jna/ffm/powerSources()).
🤖 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.

Nitpick comments:
In `@oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`:
- Around line 569-577: The test currently iterates jna and ffm lists by index
which assumes identical ordering; instead, build a Map<String, PowerSource> for
one of the providers keyed by getName() (e.g., mapJna by j.getName()), then
iterate the other list (ffm) and for each f use mapJna.get(f.getName()) to find
the matching PowerSource, assert the match exists, call updateAttributes() on
both PowerSource instances, and compare names and getMaxCapacity() as before
(refer to methods PowerSource.getName(), PowerSource.updateAttributes(),
PowerSource.getMaxCapacity() and variables jna/ffm/powerSources()).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e29898e5-2d1a-43d0-925c-94303c46e943

📥 Commits

Reviewing files that changed from the base of the PR and between 2deee08 and bb81991.

📒 Files selected for processing (1)
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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). (13)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
🔇 Additional comments (6)
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (6)

265-270: LGTM!


405-431: LGTM!


433-458: LGTM!


460-491: LGTM!


493-528: LGTM!


530-556: LGTM!

@dbwiddis
dbwiddis force-pushed the add-updateAttributes-comparison-tests branch 2 times, most recently from 8e66642 to 145fdea Compare May 23, 2026 19:24

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

🤖 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-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`:
- Around line 551-553: The assertion in NativeComparisonTest that
j.getTotalSpace() is strictly greater than 0 can fail for pseudo/virtual file
stores; relax the lower bound by changing the assertion on getTotalSpace() (used
in the test methods around NativeComparisonTest where j and f represent file
stores) to allow zero (e.g., assertGreaterThanOrEqualTo(0L) or compare with
f.getTotalSpace() only), and ensure the subsequent assertion comparing
f.getTotalSpace() to j.getTotalSpace() still verifies equality using
getTotalSpace() so real mismatches are caught.

In `@oshi-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.java`:
- Around line 193-201: Capture pre-update counters from os.getCurrentThread()
into local variables (e.g., preKernel = currentThread.getKernelTime(), preUser =
currentThread.getUserTime()), then call currentThread.updateAttributes(); if it
returns false assert the runtime OS is macOS by checking
System.getProperty("os.name") contains "mac" to allow the unimplemented case;
otherwise assert updateAttributes() returned true and that post-update
currentThread.getKernelTime() and getUserTime() are >= their respective
pre-update values and >= 0. Use the symbols OperatingSystem os, OSThread
currentThread, getCurrentThread(), updateAttributes(), getKernelTime(), and
getUserTime() to locate and modify the test.
🪄 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: 649e765f-78a4-4505-8a48-414ea7e0ecff

📥 Commits

Reviewing files that changed from the base of the PR and between 8e66642 and 145fdea.

📒 Files selected for processing (4)
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-core/src/test/java/oshi/hardware/platform/shared/PowerSourceTest.java
  • oshi-core/src/test/java/oshi/software/os/shared/FileSystemTest.java
  • oshi-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.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). (10)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🔇 Additional comments (5)
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (2)

48-48: LGTM!

Also applies to: 266-271, 412-459, 461-529, 559-578


531-550: LGTM!

Also applies to: 554-557

oshi-core/src/test/java/oshi/software/os/shared/FileSystemTest.java (1)

66-72: LGTM!

oshi-core/src/test/java/oshi/hardware/platform/shared/PowerSourceTest.java (1)

40-46: LGTM!

oshi-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.java (1)

52-52: LGTM!

Also applies to: 176-184

Comment on lines +193 to +201
// Test updateAttributes on current thread (not implemented on macOS)
OSThread currentThread = os.getCurrentThread();
assertThat("Current thread shouldn't be null", currentThread, is(notNullValue()));
if (currentThread.updateAttributes()) {
assertThat("Thread kernel time should be 0 or higher after update", currentThread.getKernelTime(),
is(greaterThanOrEqualTo(0L)));
assertThat("Thread user time should be 0 or higher after update", currentThread.getUserTime(),
is(greaterThanOrEqualTo(0L)));
}

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Strengthen the current-thread update test to avoid silent pass and validate refresh behavior.

If updateAttributes() returns false, this branch currently skips all checks and the test still passes. Also, >= 0 checks don’t verify that refreshed counters are nondecreasing after update. Capture pre-update times, assert expected success outside macOS, and compare post-update values.

Suggested test tightening
         // Test updateAttributes on current thread (not implemented on macOS)
         OSThread currentThread = os.getCurrentThread();
         assertThat("Current thread shouldn't be null", currentThread, is(notNullValue()));
-        if (currentThread.updateAttributes()) {
-            assertThat("Thread kernel time should be 0 or higher after update", currentThread.getKernelTime(),
-                    is(greaterThanOrEqualTo(0L)));
-            assertThat("Thread user time should be 0 or higher after update", currentThread.getUserTime(),
-                    is(greaterThanOrEqualTo(0L)));
+        long kernelBefore = currentThread.getKernelTime();
+        long userBefore = currentThread.getUserTime();
+        boolean updated = currentThread.updateAttributes();
+        assertThat("Current thread updateAttributes should succeed outside macOS", updated || Platform.isMac(), is(true));
+        if (updated) {
+            assertThat("Thread kernel time should be nondecreasing after update", currentThread.getKernelTime(),
+                    is(greaterThanOrEqualTo(kernelBefore)));
+            assertThat("Thread user time should be nondecreasing after update", currentThread.getUserTime(),
+                    is(greaterThanOrEqualTo(userBefore)));
         }
📝 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
// Test updateAttributes on current thread (not implemented on macOS)
OSThread currentThread = os.getCurrentThread();
assertThat("Current thread shouldn't be null", currentThread, is(notNullValue()));
if (currentThread.updateAttributes()) {
assertThat("Thread kernel time should be 0 or higher after update", currentThread.getKernelTime(),
is(greaterThanOrEqualTo(0L)));
assertThat("Thread user time should be 0 or higher after update", currentThread.getUserTime(),
is(greaterThanOrEqualTo(0L)));
}
// Test updateAttributes on current thread (not implemented on macOS)
OSThread currentThread = os.getCurrentThread();
assertThat("Current thread shouldn't be null", currentThread, is(notNullValue()));
long kernelBefore = currentThread.getKernelTime();
long userBefore = currentThread.getUserTime();
boolean updated = currentThread.updateAttributes();
assertThat("Current thread updateAttributes should succeed outside macOS", updated || Platform.isMac(), is(true));
if (updated) {
assertThat("Thread kernel time should be nondecreasing after update", currentThread.getKernelTime(),
is(greaterThanOrEqualTo(kernelBefore)));
assertThat("Thread user time should be nondecreasing after update", currentThread.getUserTime(),
is(greaterThanOrEqualTo(userBefore)));
}
🤖 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-core/src/test/java/oshi/software/os/shared/OperatingSystemTest.java`
around lines 193 - 201, Capture pre-update counters from os.getCurrentThread()
into local variables (e.g., preKernel = currentThread.getKernelTime(), preUser =
currentThread.getUserTime()), then call currentThread.updateAttributes(); if it
returns false assert the runtime OS is macOS by checking
System.getProperty("os.name") contains "mac" to allow the unimplemented case;
otherwise assert updateAttributes() returned true and that post-update
currentThread.getKernelTime() and getUserTime() are >= their respective
pre-update values and >= 0. Use the symbols OperatingSystem os, OSThread
currentThread, getCurrentThread(), updateAttributes(), getKernelTime(), and
getUserTime() to locate and modify the test.

Add JNA vs FFM comparison tests exercising updateAttributes() on all
interfaces that define it: OSProcess, OSThread, HWDiskStore, NetworkIF,
OSFileStore, and PowerSource.

Each test snapshots values, sleeps briefly, calls updateAttributes() on
both JNA and FFM instances, then verifies:
- updateAttributes() returns true
- Monotonically nondecreasing counters have not decreased (kernel/user
  time, disk reads/writes, network bytes sent/received)
- Static values remain consistent between JNA and FFM

Also narrows the Linux disk test skip: instead of disabling the entire
diskStores() test on Linux, only skip the partition name comparison
which is affected by the JNA UdevDevice.getSysname() bug fixed in
java-native-access/jna#1715 (not yet released
past 5.18.1).
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