Merged
Conversation
- 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.
…ion and update struct references
…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.
- 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`.
…og.Message` usage.
…ode in tests and components
…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.
…ce` methods in `adapters_test.go`. - Add unit tests for `splitLogLines` with various newline scenarios. - Add tests for `GetPodLogs` handling invalid `sinceTime`, non-existent pods, extreme `tailLines`, and valid options. - Add scenario for `AddService` with a `nil` namespace manager.
…t.go` - Include tests for `StreamNilStreamer`, `StreamClosedChannel`, `StreamWithTypeFilter`, and event-to-response mapping. - Add coverage for optional and empty fields in `mapEventToResponse`. - Verify event type parsing for all valid and default scenarios.
…rAdapter` - Add tests for `ListNamespaces` and `GetNamespace` (non-existent case) in `NamespaceManagerAdapter`. - Validate behavior with a nil manager in `LazyNamespaceManagerAdapter`, including error cases for `AddNamespace`, `RemoveNamespace`, and `GetNamespace`.
…l_test.go` - Add tests for service generation (`KFT1Services`, `KFT2Services`) and snapshot creation with/without headless services. - Include tests for forwarding snapshot generation and store population methods (`PopulateStore`, `PopulateStoreKFT1`, `PopulateStoreKFT2`). - Expand test coverage for IP formatting, integer-to-string conversion, and store assertions (e.g., empty store, service/forward existence). - Validate namespace-specific service and forward counts.
- Cover scenarios including successful dialing, error handling, nil metrics, and multiple protocols. - Ensure proper wrapping of connections with `MetricsConnection` when metrics are provided.
- Cover scenarios for stream creation (data streams, error streams, nil metrics). - Include tests for connection operations: `Close`, `CloseChan`, `SetIdleTimeout`, and `RemoveStreams`. - Validate correct wrapping and unwrapping of streams.
…nused parameters - Standardize signatures in mock methods by replacing unused parameters with `_`. - Update relevant test cases to ensure consistency and readability. - Add new test cases for `RemoveEmptyKey` in `handlers_test.go` and service snapshot functionality in `registry_test.go`. - Replace `int` with `int32` for `TargetPort` in test service definitions. - Enhance assertion behavior by replacing `t.Error` with `t.Fatal` for critical test failures.
Resolved merge conflicts in test files: - pkg/fwdapi/manager_test.go: Use t.Fatal for nil checks, keep additional tests - pkg/fwdapi/adapters_test.go: Use t.Fatal for nil checks, intstr.FromInt32, keep tests - pkg/fwdapi/handlers/handlers_test.go: Keep event streaming tests - .gitignore: Keep coverage.html entry 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
…determination, and recommendation generation logic. - Introduced `classifyError`, `determineStatus`, `buildSummaryMessage`, `buildIssues`, and `buildRecommendations` to simplify `Analyze` method logic. - Improved readability and maintainability by reducing nested loops and conditions. - Enhanced testability with smaller, focused functions for error handling and analysis steps.
- Extracted specific handlers (`handleKeyMsg`, `handleMouseMsg`, `handleClearCopied`, etc.) to simplify `Update` method. - Improved readability and maintainability by grouping behavior into focused methods. - Enhanced key and mouse event handling with clearer responsibilities for scroll, tab navigation, and clipboard operations.
- Extracted specific handlers (`handleKeyMsg`, `handleMouseMsg`, `handleClearCopied`, etc.) to simplify `Update` method. - Improved readability and maintainability by grouping behavior into focused methods. - Enhanced key and mouse event handling with clearer responsibilities for scroll, tab navigation, and clipboard operations.
…zation, signal handling, and namespace management logic - Extracted `validateEnvironment`, `setupSignalHandler`, `createNamespaceManager`, and other focused functions to simplify `runCmd`. - Improved readability and maintainability by grouping responsibilities into modular methods. - Enhanced namespace and context resolution logic with clearer separation of concerns.
- Extracted specific handlers (`handleKeyMsg`, `handleMouseMsg`, `handleBrowseMessage`, etc.) to simplify `Update` method. - Improved readability and maintainability by grouping behavior into smaller, focused methods. - Enhanced message handling with clearer separation of responsibilities for components and global operations.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #363 +/- ##
==========================================
+ Coverage 77.71% 80.48% +2.76%
==========================================
Files 70 70
Lines 12491 12620 +129
==========================================
+ Hits 9708 10157 +449
+ Misses 2377 2050 -327
- Partials 406 413 +7
🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Reduces cyclomatic complexity across the codebase to improve Go Report Card score and code maintainability. This PR refactors 5 high-complexity functions by extracting helper methods and consolidating switch statement handling.
Major Complexity Reductions
DetailModel.UpdaterunCmdRootModel.UpdateSyncPodForwardsAnalyzeHandler.AnalyzeFunctions Over Threshold (15)
Refactoring Techniques Used
handleKeyMsg,handleMouseMsg)handleComponentMessage,handleBrowseMessage)isPodEligible,removeStaleForwards,syncNormalService)Type of Change
Related Issues
Fixes # (Go Report Card gocyclo improvements)
Testing
go test ./...locally (22 packages pass)CI Verification
Checklist
go fmt,go vet)Files Changed
pkg/fwdtui/components/detail.go
handleKeyMsg,handleMouseMsgfromUpdatehandleNumberKey,handleTabNavigation,handleYankKeyhandleHTTPScroll,handleVimScrollHTTP,handleVimScrollLogscmd/kubefwd/services/services.go
runCmd:validateEnvironment,detectAndConfigureIdleModeinitializeTUIMode,initializeAPIModesetupHostsFile,handleStaleIPscreateNamespaceManager,wireUpAdaptersstartAPIServer,runMainLoop,performShutdownpkg/fwdtui/ui.go
RootModel.Updateusing dispatcher patternhandleWindowSizeMsg,handleKeyMsg,handleMouseMsghandleGlobalKeys,handleFocusedComponentKeyhandleComponentMessage,handleBrowseMessagepkg/fwdservice/fwdservice.go
SyncPodForwards:isPodEligible,scheduleRetry,getForwardInfosremoveStaleForwards,podStillEligible,findKeyToKeepsyncHeadlessService,syncNormalService,doSyncPodspkg/fwdapi/handlers/analyze.go
Analyze:classifyError,buildIssuesbuildRecommendations,buildActionsdetermineStatus,buildSummaryMessage,getUptimeFormatting Fixes
pkg/fwdapi/middleware/middleware.gopkg/fwdns/manager_test.go