Skip to content

Extract parsing from NetStat and Xrandr commands - #3204

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:3189-extract-unix-netstat-xrandr-parsing
Apr 28, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:3189-extract-unix-netstat-xrandr-parsing

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 28, 2026 •

Copy link
Copy Markdown
Member

Resolves part of #3189.

Separates command execution from output parsing in 5 methods:

Refactored methods:

  • NetStat.queryTcpnetstat() → new queryTcpnetstat(List<String>) — netstat -n -p tcp
  • NetStat.queryNetstat() → new queryNetstat(List<String>) — netstat -n
  • NetStat.queryTcpStats(String) → new queryTcpStats(List<String>) — netstat -s TCP section
  • NetStat.queryUdpStats(String) → new queryUdpStats(List<String>) — netstat -s UDP section
  • Xrandr.getEdidArrays() → new getEdidArrays(List<String>) — xrandr --verbose

Tests added:

  • NetStatTest: TCP connection counting, connection parsing with state, TCP/UDP stats (Linux format), empty input
  • XrandrTest: EDID block parsing, no EDID block, empty input

No public API changes. No new dependencies.

Note: Xwininfo is not included — its parsing is tightly coupled to multiple sequential X11 commands (stacking order, window tree, per-window PID lookup), making a clean extraction impractical without a larger refactor.

Summary by CodeRabbit

  • Refactor

    • Separated native command execution from output parsing for network and display; parsing now operates on pre-collected output and handles empty/truncated inputs more robustly.
  • Tests

    • Added deterministic, fixture-driven unit tests for network stats and EDID parsing, including explicit empty-input cases.
    • Moved environment-dependent checks into nested live test suites to keep CI stable.

@coderabbitai

coderabbitai Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 62f4ae23-1e71-45ba-a42f-ca28f2029f46

📥 Commits

Reviewing files that changed from the base of the PR and between 6ea6ad8 and 9f302da.

📒 Files selected for processing (4)
  • oshi-common/src/main/java/oshi/util/driver/unix/NetStat.java
  • oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java
  • oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java
  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.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). (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 11, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • 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 (4)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java
  • oshi-common/src/main/java/oshi/util/driver/unix/NetStat.java
📚 Learning: 2026-04-18T03:18:06.205Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:06.205Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).

Applied to files:

  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
  • oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java
📚 Learning: 2026-04-19T01:28:47.155Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3174
File: oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java:237-257
Timestamp: 2026-04-19T01:28:47.155Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java`, the WMI comparison tests (e.g., `testProcessor`) intentionally validate only index 0 and a few representative fields per WMI data type (String, uint16, uint32, uint64). Exhaustive row-by-row comparison is deliberately avoided for numerically heavy multi-row tables. The design rationale is: matching row counts + a few selected fields covering each data type is sufficient to verify JNA vs FFM driver parity. Do not suggest looping over all rows for these tests.

Applied to files:

  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
📚 Learning: 2026-04-05T16:15:06.124Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3117
File: oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxLogicalVolumeGroupJNA.java:95-97
Timestamp: 2026-04-05T16:15:06.124Z
Learning: In `LinuxLogicalVolumeGroupJNA.getLogicalVolumeGroups()` (oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxLogicalVolumeGroupJNA.java), `physicalVolumesMap.get(e.getKey())` in the final stream mapping cannot return null: both `logicalVolumesMap` and `physicalVolumesMap` are populated via `computeIfAbsent` inside the same conditional block (`!Util.isBlank(vgName) && !Util.isBlank(lvName)`), so every VG key in `logicalVolumesMap` is guaranteed to have a corresponding entry in `physicalVolumesMap`. Do not flag this `.get()` call as a potential null-return issue. The FFM version uses `getOrDefault` as extra defensiveness, not because null is possible here.

Applied to files:

  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
🔇 Additional comments (6)
oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java (1)

26-37: Nice extraction of command execution from parsing.

This keeps getEdidArrays() behavior intact while making EDID parsing directly testable via the package-private overload.

oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java (2)

25-68: Great move to deterministic fixture-based parsing tests.

These cases validate success + empty/no-EDID paths cleanly and make parser behavior stable across CI environments.


70-79: Good live-test guard for headless systems.

Using an assumption before assertions avoids silent false confidence when no displays are present.

oshi-common/src/main/java/oshi/util/driver/unix/NetStat.java (1)

35-76: Solid refactor: parsing is now decoupled from command execution.

The delegation pattern is clean and keeps existing public call sites intact while enabling direct fixture-driven parser tests.

Also applies to: 135-146, 225-236

oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java (2)

33-130: Excellent fixture coverage for the extracted parsing methods.

These assertions cover happy paths and empty-input behavior for all newly testable parsing overloads.


132-171: Live test split/gating looks well structured.

Keeping live checks scoped by OS while relying on fixtures for deterministic validation is a good balance.


📝 Walkthrough

Walkthrough

The PR extracts command-output parsing into package-private helpers that accept pre-collected List for NetStat and Xrandr; public methods now delegate to those helpers. Tests were converted from live/native runs to deterministic fixture-driven unit tests, with live checks moved to nested OS-gated classes.

Changes

Cohort / File(s) Summary
NetStat parsing
oshi-common/src/main/java/oshi/util/driver/unix/NetStat.java
Separated native netstat execution from parsing by adding package-private overloads that accept List<String> (TCP connections, combined TCP/UDP, TCP/UDP stats); public query methods now run the native command and delegate parsing to these overloads.
Xrandr EDID parsing
oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java
Extracted EDID parsing into a new package-private getEdidArrays(List<String>); public getEdidArrays() now delegates to it after running xrandr --verbose.
NetStat tests
oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java
Replaced live, OS-dependent tests with fixture-based unit tests feeding synthetic netstat outputs to the new parsers; retained previous live assertions in an OS-gated LiveTests nested class.
Xrandr tests
oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
Added deterministic tests for getEdidArrays(List<String>) using synthetic xrandr --verbose input; original live test moved into an OS-gated LiveTests nested class and guarded for headless cases.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related issues

Possibly related PRs

Poem

Parsers now sip from a tidy stream of lines,
Commands stay outside while the logic refines.
Fixtures hum softly, tests steady and bright,
Live checks tucked in nests, sleeping through the night. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.74% 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 accurately summarizes the main change: extracting parsing logic from NetStat and Xrandr command classes into separate methods that accept pre-collected output, improving testability and separation of concerns.
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
✨ 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 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.71429% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 59.05%. Comparing base (bdbdbe2) to head (9f302da).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...n/src/main/java/oshi/util/driver/unix/NetStat.java 83.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3204      +/-   ##
==========================================
+ Coverage   58.82%   59.05%   +0.22%     
==========================================
  Files         421      421              
  Lines       20358    20358              
  Branches     3577     3576       -1     
==========================================
+ Hits        11976    12022      +46     
+ Misses       6630     6580      -50     
- Partials     1752     1756       +4     
Flag Coverage Δ
linux 25.03% <71.42%> (+0.21%) ⬆️
macos 28.46% <42.85%> (+0.46%) ⬆️
windows 37.64% <28.57%> (+0.54%) ⬆️

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.

🧹 Nitpick comments (3)
oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java (2)

122-131: Clarify intent of triple-disabled live test.

The inner testQueryNetstat() is @DisabledOnOs({ OS.WINDOWS, OS.MAC, OS.LINUX }) while the outer LiveTests class already has @DisabledOnOs(OS.WINDOWS). This means the test only runs on FreeBSD and OpenBSD.

If this is intentional (perhaps because netstat -n output format differs on Mac/Linux), a brief comment would help future maintainers understand why.

📝 Suggested comment for clarity
+        // Only FreeBSD/OpenBSD: netstat -n output format matches the expected parsing
         `@DisabledOnOs`({ OS.WINDOWS, OS.MAC, OS.LINUX })
         `@Test`
         void testQueryNetstat() {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java` around
lines 122 - 131, The inner testQueryNetstat() method is annotated with
`@DisabledOnOs`({ OS.WINDOWS, OS.MAC, OS.LINUX }) which together with the outer
LiveTests `@DisabledOnOs`(OS.WINDOWS) effectively limits the test to BSDs; add a
brief inline comment above the testQueryNetstat() method (referencing LiveTests
and testQueryNetstat) explaining that this triple-disable is intentional because
netstat output/format differs on Mac/Linux/Windows and the live parsing is only
verified on FreeBSD/OpenBSD so future maintainers understand the purpose.

87-120: Consider verifying additional fields in empty input tests.

The empty input tests only check one field (connectionsEstablished for TCP, datagramsSent for UDP). While the implementation initializes all fields to zero, verifying a couple more fields would strengthen confidence that the entire stats object is properly zeroed.

💡 Optional enhancement for more thorough empty assertions
     `@Test`
     void testQueryTcpStatsEmpty() {
         TcpStats stats = NetStat.queryTcpStats(Collections.emptyList());
         assertThat(stats.getConnectionsEstablished(), is(0L));
+        assertThat(stats.getSegmentsSent(), is(0L));
     }

     `@Test`
     void testQueryUdpStatsEmpty() {
         UdpStats stats = NetStat.queryUdpStats(Collections.emptyList());
         assertThat(stats.getDatagramsSent(), is(0L));
+        assertThat(stats.getDatagramsReceived(), is(0L));
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java` around
lines 87 - 120, The empty-input unit tests only assert a single field; expand
assertions in testQueryTcpStatsEmpty and testQueryUdpStatsEmpty to check several
fields to ensure full zero initialization—for TCP verify at least
getConnectionsEstablished(), getConnectionsActive(), and getSegmentsReceived()
on the TcpStats returned by NetStat.queryTcpStats(Collections.emptyList()), and
for UDP verify getDatagramsSent(), getDatagramsReceived(), and
getDatagramsNoPort() on the UdpStats returned by
NetStat.queryUdpStats(Collections.emptyList()); update the tests to assert these
are 0L so the TcpStats and UdpStats objects are validated as fully zeroed.
oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java (1)

30-38: Tighten the fixture to exactly 128 bytes to make this test stricter.

Right now the fixture appears to include 258 hex chars (129 bytes), and Line 47 only checks >= 128. That can mask accidental over-read behavior in parsing. Consider making the fixture exactly 256 hex chars and asserting exactly 128 bytes.

Suggested test-tightening diff
-        // 256 hex chars = 128 bytes (standard EDID block)
+        // 256 hex chars = 128 bytes (standard EDID block)
         lines.add("\t\t00ffffffffffff001e6d085b0b0b0b0b");
         lines.add("\t\t0c1c0104b53c2278fb2eb5ae4f46a527");
         lines.add("\t\t0d5054254b80714f81809500a9c0b300");
         lines.add("\t\td1c001010101565e00a0a0a029503020");
-        lines.add("\t\t35000f282100001a000000fd00384b1e5");
-        lines.add("\t\ta1900000a202020202020000000fc004c");
+        lines.add("\t\t35000f282100001a000000fd00384b1e");
+        lines.add("\t\ta1900000a202020202020000000fc004");
         lines.add("\t\t4720554c54524147454152000000ff00");
         lines.add("\t\t3630344e54505a4832313337370a0170");
@@
-        assertThat(edids.get(0).length, greaterThanOrEqualTo(128));
+        assertThat(edids.get(0).length, is(128));

Also applies to: 47-47

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

In `@oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java` around lines
30 - 38, Update the EDID fixture in XrandrTest so the concatenated hex strings
added via the lines.add(...) calls total exactly 256 hex characters (128 bytes)
by trimming or adjusting the hex fragments (the block starting with
"00ffffffffffff00..." and ending with "3630344e54505a48..."). Then tighten the
assertion that currently checks for ">= 128" to assert equality with 128 bytes
instead, ensuring the test fails on any over-read; reference the test class
XrandrTest, the lines.add entries that build the EDID, and the assertion that
verifies the parsed byte length.
🤖 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-common/src/test/java/oshi/util/driver/unix/NetStatTest.java`:
- Around line 122-131: The inner testQueryNetstat() method is annotated with
`@DisabledOnOs`({ OS.WINDOWS, OS.MAC, OS.LINUX }) which together with the outer
LiveTests `@DisabledOnOs`(OS.WINDOWS) effectively limits the test to BSDs; add a
brief inline comment above the testQueryNetstat() method (referencing LiveTests
and testQueryNetstat) explaining that this triple-disable is intentional because
netstat output/format differs on Mac/Linux/Windows and the live parsing is only
verified on FreeBSD/OpenBSD so future maintainers understand the purpose.
- Around line 87-120: The empty-input unit tests only assert a single field;
expand assertions in testQueryTcpStatsEmpty and testQueryUdpStatsEmpty to check
several fields to ensure full zero initialization—for TCP verify at least
getConnectionsEstablished(), getConnectionsActive(), and getSegmentsReceived()
on the TcpStats returned by NetStat.queryTcpStats(Collections.emptyList()), and
for UDP verify getDatagramsSent(), getDatagramsReceived(), and
getDatagramsNoPort() on the UdpStats returned by
NetStat.queryUdpStats(Collections.emptyList()); update the tests to assert these
are 0L so the TcpStats and UdpStats objects are validated as fully zeroed.

In `@oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java`:
- Around line 30-38: Update the EDID fixture in XrandrTest so the concatenated
hex strings added via the lines.add(...) calls total exactly 256 hex characters
(128 bytes) by trimming or adjusting the hex fragments (the block starting with
"00ffffffffffff00..." and ending with "3630344e54505a48..."). Then tighten the
assertion that currently checks for ">= 128" to assert equality with 128 bytes
instead, ensuring the test fails on any over-read; reference the test class
XrandrTest, the lines.add entries that build the EDID, and the assertion that
verifies the parsed byte length.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6d82ebec-6156-4992-bee7-b8c45e240220

📥 Commits

Reviewing files that changed from the base of the PR and between bdbdbe2 and 0b2697c.

📒 Files selected for processing (4)
  • oshi-common/src/main/java/oshi/util/driver/unix/NetStat.java
  • oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java
  • oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java
  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.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). (9)
  • 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 11, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java
  • oshi-common/src/main/java/oshi/util/driver/unix/NetStat.java
📚 Learning: 2026-04-18T03:18:06.205Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:06.205Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).

Applied to files:

  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
  • oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java
🔇 Additional comments (12)
oshi-common/src/main/java/oshi/util/driver/unix/NetStat.java (4)

35-57: Clean extraction of parsing logic.

The delegation pattern here is well-implemented. The public method runs the command and delegates to the package-private overload, preserving the existing API while enabling fixture-based testing. The Javadoc clearly documents both methods.


65-97: Good separation of concerns for queryNetstat.

Same clean pattern as above. The parsing logic is now testable in isolation while the public API remains unchanged. The state substitution logic (SYN_RCVD → SYN_RECV) is preserved correctly.


135-145: Consistent refactoring for TCP stats.

The queryTcpStats extraction follows the same delegation pattern. The Javadoc correctly notes this handles both Linux and OpenBSD formats.


225-235: UDP stats extraction looks good.

Completes the consistent refactoring pattern across all four methods. Package-private visibility allows same-package tests while keeping the internal API surface minimal.

oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java (4)

33-56: Excellent fixture design for deterministic testing.

The fixtures are well-chosen:

  • TCP_NETSTAT covers tcp4, tcp6, and non-ESTABLISHED states
  • NETSTAT_N includes both TCP and UDP connections
  • Linux stats fixtures use realistic formatting with indented lines

This enables reliable unit testing without depending on the actual system's network state.


58-70: Good coverage for TCP connection counting.

Tests verify both IPv4 and IPv6 established connection counts (2 tcp4, 1 tcp6), and the empty input case correctly returns zeroes. The fixture excludes TIME_WAIT from the count as expected.


72-85: Connection parsing tests verify key attributes.

The tests confirm proper type extraction, state parsing (ESTABLISHED vs NONE for UDP), and correct handling of empty input returning an empty list.


133-160: Live tests properly organized by platform.

The OS-specific live tests are well-structured:

  • FreeBSD/macOS for queryTcpnetstat() (uses netstat -n -p tcp)
  • Linux for netstat -st4 and netstat -su4
  • OpenBSD for netstat -s -p tcp/udp

Good use of greaterThanOrEqualTo(0) assertions since actual values are non-deterministic.

oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java (2)

26-29: Nice extraction point for testability.

Delegating Line 28 through the overload cleanly separates command execution from parsing while preserving the public entrypoint behavior.


31-37: Helper method contract is clear and appropriately scoped.

The package-private overload and its Javadoc make parser-only testing straightforward without exposing new public API surface.

oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java (2)

50-61: Good edge-case coverage for parser-only path.

The empty-input and no-EDID tests are valuable and directly validate the extracted helper behavior.


63-71: Great separation of deterministic vs live tests.

Moving live command-dependent assertions into an OS-gated nested class keeps core unit tests stable while preserving runtime validation.

@dbwiddis
dbwiddis force-pushed the 3189-extract-unix-netstat-xrandr-parsing branch from 0b2697c to 3c50e04 Compare April 28, 2026 04:30

@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

Caution

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

⚠️ Outside diff range comments (1)
oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java (1)

37-61: ⚠️ Potential issue | 🟠 Major

Don't truncate the EDID payload at 128 bytes.

This helper stops once it reaches 256 hex chars, so any xrandr --verbose output that carries EDID extension data will be silently dropped. If the intent is only to support the base block, please document that explicitly; otherwise the parser needs to keep collecting the full EDID section before decoding.

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

In `@oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java` around lines 37
- 61, The getEdidArrays helper currently stops collecting EDID hex once
sb.length() reaches 256 chars and so truncates extension blocks; change the
collector to accumulate all contiguous hex lines after an "EDID" marker instead
of stopping at 256. Concretely: inside getEdidArrays, when sb != null append
trimmed lines only while the trimmed line matches a hex-only chunk (e.g. matches
"[0-9A-Fa-f]+"); treat the first non-hex (or empty) line as the end of the EDID
block, then call ParseUtil.hexStringToByteArray on the entire accumulated string
and add to displays if edid.length >= 128 (or a multiple of 128 as desired),
then reset sb to null. This preserves extension blocks and keeps the existing
ParseUtil.hexStringToByteArray and displays.add(edid) logic.
🧹 Nitpick comments (3)
oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java (2)

102-124: Tighten the empty-input coverage.

The zero-input tests only verify a subset of the returned counters, so a bug in one of the unasserted fields would still go unnoticed.

🧪 Suggested follow-up

Consider asserting every field returned by TcpStats and UdpStats when the input list is empty, for example:

     `@Test`
     void testQueryTcpStatsEmpty() {
         TcpStats stats = NetStat.queryTcpStats(Collections.emptyList());
         assertThat(stats.getConnectionsEstablished(), is(0L));
         assertThat(stats.getConnectionsActive(), is(0L));
+        assertThat(stats.getConnectionsPassive(), is(0L));
+        assertThat(stats.getConnectionFailures(), is(0L));
+        assertThat(stats.getConnectionsReset(), is(0L));
+        assertThat(stats.getSegmentsSent(), is(0L));
         assertThat(stats.getSegmentsReceived(), is(0L));
+        assertThat(stats.getSegmentsRetransmitted(), is(0L));
+        assertThat(stats.getInErrors(), is(0L));
+        assertThat(stats.getOutResets(), is(0L));
     }

     `@Test`
     void testQueryUdpStatsEmpty() {
         UdpStats stats = NetStat.queryUdpStats(Collections.emptyList());
         assertThat(stats.getDatagramsSent(), is(0L));
         assertThat(stats.getDatagramsReceived(), is(0L));
         assertThat(stats.getDatagramsNoPort(), is(0L));
+        assertThat(stats.getDatagramsReceivedErrors(), is(0L));
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java` around
lines 102 - 124, The empty-input tests only assert a subset of counters; update
testQueryTcpStatsEmpty to assert all TcpStats fields returned by
NetStat.queryTcpStats(Collections.emptyList()) (e.g., connectionsEstablished,
connectionsActive, segmentsReceived, segmentsSent, segmentsRetransmitted, etc.)
and update testQueryUdpStatsEmpty to assert every UdpStats field returned by
NetStat.queryUdpStats(Collections.emptyList()) (e.g., datagramsSent,
datagramsReceived, datagramsNoPort, datagramsReceivedErrors, etc.) so that no
counter is left unverified.

74-79: Assert the parsed endpoint fields too.

These checks only cover count, type, and state. Since the new helper’s main purpose is parsing connection details, a regression in parseIP or port extraction would still pass here.

🔎 Suggested follow-up

Add at least one assertion for the parsed local/remote address or port on the TCP fixture, and ideally one for the UDP entry as well.

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

In `@oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java` around
lines 74 - 79, The test currently only asserts count, type and state; add
assertions to verify parsed endpoint fields from NetStat.queryNetstat so
regressions in parseIP/port extraction are caught. In NetStatTest.java, for the
TCP fixture (connections.get(0)) assert its local and remote address and/or port
(e.g., getLocalAddr()/getLocalPort() and getRemoteAddr()/getRemotePort()) and
for the UDP fixture (connections.get(1)) add at least one assertion for its
parsed local address or port. Ensure you reference the existing
NetStat.queryNetstat result (connections) and use the same IPConnection getter
methods used elsewhere in the test.
oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java (1)

24-61: Assert the decoded EDID contents, not just the length.

The synthetic test proves the parser returns one 128-byte array, but a regression that returns the wrong 128 bytes would still pass. Consider asserting a stable prefix/suffix or checksum from the fixture so the hex concatenation is actually verified.

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

In `@oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java` around lines
24 - 61, The test only checks length; update testGetEdidArraysSingleDisplay to
verify the decoded EDID bytes themselves by asserting a known stable fingerprint
from createXrandrWithEdid(): e.g., check the EDID header/prefix bytes (00 FF FF
FF FF FF FF 00), one or two stable fields (manufacturer/product bytes at
offsets), and the EDID checksum (sum of 128 bytes % 256 == 0) to ensure correct
hex concatenation and parsing in Xrandr.getEdidArrays rather than just length.
🤖 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-common/src/test/java/oshi/util/driver/unix/XrandrTest.java`:
- Around line 63-70: The LiveTests test method may silently pass when
Xrandr.getEdidArrays() yields no results because runNative() returns an empty
list on failure; update the testGetEdidArrays() in class LiveTests to first call
Xrandr.getEdidArrays() and if the returned list is empty, skip the test (or
fail) with a clear message, otherwise iterate and assert each byte[] has length
>= 128; use the Xrandr.getEdidArrays() result to decide skipping so headless
systems or hosts without xrandr don't produce a false positive.

---

Outside diff comments:
In `@oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java`:
- Around line 37-61: The getEdidArrays helper currently stops collecting EDID
hex once sb.length() reaches 256 chars and so truncates extension blocks; change
the collector to accumulate all contiguous hex lines after an "EDID" marker
instead of stopping at 256. Concretely: inside getEdidArrays, when sb != null
append trimmed lines only while the trimmed line matches a hex-only chunk (e.g.
matches "[0-9A-Fa-f]+"); treat the first non-hex (or empty) line as the end of
the EDID block, then call ParseUtil.hexStringToByteArray on the entire
accumulated string and add to displays if edid.length >= 128 (or a multiple of
128 as desired), then reset sb to null. This preserves extension blocks and
keeps the existing ParseUtil.hexStringToByteArray and displays.add(edid) logic.

---

Nitpick comments:
In `@oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java`:
- Around line 102-124: The empty-input tests only assert a subset of counters;
update testQueryTcpStatsEmpty to assert all TcpStats fields returned by
NetStat.queryTcpStats(Collections.emptyList()) (e.g., connectionsEstablished,
connectionsActive, segmentsReceived, segmentsSent, segmentsRetransmitted, etc.)
and update testQueryUdpStatsEmpty to assert every UdpStats field returned by
NetStat.queryUdpStats(Collections.emptyList()) (e.g., datagramsSent,
datagramsReceived, datagramsNoPort, datagramsReceivedErrors, etc.) so that no
counter is left unverified.
- Around line 74-79: The test currently only asserts count, type and state; add
assertions to verify parsed endpoint fields from NetStat.queryNetstat so
regressions in parseIP/port extraction are caught. In NetStatTest.java, for the
TCP fixture (connections.get(0)) assert its local and remote address and/or port
(e.g., getLocalAddr()/getLocalPort() and getRemoteAddr()/getRemotePort()) and
for the UDP fixture (connections.get(1)) add at least one assertion for its
parsed local address or port. Ensure you reference the existing
NetStat.queryNetstat result (connections) and use the same IPConnection getter
methods used elsewhere in the test.

In `@oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java`:
- Around line 24-61: The test only checks length; update
testGetEdidArraysSingleDisplay to verify the decoded EDID bytes themselves by
asserting a known stable fingerprint from createXrandrWithEdid(): e.g., check
the EDID header/prefix bytes (00 FF FF FF FF FF FF 00), one or two stable fields
(manufacturer/product bytes at offsets), and the EDID checksum (sum of 128 bytes
% 256 == 0) to ensure correct hex concatenation and parsing in
Xrandr.getEdidArrays rather than just length.
🪄 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: 9481ad5b-fc44-4c59-8ecc-373bc113cec6

📥 Commits

Reviewing files that changed from the base of the PR and between 0b2697c and 3c50e04.

📒 Files selected for processing (4)
  • oshi-common/src/main/java/oshi/util/driver/unix/NetStat.java
  • oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java
  • oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java
  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/main/java/oshi/util/driver/unix/NetStat.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 21, windows-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java
📚 Learning: 2026-04-18T03:18:06.205Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:06.205Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).

Applied to files:

  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
  • oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java
🔇 Additional comments (3)
oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java (2)

33-57: Good move switching these to in-file fixtures.

This makes the parser tests deterministic and removes the environment-dependent setup from the unit path.


126-165: LGTM on the OS-gated live coverage.

Keeping the platform-specific checks in a nested class makes the fixture-based parser tests cleaner without dropping the existing live verification.

oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java (1)

26-29: Nice extraction.

Keeping the public method as a thin delegate preserves behavior and makes the parsing logic easier to unit test.

@dbwiddis
dbwiddis force-pushed the 3189-extract-unix-netstat-xrandr-parsing branch from 3c50e04 to 6ea6ad8 Compare April 28, 2026 04:40

@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 (2)
oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java (2)

112-127: Consider checking the remaining UDP stat as well.

The empty-input case currently exercises three of four getters; covering getDatagramsReceivedErrors() would make the zero-value contract explicit.

♻️ Suggested addition
     assertThat(stats.getDatagramsSent(), is(0L));
     assertThat(stats.getDatagramsReceived(), is(0L));
     assertThat(stats.getDatagramsNoPort(), is(0L));
+    assertThat(stats.getDatagramsReceivedErrors(), is(0L));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java` around
lines 112 - 127, Update the empty-input unit test to assert the remaining UDP
error getter: in the test method testQueryUdpStatsEmpty call
NetStat.queryUdpStats(Collections.emptyList()) as before and add an assertion
for UdpStats.getDatagramsReceivedErrors() expecting 0L so the zero-value
contract is explicit; this touches the test method testQueryUdpStatsEmpty and
the UdpStats getters used by NetStat.queryUdpStats.

91-110: Consider asserting getInErrors() here too.

TCP_STATS_LINUX already includes a bad segments received entry, but the test never checks the corresponding field. Adding that assertion would make this parsing test complete.

♻️ Suggested addition
     assertThat(stats.getSegmentsSent(), is(345678L));
     assertThat(stats.getSegmentsReceived(), is(789012L));
     assertThat(stats.getSegmentsRetransmitted(), is(901L));
+    assertThat(stats.getInErrors(), is(0L));
     assertThat(stats.getOutResets(), is(45L));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java` around
lines 91 - 110, Add an assertion for the "in errors" field: in
testQueryTcpStatsLinux, after the existing segment assertions call
NetStat.queryTcpStats(TCP_STATS_LINUX) and assert that stats.getInErrors()
equals the expected value parsed from TCP_STATS_LINUX (the "bad segments
received" value); also add an assertion in testQueryTcpStatsEmpty to assert
stats.getInErrors() is 0 to cover the empty-input case. Use the
TcpStats.getInErrors() accessor to locate and verify the field.
🤖 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-common/src/test/java/oshi/util/driver/unix/NetStatTest.java`:
- Around line 112-127: Update the empty-input unit test to assert the remaining
UDP error getter: in the test method testQueryUdpStatsEmpty call
NetStat.queryUdpStats(Collections.emptyList()) as before and add an assertion
for UdpStats.getDatagramsReceivedErrors() expecting 0L so the zero-value
contract is explicit; this touches the test method testQueryUdpStatsEmpty and
the UdpStats getters used by NetStat.queryUdpStats.
- Around line 91-110: Add an assertion for the "in errors" field: in
testQueryTcpStatsLinux, after the existing segment assertions call
NetStat.queryTcpStats(TCP_STATS_LINUX) and assert that stats.getInErrors()
equals the expected value parsed from TCP_STATS_LINUX (the "bad segments
received" value); also add an assertion in testQueryTcpStatsEmpty to assert
stats.getInErrors() is 0 to cover the empty-input case. Use the
TcpStats.getInErrors() accessor to locate and verify the field.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3dbc4614-f0b7-41a3-ba3f-be21e8a4238a

📥 Commits

Reviewing files that changed from the base of the PR and between 3c50e04 and 6ea6ad8.

📒 Files selected for processing (4)
  • oshi-common/src/main/java/oshi/util/driver/unix/NetStat.java
  • oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java
  • oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java
  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/main/java/oshi/util/driver/unix/NetStat.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, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, ubuntu-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java
📚 Learning: 2026-04-18T03:18:06.205Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:06.205Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).

Applied to files:

  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
  • oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java
📚 Learning: 2026-04-19T01:28:47.155Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3174
File: oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java:237-257
Timestamp: 2026-04-19T01:28:47.155Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java`, the WMI comparison tests (e.g., `testProcessor`) intentionally validate only index 0 and a few representative fields per WMI data type (String, uint16, uint32, uint64). Exhaustive row-by-row comparison is deliberately avoided for numerically heavy multi-row tables. The design rationale is: matching row counts + a few selected fields covering each data type is sufficient to verify JNA vs FFM driver parity. Do not suggest looping over all rows for these tests.

Applied to files:

  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
📚 Learning: 2026-04-05T16:15:06.124Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3117
File: oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxLogicalVolumeGroupJNA.java:95-97
Timestamp: 2026-04-05T16:15:06.124Z
Learning: In `LinuxLogicalVolumeGroupJNA.getLogicalVolumeGroups()` (oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxLogicalVolumeGroupJNA.java), `physicalVolumesMap.get(e.getKey())` in the final stream mapping cannot return null: both `logicalVolumesMap` and `physicalVolumesMap` are populated via `computeIfAbsent` inside the same conditional block (`!Util.isBlank(vgName) && !Util.isBlank(lvName)`), so every VG key in `logicalVolumesMap` is guaranteed to have a corresponding entry in `physicalVolumesMap`. Do not flag this `.get()` call as a potential null-return issue. The FFM version uses `getOrDefault` as extra defensiveness, not because null is possible here.

Applied to files:

  • oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java
🔇 Additional comments (10)
oshi-common/src/main/java/oshi/util/driver/unix/Xrandr.java (2)

26-29: Good separation of concerns.

Keeping the native command execution here and handing parsing off to the helper makes the public entry point much easier to test.


31-62: Parsing helper looks solid.

The empty-input guard, EDID accumulation, and 128-byte minimum match the current xrandr --verbose format and keep invalid blocks out.

oshi-common/src/test/java/oshi/util/driver/unix/XrandrTest.java (5)

25-42: Nice fixture setup.

Hard-coding a representative EDID block here makes the parser test deterministic without relying on the host display stack.


44-55: Good happy-path assertions.

Checking the returned size, EDID length, and header bytes is a solid sanity check for the new overload.


57-60: Empty-input behavior is covered.

This locks down the no-data path and confirms the helper returns an empty result cleanly.


63-68: No-EDID behavior is covered.

Verifying that unrelated xrandr output still yields an empty list is the right edge-case check here.


70-80: Good live-test guard.

The nested OS gate plus assumeFalse avoids false positives on headless systems while still keeping a smoke test in place.

oshi-common/src/test/java/oshi/util/driver/unix/NetStatTest.java (3)

33-57: Good fixture setup for deterministic parsing tests.

These in-file samples make the parser coverage stable and avoid depending on host netstat output.


58-88: Good coverage for queryTcpnetstat and queryNetstat.

The new list-based tests validate the refactored parsing paths directly and keep the empty-input behavior explicit.


129-169: Live test gating looks sensible.

Keeping the OS-dependent checks in a nested class preserves coverage for the command-backed paths without making the fixture tests flaky.

Separate command execution from output parsing for testability:

- NetStat.queryTcpnetstat() — netstat -n -p tcp
- NetStat.queryNetstat() — netstat -n
- NetStat.queryTcpStats() — netstat -s (TCP section)
- NetStat.queryUdpStats() — netstat -s (UDP section)
- Xrandr.getEdidArrays() — xrandr --verbose

Each method now has a package-private overload accepting List<String>.
No public API changes.

Added fixture-based tests for TCP connection counting, connection
parsing, TCP/UDP statistics (Linux format), and EDID block parsing.
@dbwiddis
dbwiddis force-pushed the 3189-extract-unix-netstat-xrandr-parsing branch from 6ea6ad8 to 9f302da Compare April 28, 2026 04:47
@dbwiddis
dbwiddis merged commit fa85496 into oshi:master Apr 28, 2026
16 checks passed
@dbwiddis
dbwiddis deleted the 3189-extract-unix-netstat-xrandr-parsing branch April 28, 2026 05:05
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