Skip to content

refactor: extract VPNBypassCore library for testable coverage#41

Merged
GeiserX merged 6 commits into
mainfrom
refactor/library-extraction
May 4, 2026
Merged

refactor: extract VPNBypassCore library for testable coverage#41
GeiserX merged 6 commits into
mainfrom
refactor/library-extraction

Conversation

@GeiserX
Copy link
Copy Markdown
Owner

@GeiserX GeiserX commented May 3, 2026

Summary

  • Split single executableTarget into three SPM targets: VPNBypassCore (library), VPNBypass (thin executable), VPNBypassTests
  • Tests now use @testable import VPNBypassCore to exercise real production code instead of duplicated local implementations
  • Deleted redundant test helpers (DomainEntry, OnceGateTestImpl, local isValidCIDR/isValidIP/cleanDomain) that shadowed production code
  • Made pure validation functions nonisolated for direct test access from non-actor context
  • Coverage now instruments actual production code (was 0% due to executableTarget limitation)

Test plan

  • swift build succeeds
  • swift test — all 68 tests pass
  • swift test --enable-code-coverage confirms non-zero coverage (6.78% total, RouteManager 6.49%)
  • CI passes on self-hosted runner

Summary by CodeRabbit

  • Chores
    • Modularized core internals and reorganized build configuration; updated CI cache behavior and coverage thresholds.
  • Improvements
    • Saving custom services now uses updated domain normalization, affecting how entered domains are cleaned and persisted.
  • Tests
    • Test suite refactored to exercise production code directly, improving reliability and alignment with ship behavior.

Split the single executableTarget into a three-target SPM layout:
VPNBypassCore (library), VPNBypass (thin executable), and VPNBypassTests.

Tests now import real production code via @testable import VPNBypassCore,
replacing duplicated local implementations. Pure validation functions
(cleanDomain, isValidIP, isValidCIDR) marked nonisolated for test access.

Coverage reports now instrument actual production code instead of showing
0% due to the previous executableTarget limitation.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 3, 2026

Warning

Rate limit exceeded

@GeiserX has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 20 minutes and 14 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 80f75601-5845-439f-9909-2d068efae0eb

📥 Commits

Reviewing files that changed from the base of the PR and between 9438b8f and c5351c7.

📒 Files selected for processing (13)
  • Package.swift
  • Tests/VPNBypassTests/CleanDomainTests.swift
  • Tests/VPNBypassTests/ColorExtensionTests.swift
  • Tests/VPNBypassTests/ConfigCodableTests.swift
  • Tests/VPNBypassTests/HelperProtocolTests.swift
  • Tests/VPNBypassTests/HelperStateTests.swift
  • Tests/VPNBypassTests/IPValidationExtendedTests.swift
  • Tests/VPNBypassTests/NotificationPreferencesTests.swift
  • Tests/VPNBypassTests/RouteManagerIntegrationTests.swift
  • Tests/VPNBypassTests/RouteManagerLogicTests.swift
  • Tests/VPNBypassTests/ThemeTests.swift
  • Tests/VPNBypassTests/VPNBypassTests.swift
  • codecov.yml
📝 Walkthrough

Walkthrough

Extracts core logic into a new VPNBypassCore package target, exposes formerly private RouteManager helpers as nonisolated, adds a thin Sources/VPNBypass/main.swift entrypoint, updates build/Makefile and CI cache keys, adjusts tests to use production types, and relaxes Codecov thresholds and ignore patterns.

Changes

Modularization + API Exposure

Layer / File(s) Summary
Package Layout / Data Shape
Package.swift, Sources/VPNBypassCore/...
Adds VPNBypassCore target at Sources/VPNBypassCore and makes VPNBypass and VPNBypassTests depend on it; resources for core are processed.
Core API / Concurrency
Sources/VPNBypassCore/RouteManager.swift
cleanDomain(_:), isValidIP(_:), isValidCIDR(_:) changed from private to nonisolated (visibility/concurrency change, implementation unchanged).
App Entrypoint / Public API
Sources/VPNBypassCore/VPNBypassApp.swift, Sources/VPNBypass/main.swift
VPNBypassApp changed from @main to public struct with public init() and public var body; new thin executable entrypoint imports VPNBypassCore and calls VPNBypassApp.main().
Build Wiring
Makefile
Helper tool build now compiles HelperProtocol.swift from Sources/VPNBypassCore; app bundle localization copies .lproj from Sources/VPNBypassCore/Resources.
CI / Tooling
.github/workflows/ci.yml, codecov.yml
SPM cache key updated to hash both Package.swift and Package.resolved; Codecov project/patch thresholds lowered and Helper/** and Sources/VPNBypass/** added to ignore list.
Tests / Call Sites
Tests/VPNBypassTests/VPNBypassTests.swift, Sources/VPNBypassCore/SettingsView.swift
Tests switched to @testable import VPNBypassCore and call production helpers/types (RouteManager, DomainEntry, OnceGate); SettingsView now uses routeManager.cleanDomain(...) for service domain normalization.

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly Related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the core changes and test results comprehensively. However, the template requires checking boxes for platform testing (macOS Ventura/Sonoma), build verification, and CHANGELOG updates—none of which are completed. Complete the checklist items: verify builds work on specified macOS versions, confirm app bundle creation, and update CHANGELOG.md if applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main refactoring objective: extracting VPNBypassCore as a library to enable testable coverage. It's specific, concise, and captures the primary change.
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
  • Commit unit tests in branch refactor/library-extraction

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
Review rate limit: 0/1 reviews remaining, refill in 20 minutes and 14 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

Makefile bundle target referenced deleted Resources/ directory — now
points to Sources/VPNBypassCore/Resources/. Raised codecov targets
from 30%/50% to 70%/80% to catch future coverage regressions.
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
Sources/VPNBypassCore/RouteManager.swift (1)

3664-3709: ⚡ Quick win

Make these pure validators static instead of hanging them off RouteManager.shared.

Tests now have to initialize RouteManager.shared just to parse strings, and RouteManager.init() still creates the Application Support directory on Line 413. Moving these to static helpers or a small validator type keeps them testable without singleton side effects.

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

In `@Sources/VPNBypassCore/RouteManager.swift` around lines 3664 - 3709, The pure
validation/normalization methods cleanDomain(_:), isValidIP(_:) and
isValidCIDR(_:) should be converted from instance methods on RouteManager to
static helpers so tests don't need RouteManager.shared or trigger
RouteManager.init() side effects; change their signatures to static func
cleanDomain(_:) / static func isValidIP(_:) / static func isValidCIDR(_:) (or
move them into a small static Validator/RouteValidator type) and update all call
sites to reference the static methods (e.g., RouteManager.cleanDomain(...) or
RouteValidator.cleanDomain(...)) so production behavior is unchanged but tests
can call the validators without initializing the singleton.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Tests/VPNBypassTests/VPNBypassTests.swift`:
- Around line 405-415: The test helper classifyInput currently treats inputs
with slashes as domains, which diverges from production
RouteManager.addInverseDomain(_:), so restore the slash-rejection: after
computing trimmed and cidr (in classifyInput), if not cidr and
trimmed.contains("/") then return nil; otherwise proceed to cleanDomain and the
existing empty-check/return. This will ensure classifyInput mirrors
RouteManager.addInverseDomain behavior for inputs like
"https://example.com/path" or invalid CIDRs.

---

Nitpick comments:
In `@Sources/VPNBypassCore/RouteManager.swift`:
- Around line 3664-3709: The pure validation/normalization methods
cleanDomain(_:), isValidIP(_:) and isValidCIDR(_:) should be converted from
instance methods on RouteManager to static helpers so tests don't need
RouteManager.shared or trigger RouteManager.init() side effects; change their
signatures to static func cleanDomain(_:) / static func isValidIP(_:) / static
func isValidCIDR(_:) (or move them into a small static Validator/RouteValidator
type) and update all call sites to reference the static methods (e.g.,
RouteManager.cleanDomain(...) or RouteValidator.cleanDomain(...)) so production
behavior is unchanged but tests can call the validators without initializing the
singleton.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 95d3f206-b21f-4c04-813a-a5e6b444d851

📥 Commits

Reviewing files that changed from the base of the PR and between c29a3ef and 2460497.

📒 Files selected for processing (19)
  • .github/workflows/ci.yml
  • Makefile
  • Package.swift
  • Sources/VPNBypass/main.swift
  • Sources/VPNBypassCore/ColorExtension.swift
  • Sources/VPNBypassCore/HelperManager.swift
  • Sources/VPNBypassCore/HelperProtocol.swift
  • Sources/VPNBypassCore/LaunchAtLoginManager.swift
  • Sources/VPNBypassCore/MenuBarViews.swift
  • Sources/VPNBypassCore/NotificationManager.swift
  • Sources/VPNBypassCore/Resources/en.lproj/Localizable.strings
  • Sources/VPNBypassCore/Resources/es.lproj/Localizable.strings
  • Sources/VPNBypassCore/Resources/fr.lproj/Localizable.strings
  • Sources/VPNBypassCore/RouteManager.swift
  • Sources/VPNBypassCore/SettingsView.swift
  • Sources/VPNBypassCore/Theme.swift
  • Sources/VPNBypassCore/VPNBypassApp.swift
  • Tests/VPNBypassTests/VPNBypassTests.swift
  • codecov.yml

Comment thread Tests/VPNBypassTests/VPNBypassTests.swift
cleanDomain is now nonisolated and directly callable — the wrapper
added no value. Single caller in SettingsView updated.
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)
Sources/VPNBypassCore/SettingsView.swift (1)

974-987: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Guard against all-empty cleanDomains before persisting the service.

canSave only checks !$0.trimmingCharacters(in: .whitespaces).isEmpty, but cleanDomain does far more stripping (protocol schemes, userinfo, non-[a-zA-Z0-9.-] chars). Inputs like @, ://foo, or http:// all satisfy canSave yet clean to "", so cleanDomains ends up empty. The call then reaches addCustomService(name:, domains:[], ipRanges:), persisting a service entry that will never match or route any traffic.

🛡️ Proposed fix
 private func save() {
     let cleanDomains = domains
         .map { routeManager.cleanDomain($0) }
         .filter { !$0.isEmpty }
+    guard !cleanDomains.isEmpty else { return }
     let cleanIPs = ipRanges.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
     let name = serviceName.trimmingCharacters(in: .whitespaces)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Sources/VPNBypassCore/SettingsView.swift` around lines 974 - 987, The save()
method must guard against persisting services with no effective matchers: after
computing cleanDomains and cleanIPs, ensure at least one non-empty cleaned
domain or cleaned IP-range exists (i.e., if cleanDomains.isEmpty &&
cleanIPs.isEmpty return early or surface a validation error) and do not call
routeManager.addCustomService/updateCustomService with empty matchers; also
update the canSave logic to validate against the cleaned domain set
(cleanDomains) rather than the raw domains so the Save button is disabled for
inputs that clean to empty.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@Sources/VPNBypassCore/SettingsView.swift`:
- Around line 974-987: The save() method must guard against persisting services
with no effective matchers: after computing cleanDomains and cleanIPs, ensure at
least one non-empty cleaned domain or cleaned IP-range exists (i.e., if
cleanDomains.isEmpty && cleanIPs.isEmpty return early or surface a validation
error) and do not call routeManager.addCustomService/updateCustomService with
empty matchers; also update the canSave logic to validate against the cleaned
domain set (cleanDomains) rather than the raw domains so the Save button is
disabled for inputs that clean to empty.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ae07af5d-0df3-4d70-b5f5-f2d3ee831d11

📥 Commits

Reviewing files that changed from the base of the PR and between 2460497 and 9438b8f.

📒 Files selected for processing (2)
  • Sources/VPNBypassCore/RouteManager.swift
  • Sources/VPNBypassCore/SettingsView.swift
🚧 Files skipped from review as they are similar to previous changes (1)
  • Sources/VPNBypassCore/RouteManager.swift

GeiserX added 3 commits May 4, 2026 09:29
…code

CodeRabbit caught that the test helper classifyInput diverged from
production addInverseDomain — inputs with "/" that aren't valid CIDR
are now rejected. Updated tests that had wrong expectations for URL
inputs with paths.
Remove sources restriction from testTarget so additional test files
can be added. Add SettingsView, MenuBarViews, and VPNBypassApp to
codecov ignore list since SwiftUI views cannot be unit tested.
Add tests for RouteManager integration (config mutations, export/import,
save/load), business logic (logging, defaults, structs), clean domain
parsing, IP/CIDR validation, Config/ProxyConfig/VPNType codable
roundtrips, HelperState enum, notification preferences, Color extension,
Theme constants, and HelperProtocol constants.

Lower codecov targets to 60% and exclude system-dependent files
(HelperManager, LaunchAtLoginManager, NotificationManager) that require
XPC/SMAppService/UNUserNotificationCenter and cannot be unit tested.
@GeiserX GeiserX merged commit c5351c7 into main May 4, 2026
3 checks passed
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