Skip to content

Add CoreFoundation FFM tests for all wrapper types - #3163

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:corefoundation-ffm-tests
Apr 15, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:corefoundation-ffm-tests

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds 35 tests for all CoreFoundation wrapper types in CoreFoundation.java, exercising real native CoreFoundation calls on macOS.

Changes

  • New test class CoreFoundationTest with 35 tests, gated by @EnabledOnOs(OS.MAC) + @EnabledForJreRange(min = JRE.JAVA_25)
  • module-info.test: Added --add-opens for oshi.ffm.mac so JUnit can reflectively access the test class

Test Coverage

CFTypeRef (base class)

  • Null handling (NULL and Java null)
  • getTypeID, isTypeID
  • equals/hashCode (equal strings, different strings, null refs, self-equality)
  • retain/release with retain count verification

CFStringRef

  • Roundtrip create → stringValue
  • Empty string, null → empty, Unicode (Japanese)
  • ClassCastException when wrapping a non-string

CFNumberRef

  • longValue, intValue, shortValue, byteValue, doubleValue, floatValue roundtrips via CFNumberCreate
  • Null → zero for all numeric types

CFBooleanRef

  • kCFBooleanTrue → true, kCFBooleanFalse → false (via symbol lookup + reinterpret)
  • Null → false

CFDataRef

  • Roundtrip via CFDataCreate: getLength, getBytePtr, getBytes
  • Null → defaults

CFArrayRef

  • Create array with 2 CFStrings, verify getCount and getValueAtIndex
  • Null → defaults

CFDictionaryRef / CFMutableDictionaryRef

  • setValue/getValue/getCount/getValueIfPresent, missing key returns NULL
  • Null key ignored (no crash, count stays 0)
  • Null → defaults

CFAllocatorRef, CFLocale, CFDateFormatter

  • CFAllocatorGetDefault → non-null
  • CFLocale.copyCurrent → non-null
  • CFDateFormatter.create + getFormat → non-empty format string
  • Null formatter → null format

ClassCastException paths

  • 5 tests: CFNumberRef, CFBooleanRef, CFArrayRef, CFDataRef, CFDictionaryRef all reject a CFString segment

Summary by CodeRabbit

  • Tests
    • Added comprehensive macOS integration tests for CoreFoundation wrappers (Java 25+): refs, strings, numbers, booleans, data/arrays, dictionaries/mutability, allocators, locale/date formatting, retain-count and cast/error paths.
  • Bug Fixes
    • Improved native-backed hashing for CoreFoundation objects with consistent null handling and a safe fallback to avoid errors.
  • Chores
    • Enabled macOS CoreFoundation tests in the JVM test configuration and excluded FFIM-related sources from coverage reporting.

@coderabbitai

coderabbitai Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

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
  • ✅ Review completed - (🔄 Check again to review again)
📝 Walkthrough

Walkthrough

Adds macOS JUnit 5 integration tests for CoreFoundation FFM wrappers, introduces a native CFHash downcall and hashCode fallback, updates test JVM args to open oshi.ffm.mac to JUnit, and excludes **/ffm/** from JaCoCo coverage.

Changes

Cohort / File(s) Summary
JUnit Module Configuration
oshi-core-java25/src/test/java/module-info.test
Added --add-opens to open com.github.oshi/oshi.ffm.mac to org.junit.platform.commons and added --enable-native-access com.github.oshi JVM arg for tests.
CoreFoundation FFM Tests
oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java
New macOS-only (Java 25+) JUnit 5 integration tests exercising CF wrapper types: null handling, type checks, retain/release, round-trips, array/dictionary behaviors, and ClassCastException cases.
CoreFoundation runtime + hash
oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundation.java, oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.java
Added CFHash downcall in CoreFoundationFunctions; changed CFTypeRef.hashCode() to return 0 for null, call native CFHash for non-null, and fall back to Objects.hash(segment()) on exception.
JaCoCo config
pom.xml
Added JaCoCo exclusion **/ffm/** to omit FFM-related classes from coverage instrumentation/reporting.

Sequence Diagram(s)

sequenceDiagram
    participant Test as JUnit Test
    participant CF as CoreFoundation.CFTypeRef
    participant CFN as CoreFoundationFunctions
    participant Native as macOS CoreFoundation

    Test->>CF: construct/get wrapper (MemorySegment)
    CF->>CFN: call CFHash(segment)  (hashCode)
    alt CFHash succeeds
        CFN->>Native: downcall CFHash(segment)
        Native-->>CFN: return hash (long)
        CFN-->>CF: return value
        CF-->>Test: hashCode -> Long.hashCode(value)
    else CFHash throws
        CFN-->>CF: throw
        CF-->>Test: fall back to Objects.hash(segment())
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰
I hopped to macOS with nimble paws,
Called CF functions and counted the laws,
I kept nulls gentle and hashes true,
Retained a crumb, then released it too,
A tiny test carrot — for me and you 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.58% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding comprehensive tests for CoreFoundation FFM wrapper types, which aligns with the primary deliverable of a new CoreFoundationTest class containing 35 tests.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

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 Apr 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 57.80%. Comparing base (1588a3a) to head (9832bd0).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3163      +/-   ##
==========================================
- Coverage   58.43%   57.80%   -0.63%     
==========================================
  Files         362      316      -46     
  Lines       20231    17392    -2839     
  Branches     3306     3069     -237     
==========================================
- Hits        11821    10053    -1768     
+ Misses       6785     5862     -923     
+ Partials     1625     1477     -148     
Flag Coverage Δ
linux ?
macos ?
macos-latest 29.74% <ø> (?)
ubuntu-latest 26.42% <ø> (?)
windows ?
windows-latest 30.68% <ø> (?)

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

🧹 Nitpick comments (1)
oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java (1)

70-84: testCFTypeRefEqualsAndHashCode currently validates only equals().

Please add positive hashCode() contract assertions for equal instances (including null-wrapper equality case) so the method name and coverage match.

♻️ Suggested test additions
     try {
         assertThat(str1.equals(str2), is(true));
+        assertThat(str1.hashCode(), is(str2.hashCode()));
         assertThat(str1.equals(str3), is(false));
         assertThat(str1.equals(null), is(false));
         assertThat(str1.equals(str1), is(true));
         // Null refs are equal to each other
         var nullRef1 = new CFTypeRef(NULL);
         var nullRef2 = new CFTypeRef(NULL);
         assertThat(nullRef1.equals(nullRef2), is(true));
+        assertThat(nullRef1.hashCode(), is(nullRef2.hashCode()));
         assertThat(nullRef1.equals(str1), is(false));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java` around
lines 70 - 84, Add assertions verifying the hashCode contract in
testCFTypeRefEqualsAndHashCode: for equal CFStringRef instances created via
CFStringRef.createCFString("test") assert their hashCode() values are equal, for
unequal instances (e.g., "test" vs "other") assert hashCodes are likely
different (or at least not relied upon), and for the null-wrapper case (new
CFTypeRef(NULL) vs new CFTypeRef(NULL)) assert their hashCode() values are
equal; place these assertions alongside the existing equals() assertions in the
same try/finally block so the test name and coverage reflect both equals() and
hashCode().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java`:
- Around line 437-438: The test leaks two native CFStringRef instances because
CFStringRef.createCFString("val") is called and then dict.setValue(null, ...)
returns early without releasing them; update the null-key test around
dict.setValue(...) to capture the created CFStringRef objects into local
variables (e.g., CFStringRef keyRef1/keyRef2 and valueRef1/valueRef2) and ensure
each created ref is explicitly released (via the appropriate CF release/dispose
method used elsewhere in the project) in a finally block or immediately after
the setValue call when the key is null so no native refs remain leaked;
reference CFStringRef.createCFString and dict.setValue to locate the fix.
- Around line 95-101: The test currently relies on exact CFGetRetainCount values
(CoreFoundationFunctions.CFGetRetainCount) around str.retain() and
str.release(), which is flaky; remove the exact equal assertions and instead
verify retain/release behavior without asserting precise counts—for example,
check that calling str.retain() does not throw and that str.release() eventually
allows cleanup (or assert that retain count is >0 before release or use
boolean/exception-based semantics), replacing the is(countBefore + 1) and
is(countBefore) assertions with non-exact checks or behavioral assertions using
the CoreFoundation wrapper methods (str.retain, str.release, and
CFGetRetainCount only for non-exact comparisons like greater-than/positive) so
the test no longer depends on exact retain-count deltas.

---

Nitpick comments:
In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java`:
- Around line 70-84: Add assertions verifying the hashCode contract in
testCFTypeRefEqualsAndHashCode: for equal CFStringRef instances created via
CFStringRef.createCFString("test") assert their hashCode() values are equal, for
unequal instances (e.g., "test" vs "other") assert hashCodes are likely
different (or at least not relied upon), and for the null-wrapper case (new
CFTypeRef(NULL) vs new CFTypeRef(NULL)) assert their hashCode() values are
equal; place these assertions alongside the existing equals() assertions in the
same try/finally block so the test name and coverage reflect both equals() and
hashCode().
🪄 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: 058d157f-661e-4450-bef4-5b9244414514

📥 Commits

Reviewing files that changed from the base of the PR and between 1964f5d and f4305c9.

📒 Files selected for processing (2)
  • oshi-core-java25/src/test/java/module-info.test
  • oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.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, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • 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: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.

Applied to files:

  • oshi-core-java25/src/test/java/module-info.test
📚 Learning: 2026-04-06T04:45:51.516Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:51.516Z
Learning: In the oshi/oshi project, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.

Applied to files:

  • oshi-core-java25/src/test/java/module-info.test
🔇 Additional comments (2)
oshi-core-java25/src/test/java/module-info.test (1)

9-10: Correct JPMS test access update for macOS FFM tests.

Opening com.github.oshi/oshi.ffm.mac to org.junit.platform.commons is the right test-side change for reflective discovery/invocation of the new package-private JUnit class.

oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java (1)

41-43: Great test guardrails and breadth for native wrapper coverage.

The OS/JRE gating and broad real-call coverage across wrapper types look solid for this suite.

Also applies to: 149-553

@dbwiddis
dbwiddis force-pushed the corefoundation-ffm-tests branch from f4305c9 to 3906668 Compare April 15, 2026 04:46

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

♻️ Duplicate comments (1)
oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java (1)

93-103: ⚠️ Potential issue | 🟠 Major

Remove exact retain-count assertions; this is flaky by CoreFoundation contract.

At Line 97 and Line 100/103, the test asserts precise CFGetRetainCount deltas. This is not stable and can fail nondeterministically. Keep behavioral retain/release validation without exact count math.

What do Apple CoreFoundation docs say about CFGetRetainCount reliability, and do they recommend asserting exact retain-count deltas in automated tests?
Proposed change
     `@Test`
     void testCFTypeRefRetainRelease() throws Throwable {
         var str = CFStringRef.createCFString("retain-test");
         try {
-            long countBefore = CoreFoundationFunctions.CFGetRetainCount(str.segment());
             str.retain();
-            long countAfter = CoreFoundationFunctions.CFGetRetainCount(str.segment());
-            assertThat(countAfter, is(countBefore + 1));
-            // Release the extra retain
             str.release();
-            assertThat(CoreFoundationFunctions.CFGetRetainCount(str.segment()), is(countBefore));
+            assertThat(str.isNull(), is(false));
+            assertThat(str.isTypeID(CoreFoundationFunctions.STRING_TYPE_ID), is(true));
         } finally {
             str.release();
         }
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java` around
lines 93 - 103, The test testCFTypeRefRetainRelease relies on exact values from
CoreFoundationFunctions.CFGetRetainCount which is flaky; modify the test to
avoid exact retain-count arithmetic: after creating the CFStringRef via
CFStringRef.createCFString("retain-test") call str.retain() and assert that
CFGetRetainCount(str.segment()) is greater than or equal to the prior value (or
simply greater than when possible), then call str.release() and assert the count
is not greater than the retained value (or that it returns to a non-increased
state) — in short replace strict equality assertions around
CoreFoundationFunctions.CFGetRetainCount with non-exact comparisons or
behavioral checks (no-op safety of str.release) referencing
testCFTypeRefRetainRelease, CFStringRef.createCFString,
CoreFoundationFunctions.CFGetRetainCount, str.retain, and str.release.
🧹 Nitpick comments (1)
oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java (1)

170-267: Consider parameterizing numeric conversion tests to reduce duplication.

The CFNumber tests are solid, but this block is highly repetitive and could be collapsed into parameterized cases for easier maintenance.

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

In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java` around
lines 170 - 267, The test methods
testCFNumberLong/testCFNumberInt/testCFNumberShort/testCFNumberByte/testCFNumberDouble/testCFNumberFloat
should be consolidated into a single parameterized JUnit test that iterates over
cases (type id, ValueLayout constant, input value, expected accessor and
expected assertion), calling CoreFoundationFunctions.CFNumberCreate and wrapping
the result in CFNumberRef for each case; use method sources or
`@ParameterizedTest` with a stream of tuples (e.g.,
(CoreFoundation.kCFNumberLongLongType, ValueLayout.JAVA_LONG, 123456789L,
cfNum::longValue, 123456789L)) to avoid duplication while ensuring
cfNum.release() runs in finally for each iteration and assertions use
appropriate matchers (is/closeTo) per type.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java`:
- Around line 93-103: The test testCFTypeRefRetainRelease relies on exact values
from CoreFoundationFunctions.CFGetRetainCount which is flaky; modify the test to
avoid exact retain-count arithmetic: after creating the CFStringRef via
CFStringRef.createCFString("retain-test") call str.retain() and assert that
CFGetRetainCount(str.segment()) is greater than or equal to the prior value (or
simply greater than when possible), then call str.release() and assert the count
is not greater than the retained value (or that it returns to a non-increased
state) — in short replace strict equality assertions around
CoreFoundationFunctions.CFGetRetainCount with non-exact comparisons or
behavioral checks (no-op safety of str.release) referencing
testCFTypeRefRetainRelease, CFStringRef.createCFString,
CoreFoundationFunctions.CFGetRetainCount, str.retain, and str.release.

---

Nitpick comments:
In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java`:
- Around line 170-267: The test methods
testCFNumberLong/testCFNumberInt/testCFNumberShort/testCFNumberByte/testCFNumberDouble/testCFNumberFloat
should be consolidated into a single parameterized JUnit test that iterates over
cases (type id, ValueLayout constant, input value, expected accessor and
expected assertion), calling CoreFoundationFunctions.CFNumberCreate and wrapping
the result in CFNumberRef for each case; use method sources or
`@ParameterizedTest` with a stream of tuples (e.g.,
(CoreFoundation.kCFNumberLongLongType, ValueLayout.JAVA_LONG, 123456789L,
cfNum::longValue, 123456789L)) to avoid duplication while ensuring
cfNum.release() runs in finally for each iteration and assertions use
appropriate matchers (is/closeTo) per type.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4b9a70ec-1d3a-4788-b873-79905c875ae5

📥 Commits

Reviewing files that changed from the base of the PR and between f4305c9 and 3906668.

📒 Files selected for processing (2)
  • oshi-core-java25/src/test/java/module-info.test
  • oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java
✅ Files skipped from review due to trivial changes (1)
  • oshi-core-java25/src/test/java/module-info.test
📜 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). (6)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
🔇 Additional comments (3)
oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java (3)

41-43: Good platform/runtime gating for native tests.

@EnabledOnOs(OS.MAC) + @EnabledForJreRange(min = JRE.JAVA_25) is the right guardrail for this FFM/CoreFoundation suite.


430-448: Nice fix for native resource cleanup in null-key dictionary test.

Capturing and releasing val1/val2 in finally avoids leaking CF objects on the null-key path.


514-562: Great negative-path coverage for wrapper cast safety.

These ClassCastException tests materially strengthen type-safety guarantees across wrappers.

@dbwiddis
dbwiddis force-pushed the corefoundation-ffm-tests branch from 3906668 to 8272208 Compare April 15, 2026 04:55

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java`:
- Around line 75-77: The test fails the equals/hashCode contract because
CFTypeRef.equals() uses CFEqual(value) but CFTypeRef.hashCode() uses segment
identity; update CFTypeRef.hashCode() in CoreFoundation.java to return a
value-based hash by calling the native CFHash for the underlying CFType (e.g.,
add or use a CoreFoundation.CFHash(Pointer) native wrapper or
CoreFoundation.INSTANCE.CFHash(ref) and convert its result to int), handle nulls
consistently, and ensure the implementation mirrors CFTypeRef.equals() semantics
so equal CF values produce equal hash codes.
🪄 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: 25fc2133-0b8a-4650-a1ca-12b05c4feba8

📥 Commits

Reviewing files that changed from the base of the PR and between 3906668 and 8272208.

📒 Files selected for processing (3)
  • oshi-core-java25/src/test/java/module-info.test
  • oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java
  • pom.xml
✅ Files skipped from review due to trivial changes (1)
  • oshi-core-java25/src/test/java/module-info.test
📜 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). (1)
  • GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3163
File: oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java:97-103
Timestamp: 2026-04-15T04:56:15.707Z
Learning: In CoreFoundationTest.java (oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java), asserting exact CFGetRetainCount deltas (+1 after retain, -1 after release) is intentional and considered reliable for freshly created CF objects (e.g., CFStringRef via CFStringRef.createCFString) where the test holds sole ownership. Do not flag these assertions as flaky — the Apple "avoid CFGetRetainCount" advisory applies to shared/framework-managed objects, not exclusively owned objects in unit tests.
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.

Applied to files:

  • pom.xml
📚 Learning: 2026-04-15T04:56:15.707Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3163
File: oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java:97-103
Timestamp: 2026-04-15T04:56:15.707Z
Learning: In CoreFoundationTest.java (oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java), asserting exact CFGetRetainCount deltas (+1 after retain, -1 after release) is intentional and considered reliable for freshly created CF objects (e.g., CFStringRef via CFStringRef.createCFString) where the test holds sole ownership. Do not flag these assertions as flaky — the Apple "avoid CFGetRetainCount" advisory applies to shared/framework-managed objects, not exclusively owned objects in unit tests.

Applied to files:

  • oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java
🔇 Additional comments (3)
oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java (2)

97-103: Retain-count delta checks are appropriate in this test scope.

This is a good, targeted ownership assertion for freshly created refs held solely by the test.

Based on learnings: asserting exact CFGetRetainCount deltas here is intentional and reliable for exclusively owned, freshly created CF objects.


439-447: Good native cleanup on ignored-null-key path.

val1 and val2 are now explicitly released in finally, which prevents leaking CFString refs when setValue ignores null keys.

pom.xml (1)

801-807: The FFM exclusion at line 805 is pre-existing and not a change in this PR. This review comment is based on an incorrect premise.

			> Likely an incorrect or invalid review comment.

35 tests covering CFTypeRef, CFStringRef, CFNumberRef, CFBooleanRef,
CFDataRef, CFArrayRef, CFDictionaryRef, CFMutableDictionaryRef,
CFAllocatorRef, CFLocale, and CFDateFormatter. Tests exercise null
handling, roundtrip conversions, retain/release, equals, type ID
checks, and ClassCastException paths. All gated by @EnabledOnOs(MAC)
and @EnabledForJreRange(min = JAVA_25).
@dbwiddis
dbwiddis force-pushed the corefoundation-ffm-tests branch from 02aca10 to 9832bd0 Compare April 15, 2026 05:21

@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-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java (1)

70-90: Consider adding one test for the hashCode() fallback branch.

This covers null/happy paths well; adding a targeted case for the CFHash-throws fallback would lock in the resilience behavior too.

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

In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java` around
lines 70 - 90, Add a unit test that exercises CFTypeRef.hashCode's fallback when
the native CFHash call throws: create a CFStringRef (e.g., via
CFStringRef.createCFString("fallback")), use a Mockito/spy on
CoreFoundation.CFHash (or the native wrapper method used by CFTypeRef.hashCode)
to throw a runtime exception for that object, then assert CFTypeRef.hashCode()
returns the fallback value (e.g., System.identityHashCode(ref) or whatever the
fallback implementation uses) and does not propagate the exception; reference
CFTypeRef.hashCode, CFStringRef.createCFString, and CoreFoundation.CFHash in the
test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java`:
- Around line 70-90: Add a unit test that exercises CFTypeRef.hashCode's
fallback when the native CFHash call throws: create a CFStringRef (e.g., via
CFStringRef.createCFString("fallback")), use a Mockito/spy on
CoreFoundation.CFHash (or the native wrapper method used by CFTypeRef.hashCode)
to throw a runtime exception for that object, then assert CFTypeRef.hashCode()
returns the fallback value (e.g., System.identityHashCode(ref) or whatever the
fallback implementation uses) and does not propagate the exception; reference
CFTypeRef.hashCode, CFStringRef.createCFString, and CoreFoundation.CFHash in the
test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 760193ad-5317-4e49-afd7-000016a57796

📥 Commits

Reviewing files that changed from the base of the PR and between 02aca10 and 9832bd0.

📒 Files selected for processing (5)
  • oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundation.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.java
  • oshi-core-java25/src/test/java/module-info.test
  • oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java
  • pom.xml
✅ Files skipped from review due to trivial changes (1)
  • pom.xml
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-core-java25/src/test/java/module-info.test
📜 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 21, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3163
File: oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java:97-103
Timestamp: 2026-04-15T04:56:15.707Z
Learning: In CoreFoundationTest.java (oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java), asserting exact CFGetRetainCount deltas (+1 after retain, -1 after release) is intentional and considered reliable for freshly created CF objects (e.g., CFStringRef via CFStringRef.createCFString) where the test holds sole ownership. Do not flag these assertions as flaky — the Apple "avoid CFGetRetainCount" advisory applies to shared/framework-managed objects, not exclusively owned objects in unit tests.
📚 Learning: 2026-04-15T04:56:15.707Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3163
File: oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java:97-103
Timestamp: 2026-04-15T04:56:15.707Z
Learning: In CoreFoundationTest.java (oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java), asserting exact CFGetRetainCount deltas (+1 after retain, -1 after release) is intentional and considered reliable for freshly created CF objects (e.g., CFStringRef via CFStringRef.createCFString) where the test holds sole ownership. Do not flag these assertions as flaky — the Apple "avoid CFGetRetainCount" advisory applies to shared/framework-managed objects, not exclusively owned objects in unit tests.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.java
  • oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundation.java
  • oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.java
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundation.java
🔇 Additional comments (4)
oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundationFunctions.java (1)

61-75: CFHash wrapper addition is clean and consistent.

The new native binding and wrapper method follow the same FFM downcall pattern already used throughout this class.

oshi-core-java25/src/main/java/oshi/ffm/mac/CoreFoundation.java (1)

173-180: CFTypeRef.hashCode() update looks solid.

Null returns are now deterministic, and using CFHash makes hashing value-oriented while keeping a safe fallback path.

oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java (2)

94-106: Retain/release delta assertions are appropriate in this test context.

This is a good ownership-semantics check for a freshly created CF object under test control.

Based on learnings, asserting exact CFGetRetainCount deltas for freshly created solely-owned CF objects in this test is intentional and reliable.


439-448: Nice fix: temporary CFString refs are now explicitly released.

The added finally cleanup removes native leak risk in the null-key dictionary path.

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