Skip to content

Tests/coverage#362

Merged
cjimti merged 41 commits intomasterfrom
tests/coverage
Jan 6, 2026
Merged

Tests/coverage#362
cjimti merged 41 commits intomasterfrom
tests/coverage

Conversation

@cjimti
Copy link
Copy Markdown
Member

@cjimti cjimti commented Jan 6, 2026

Improve test coverage to 80.5%. This PR adds comprehensive tests across multiple packages and fixes GoLand/IDE warnings in test files.

Coverage Improvements

Package Before After
pkg/fwdmetrics ~80% 93.0%
pkg/fwdmcp/testutil 0% 88.9%
pkg/fwdapi ~70% 73.9%
pkg/fwdapi/handlers ~85% 90.3%
Total ~79% 80.5%

New Tests Added

  • pkg/fwdmetrics/connection_test.go - Tests for MetricsConnection wrapper (CreateStream, Close, CloseChan, SetIdleTimeout, RemoveStreams)
  • pkg/fwdmetrics/dialer_test.go - Tests for MetricsDialer wrapper (Dial success/error/nil cases)
  • pkg/fwdmetrics/registry_test.go - Added tests for GetServiceSnapshot, Subscribe, Subscribe_Cancel, Subscribe_RegistryStop
  • pkg/fwdmcp/testutil/testutil_test.go - Comprehensive tests for test fixtures and assertions
  • pkg/fwdapi/handlers/handlers_test.go - Added TestServicesCRUDHandler_RemoveEmptyKey
  • pkg/fwdapi/manager_test.go - Added tests for direct namespaceManagerAdapter

Code Quality Fixes

Fixed GoLand/IDE warnings across test files:

  1. Unused parameters - Changed to _ prefix in mock implementations:

    • handlers_test.go: 15+ mock methods fixed
    • manager_test.go: Mock methods fixed
  2. Potential nil dereference - Changed t.Error() to t.Fatal() when checking err == nil before err.Error():

    • adapters_test.go: 14 occurrences
    • manager_test.go: 5 occurrences
  3. Deprecated APIs - Updated intstr.FromInt() to intstr.FromInt32():

    • adapters_test.go: 4 occurrences

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • Test improvement (new or updated tests)
  • Documentation update
  • Stability/performance improvement
  • Build/CI improvement

Note: New features are developed by maintainers only. See CONTRIBUTING.md for details.

Testing

  • Ran go test ./... locally
  • Tested manually with a Kubernetes cluster
  • Added new tests for changes (if applicable)
$ go test ./... -coverprofile=coverage.out
$ go tool cover -func=coverage.out | tail -1
total:                                          (statements)            80.5%

Checklist

  • My code follows the project's style guidelines (go fmt, go vet)
  • I have read CONTRIBUTING.md
  • I have updated documentation if needed
  • This PR is focused and does not include unrelated changes

Package Coverage Summary

ok      github.com/txn2/kubefwd/pkg/fwdapi              coverage: 73.9%
ok      github.com/txn2/kubefwd/pkg/fwdapi/handlers     coverage: 90.3%
ok      github.com/txn2/kubefwd/pkg/fwdapi/history      coverage: 95.4%
ok      github.com/txn2/kubefwd/pkg/fwdapi/middleware   coverage: 100.0%
ok      github.com/txn2/kubefwd/pkg/fwdcfg              coverage: 96.3%
ok      github.com/txn2/kubefwd/pkg/fwdhost             coverage: 90.9%
ok      github.com/txn2/kubefwd/pkg/fwdip               coverage: 95.8%
ok      github.com/txn2/kubefwd/pkg/fwdmcp              coverage: 86.2%
ok      github.com/txn2/kubefwd/pkg/fwdmcp/testutil     coverage: 88.9%
ok      github.com/txn2/kubefwd/pkg/fwdmetrics          coverage: 93.0%
ok      github.com/txn2/kubefwd/pkg/fwdnet              coverage: 77.3%
ok      github.com/txn2/kubefwd/pkg/fwdns               coverage: 61.9%
ok      github.com/txn2/kubefwd/pkg/fwdport             coverage: 57.9%
ok      github.com/txn2/kubefwd/pkg/fwdpub              coverage: 100.0%
ok      github.com/txn2/kubefwd/pkg/fwdservice          coverage: 80.3%
ok      github.com/txn2/kubefwd/pkg/fwdsvcregistry      coverage: 91.4%
ok      github.com/txn2/kubefwd/pkg/fwdtui              coverage: 80.0%
ok      github.com/txn2/kubefwd/pkg/fwdtui/components   coverage: 88.4%
ok      github.com/txn2/kubefwd/pkg/fwdtui/events       coverage: 100.0%
ok      github.com/txn2/kubefwd/pkg/fwdtui/state        coverage: 98.6%
ok      github.com/txn2/kubefwd/pkg/utils               coverage: 88.5%

cjimti added 30 commits January 5, 2026 22:05
- Introduced a test case for `CheckRoot` to verify behavior when running as root and non-root.
- Introduced extensive test coverage for LogsHandler system-related endpoints, including `System` and `ClearSystem`.
- Added tests for KubernetesHandler endpoints covering pod logs, pod listing, events, and endpoints retrieval.
- Ensured robust handling of edge cases such as missing parameters, invalid input, and uninitialized states.
- Added test cases for `isPodReady` covering various pod phases and container readiness scenarios.
- Introduced tests for `CloseIdleHTTPConnections` to verify behavior with and without `CloseIdleConnections` support in custom transports.
- Introduced tests for `RemoveAllocatedHosts` covering scenarios with and without registered hostnames.
- Verified graceful handling of permission-related errors when accessing `/etc/hosts`.
- Ensured registry state cleanup before and after test execution.
- Added test cases for `GetCurrentContext` covering valid configurations, invalid paths, and empty config scenarios.
- Verified correct context retrieval and error handling for different inputs.
- Added test cases for multiple models, including `DetailModel`, `HeaderModel`, `HelpModel`, `LogsModel`, `ServicesModel`, and `StatusBarModel`.
- Verified initialization, setter functionalities, and rendering methods for different scenarios.
- Ensured coverage of edge cases and improved reliability of model behaviors.
- Comprehensive test coverage added for `DetailModel` update scenarios, including handling of new message types and keypress events.
- Extended tests for HTTP tab scrolling, pod log requests, snapshot handling, and connect string generation.
- Verified edge cases and ensured robustness of model behavior under various conditions.
- Added test cases for `GetRESTClient` covering scenarios with unreachable clusters and invalid or empty configurations.
- Verified proper error handling and ensured function executes without panicking under various conditions.
- Added coverage for `KubernetesDiscoveryHTTP` methods: pod logs, pod listing, events, endpoints, and pod details retrieval.
- Included tests for error-handling scenarios and specific behaviors under various conditions.
- Added unit tests for `AnalysisProviderHTTP`, `HTTPTrafficProviderHTTP`, and `HistoryProviderHTTP` methods.
- Added tests for `NamespaceManagerAdapter` lazy initialization and error handling when the manager is nil.
- Introduced test cases for `Manager` shutdown handling, namespace manager setters, and `Run` method behavior.
- Verified pod discovery methods, including pod logs, pod listing, events, and endpoints retrieval.
- Added tests for `ListNamespaces`, `ListServices`, `GetService`, `ListPods`, `GetPod`, `GetEvents`, and `GetEndpoints` in `KubernetesDiscoveryAdapter`.
- Verified functionalities with a fake Kubernetes client for namespaces, services, pods, events, and endpoints.
- Included tests for edge cases like non-existent resources, terminating pods, and filtered events.
…lModel` behaviors

- Added test cases covering keypress handling, window size adjustments, scrolling behaviors, filtering, and various edge scenarios.
- Verified interactions with auto-follow, filtering, navigation, and rendering across the models.
- Ensured robustness and error handling in model update methods.
- Added tests for `StopGlobalPodInformer` to verify it stops correctly without panicking.
- Introduced coverage for `ResetGlobalPodInformer`, ensuring proper state reset and cleanup after execution.
…aviors

- Added tests for `StopWatcher`, `StopAll`, `GetCurrentContext`, `SetClientSet`, and `GetClientSet` methods in `Manager`.
- Introduced coverage for `NamespaceWatcher` methods, including `Info`.
- Verified manager cleanup, watcher removal, and robustness under various conditions.
- Added tests for `handleSetupLocalDevPrompt`, `handleConnectionGuidePrompt`, `handleForwardNamespacePrompt`, `handleDebugServicePrompt`, `handleQuickConnectPrompt`, and `handleAnalyzeIssuesPrompt`.
- Verified prompt behavior for various argument combinations, including `namespace`, `context`, `service_name`, `language`, and `symptom`.
- Ensured proper handling of nil arguments and validated prompt descriptions, messages, and content.
…`, and `handleContextsResource`

- Added test cases for `handleStatusResource`, including scenarios with healthy states, states with errors, and no active services.
- Added tests for `handleHTTPTrafficResource`, covering HTTP traffic snapshots, nil metrics, and no traffic scenarios.
- Added tests for `handleContextsResource`, verifying Kubernetes context listing behavior with mock discovery, including error and success cases.
- Added tests for `SetAnalysisProvider`, `SetHTTPTrafficProvider`, and `SetHistoryProvider`.
- Verified initial nil states and behavior when setting nil providers.
- Added test cases for `boundedSize`, covering various scenarios, including zero size, negative size, below/at/above limit, and extreme values.
- Verified expected behavior and proper limit enforcement.
- Introduced `TestBoundedSize` to validate the behavior of the `boundedSize` helper function.
- Covered scenarios with zero, negative, below/at/above limit, and extreme sizes to ensure proper enforcement of size limits.
- Added tests for `handleGetConnectionInfo`, including state fallback scenarios, namespace/context filtering, and service-not-found cases.
- Introduced tests for `handleFindServices` with various filters (namespace, port, query) and their combinations.
- Added tests for HTTP traffic, analysis, quick status, and history handlers with mock providers to validate responses and edge cases.
- Ensured proper handling of nil providers, missing keys, and default parameter values.
- Introduced `TestManager_SetCallbacks_WithModel` to verify proper handling of callback setters with both nil and non-nil values.
- Ensured no panics and correct behavior for `SetErroredServicesReconnector` and `SetRemoveForwardCallback`.
…space`

- Added tests to validate success and error paths for `loadServices`, ensuring proper handling of service discovery and errors.
- Covered scenarios for `forwardService`, including correct forwarding and error handling during conflicts.
- Introduced tests for `forwardNamespace` to verify namespace forwarding behavior, service counts, and error handling.
- Introduced tests for `ServiceForwardedMsg`, `NamespaceForwardedMsg`, and `BrowseContextsLoadedMsg` to validate forwarding behavior and error handling.
- Added tests for user interactions, including key presses (`Tab`, `?`, `Enter`), mouse clicks, and wheel events to confirm focus switching and functionality in logs and services views.
- Verified log streaming error handling and detail panel visibility during pod and service updates.
- Covered edge cases for nil streamers, missing selections, and context loading with default values.
…nostics adapters

- Introduced tests for `ServiceControllerAdapter` methods (`Reconnect`, `Sync`, and `ReconnectAll`) to validate error handling and behavior.
- Added `KubernetesDiscoveryAdapter` tests for `ListPods` with filters (service name, field selector, and label selector).
- Covered `DiagnosticsProviderAdapter` methods (`GetServiceDiagnostic` and `GetForwardDiagnostic`) under various scenarios, including active, error, partial states, and missing services/forwards.
- Introduced tests for `GetPod` covering pod states: terminating with waiting containers, running containers.
- Validated container state handling for `Terminating`, `Waiting`, and `Running` scenarios, including state reasons, last states, and container statuses.
- Introduced tests for `ReconnectErroredMsg`, `OpenDetailMsg`, `RemoveForwardMsg`, and various `KeyMsg` scenarios.
- Validated behavior for reconnecting errored services, opening detail panels, removing forwards with and without callbacks, and keypress handling (e.g., `r`, `q`, `/`).
- Covered edge cases like empty keys, nil commands, and filtering states.
- Added tests for `GetEvents` with specified limits and default limits.
- Validated behavior with event sorting by timestamp and handling of empty event lists.
cjimti and others added 11 commits January 6, 2026 00:48
- Add tests for addServiceHandler with valid and headless services
- Add tests for deleteServiceHandler with valid service
- Add tests for updateServiceHandler with selector/port changes
- Add tests for removeNamespaceServices with services in registry
- Add tests for NamespaceWatcher.Info not running state
- Add tests for Manager.StopWatcher with empty context
- Add tests for Manager.ListWatchers with watchers
- Add tests for parsePortMap with port mappings
- Add tests for splitPortMapping edge cases
- Add tests for lazy namespace manager adapter with real manager
- Add test for Manager.Run with missing state reader
- Coverage: fwdns 55.7% → 61.9%, total 77.3% → 77.6%

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Replace unused func parameters with _ (blank identifier)
- Fix mock implementations in browse_test.go, components_test.go
- Fix handler functions in events_test.go
- Fix manager_test.go mock implementations
- Fix fuzz_test.go, fwdhost_test.go, fwdpub_test.go unused params
- Fix cmd/kubefwd.go and cmd/mcp.go cobra callback params

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Convert if-else chains to switch statements throughout codebase
- Fix assignOp: use += instead of = ... +
- Fix singleCaseSwitch: convert single-case switches to if statements
- Standardize status calculation pattern across:
  - pkg/fwdapi/adapters.go
  - pkg/fwdapi/handlers/analyze.go
  - pkg/fwdapi/handlers/http_traffic.go
  - pkg/fwdapi/handlers/services.go
  - pkg/fwdmcp/resources.go
  - pkg/fwdmcp/tools.go
  - pkg/fwdtui/components/browse.go
  - pkg/fwdtui/components/detail.go
  - pkg/fwdtui/components/header.go
  - pkg/fwdtui/components/statusbar.go
  - cmd/kubefwd/services/services.go

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
…eir rules

- Added `gocritic`, `revive`, `predeclared`, and `nilnil` linters.
- Enabled specific tags and disabled noisy checks for `gocritic`.
- Configured selective rules for `revive` with customized severities.
- Increased issue limits per linter and for duplicate issues to improve coverage.
- Added exclusions for test files to relax unused parameters checks.
- Replace `0644` with `0o644` for explicit octal file permissions.
- Rename variables (`state` → `stateReader`, `events` → `eventItems`) for better readability and consistency.
- Update `http.NewRequest` to use `http.NoBody` instead of `nil` for clarity.
- Simplify and improve event sorting and limiting logic in `adapters.go`.
- Rename variables (`state` → `stateReader`, `context` → `k8sContext`) to improve readability and disambiguate semantics.
- Use `strings.EqualFold` for case-insensitive string comparisons in log filtering.
- Simplify context handling in multiple methods, ensuring proper fallback to the current context when absent.
- Update test variable names for improved readability (e.g., `events` → `eventList`, `count = 0` → `count`).
- Use `http.NoBody` instead of `nil` in `httptest.NewRequest` for explicit intent.
- Replace numeric file permissions (`0644`, `0755`) with explicit octal literals (`0o644`, `0o755`) for clarity.
- Improve file content comparison by using `bytes.Equal`.
…es and test-specific exclusions

- Disable `shadow`, `nestingReduce`, `evalOrder`, `deferUnlambda`, and `exposedSyncMutex` to reduce noise and false positives.
- Add `nilnil` to test-specific linters for common return patterns.
- Configure exclusions for test files, interfaces, and intentional patterns in `pkg` code.
@cjimti cjimti self-assigned this Jan 6, 2026
@codecov
Copy link
Copy Markdown

codecov bot commented Jan 6, 2026

Codecov Report

❌ Patch coverage is 80.29197% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.75%. Comparing base (080853c) to head (c529de9).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
pkg/fwdmcp/tools.go 72.97% 7 Missing and 3 partials ⚠️
cmd/kubefwd/services/services.go 0.00% 4 Missing ⚠️
pkg/fwdapi/adapters.go 84.00% 4 Missing ⚠️
pkg/fwdapi/handlers/logs.go 0.00% 2 Missing ⚠️
pkg/fwdapi/handlers/services.go 87.50% 2 Missing ⚠️
cmd/kubefwd/kubefwd.go 0.00% 1 Missing ⚠️
cmd/kubefwd/mcp/mcp.go 0.00% 1 Missing ⚠️
pkg/fwdapi/handlers/http_traffic.go 80.00% 1 Missing ⚠️
pkg/fwdtui/components/browse.go 75.00% 1 Missing ⚠️
pkg/fwdtui/components/detail.go 90.90% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           master     #362       +/-   ##
===========================================
+ Coverage   63.91%   77.75%   +13.83%     
===========================================
  Files          70       70               
  Lines       12461    12491       +30     
===========================================
+ Hits         7965     9712     +1747     
+ Misses       4166     2375     -1791     
- Partials      330      404       +74     
Files with missing lines Coverage Δ
pkg/fwdapi/handlers/analyze.go 90.10% <100.00%> (+0.10%) ⬆️
pkg/fwdapi/handlers/forwards.go 95.60% <100.00%> (ø)
pkg/fwdhost/fwdhost.go 82.75% <100.00%> (+12.06%) ⬆️
pkg/fwdmcp/httpclient.go 75.02% <100.00%> (+16.84%) ⬆️
pkg/fwdmcp/resources.go 89.21% <100.00%> (+25.68%) ⬆️
pkg/fwdns/manager.go 61.85% <100.00%> (+17.58%) ⬆️
pkg/fwdtui/components/header.go 93.33% <100.00%> (+19.13%) ⬆️
pkg/fwdtui/components/statusbar.go 100.00% <100.00%> (+6.06%) ⬆️
cmd/kubefwd/kubefwd.go 0.00% <0.00%> (ø)
cmd/kubefwd/mcp/mcp.go 0.00% <0.00%> (ø)
... and 8 more

... and 14 files with indirect coverage changes

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

@cjimti cjimti merged commit 6ad2509 into master Jan 6, 2026
12 checks passed
@cjimti cjimti deleted the tests/coverage branch January 6, 2026 20:10
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