Skip to content

Improve Unit Test Coverage#340

Merged
cjimti merged 10 commits intomasterfrom
fix/security_scorecard
Dec 30, 2025
Merged

Improve Unit Test Coverage#340
cjimti merged 10 commits intomasterfrom
fix/security_scorecard

Conversation

@cjimti
Copy link
Copy Markdown
Member

@cjimti cjimti commented Dec 30, 2025

This PR adds comprehensive unit tests to improve code coverage across multiple packages, bringing overall coverage from ~62% to 63.5% with significant improvements in individual packages.

Coverage Improvements

Package Before After Change
pkg/fwdmcp 63.6% 65.4% +1.8%
pkg/fwdmetrics 65.1% 80.6% +15.5%
pkg/fwdapi 48.0% 56.8% +8.8%
pkg/fwdns 44.8% 46.5% +1.7%
pkg/fwdsvcregistry 67.1% 91.4% +24.3%
Overall ~62% 63.5% +1.5%

New Test Files

pkg/fwdmcp/httpclient_test.go

Added tests for HTTP client adapter functions:

  • TestStateReaderHTTP_GetForward - Tests getting a single forward
  • TestMetricsProviderHTTP_GetServiceSnapshot - Tests service snapshot retrieval
  • TestDiagnosticsProviderHTTP_GetServiceDiagnostic - Tests service diagnostics
  • TestDiagnosticsProviderHTTP_GetForwardDiagnostic - Tests forward diagnostics
  • TestDiagnosticsProviderHTTP_GetNetworkStatus - Tests network status
  • TestNewAPIUnavailableError - Tests API error constructor

pkg/fwdmetrics/registry_test.go

Added tests for metrics registry operations:

  • TestRegistryRegisterUnregisterService - Service registration lifecycle
  • TestRegistryGetServiceNotFound - Non-existent service handling
  • TestRegistryUnregisterPortForward - Port forward unregistration
  • TestRegistryUnregisterPortForwardWithMultiple - Multiple port forwards
  • TestRegistryGetAllServices - Get all services
  • TestRegistryGetTotals - Aggregated totals across services
  • TestServiceMetricsGetTotals - Service-level totals
  • TestServiceMetricsRemovePortForward - Port forward removal
  • TestPortForwardMetricsKey - Key generation
  • TestPortForwardMetricsServiceKey - Service key generation
  • TestPortForwardMetricsEnableHTTPSniffing - HTTP sniffing feature

pkg/fwdmetrics/stream_test.go

Added tests for metrics stream wrapper:

  • TestMetricsStreamClose - Stream close delegation
  • TestMetricsStreamReset - Stream reset delegation
  • TestMetricsStreamHeaders - Headers passthrough
  • TestMetricsStreamIdentifier - Stream identifier
  • TestMetricsStreamMultipleOperations - Combined operations

pkg/fwdapi/logbuffer_test.go

Added tests for log buffer functionality:

  • TestBoundedSize - Size boundary checks (CodeQL CWE-770 compliance)
  • TestNewLogBuffer - Buffer creation
  • TestLogBufferAdd - Entry addition
  • TestLogBufferAddWrap - Ring buffer wrapping
  • TestLogBufferGetLast - Recent entry retrieval
  • TestLogBufferGetAll - All entries retrieval
  • TestLogBufferClear - Buffer clearing
  • TestLogBufferHookLevels - Logrus hook levels
  • TestLogBufferHookFire - Hook firing
  • TestGetLogBuffer - Global buffer singleton
  • TestGetLogBufferProvider - Provider interface
  • TestInitLogBuffer - Initialization
  • TestLogBufferConcurrency - Thread safety

pkg/fwdapi/manager_test.go (extended)

Added tests for manager interface setters:

  • TestManager_SetDiagnosticsProvider
  • TestManager_SetNamespaceController
  • TestManager_SetServiceCRUD
  • TestManager_SetKubernetesDiscovery
  • TestManager_GetNamespaceManager
  • TestNamespaceControllerMethods - Interface methods
  • TestServiceCRUDMethods - CRUD interface methods
  • TestKubernetesDiscoveryMethods - K8s discovery interface

pkg/fwdns/manager_test.go (extended)

Added tests for namespace manager:

  • TestManager_GetWatcherByKey - Watcher lookup by key
  • TestNamespaceWatcher_Done - Done channel behavior

pkg/fwdsvcregistry/fwdsvcregistry_test.go (extended)

Added tests using fake K8s client:

  • TestGet_ExistingService - Get existing service
  • TestGet_NonExistentService - Get non-existent service
  • TestGetAll - Get all services
  • TestGetAll_Empty - Empty registry
  • TestGetByNamespace - Filter by namespace
  • TestGetByNamespace_DifferentContexts - Multi-context filtering

Testing Approach

  1. httptest-based testing - Used Go's net/http/httptest package for HTTP client tests in fwdmcp

  2. Fake K8s client - Used k8s.io/client-go/kubernetes/fake for testing code that interacts with Kubernetes APIs

  3. Interface mocking - Created mock implementations for interfaces like StateReader, MetricsProvider, ServiceController, etc.

  4. Concurrency testing - Added tests for thread-safe operations with sync.WaitGroup and race condition checks

Packages Not Addressed

Some packages remain at lower coverage due to their nature:

  • pkg/fwdtui (20.6%) - Requires Bubble Tea TUI mocking framework
  • pkg/fwdport (57.2%) - Requires SPDY port-forward connection mocking
  • cmd/kubefwd/services (14.8%) - Integration-level orchestration code
  • cmd/kubefwd (0%) - CLI entry point

Running Tests

# Run all tests
go test ./...

# Run with coverage
go test -cover ./...

# Generate coverage report
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

# Run specific package tests
go test -v ./pkg/fwdmetrics/...
go test -v ./pkg/fwdsvcregistry/...

Related Issues

  • Improves project testability for future contributions
  • Supports OpenSSF Scorecard "Maintained" check

- Includes pinned Python dependencies with hashes for use in documentation generation workflows.
… registry behavior, metrics aggregation, and HTTP sniffing.
…, including operations like `Read`, `Write`, `Close`, `Reset`, and header and identifier validation.
…, namespace controller, service CRUD, and Kubernetes discovery integrations
Covers `LogBuffer` behavior including initialization, bounded size, entry addition, retrieval (all, last), clearing, hook levels, logging hooks, and concurrency.
Refactor and expand test coverage for namespace controller, service CRUD, and Kubernetes discovery methods. Includes mock integrations for methods like `AddNamespace`, `ListNamespaces`, `GetNamespace`, `RemoveNamespace`, and corresponding service operations.
Covers `GetWatcherByKey` and `NamespaceWatcher.Done` methods, including watcher retrieval, channel handling, and validation.
Covers service retrieval methods including `Get`, `GetAll`, `GetByNamespace`, and handling of empty and non-existent services, as well as multiple contexts and namespaces.
@codecov
Copy link
Copy Markdown

codecov bot commented Dec 30, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 63.67%. Comparing base (c762a68) to head (c3bdc17).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #340      +/-   ##
==========================================
+ Coverage   61.54%   63.67%   +2.13%     
==========================================
  Files          69       69              
  Lines       11071    11071              
==========================================
+ Hits         6814     7050     +236     
+ Misses       3981     3738     -243     
- Partials      276      283       +7     

see 10 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 41931d2 into master Dec 30, 2025
9 of 11 checks passed
@cjimti cjimti deleted the fix/security_scorecard branch December 30, 2025 19:28
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