Skip to content

Conversation

thzgajendra
Copy link

@thzgajendra thzgajendra commented Sep 22, 2025

WebSocket Package: 100% Test Coverage & Linter Fixes

📋 Overview

This PR implements comprehensive test coverage for the pkg/gofr/websocket package, achieving 100% test coverage while fixing all linter issues. The changes include extensive test cases covering all functionality, edge cases, performance scenarios, and proper error handling.

🎯 Goals Achieved

  • 100% Test Coverage - All functions and methods in the websocket package are fully tested
  • Zero Linter Issues - All golangci-lint issues resolved without disabling any linters
  • Comprehensive Test Suite - Tests cover normal operations, edge cases, error conditions, and performance
  • Code Quality - Proper error handling, thread safety, and clean code practices

📊 Test Coverage Results

PASS
coverage: 100.0% of statements
ok      gofr.dev/pkg/gofr/websocket     2.143s

Coverage Breakdown:

  • websocket.go: 100% coverage across all 20 functions
  • options.go: 100% coverage across all 7 option functions
  • mock_interfaces.go: 100% coverage across all 4 mock functions

🔧 Changes Made

1. Consolidated Test File

  • File: pkg/gofr/websocket/websocket_test.go
  • Lines: 986 lines of comprehensive test coverage
  • Approach: Consolidated all test cases into a single, well-organized test file

2. Core Functionality Tests

  • WSUpgrader Tests: Creation, options, upgrade operations
  • Connection Tests: Bind, WriteMessage, ReadMessage, deadlines

3. Edge Case Coverage

  • Error Handling: Invalid JSON, closed connections, nil pointers
  • Concurrent Operations: Thread-safe operations with proper synchronization
  • Performance Tests: Large message handling, concurrent writes

🚀 Key Features Tested

Thread Safety

  • Concurrent read/write operations
  • Thread-safe connection management
  • Proper mutex usage verification

Error Handling

  • Invalid JSON parsing
  • Closed connection handling
  • Network error scenarios
  • Upgrade failure handling

Performance

  • Large message throughput
  • Concurrent connection scaling
  • Memory usage optimization

WebSocket Protocol

  • Text message handling
  • Connection lifecycle management
  • Deadline enforcement
  • Proper cleanup

🧪 Test Execution

Run All Tests

cd pkg/gofr/websocket
go test -v

Run with Coverage

go test -cover -coverprofile=coverage.out
go tool cover -func=coverage.out

Run Performance Tests

go test -v -short=false

Run Linter

golangci-lint run .

📈 Metrics

  • Total Test Functions: 25+
  • Test Coverage: 100%
  • Linter Issues: 0
  • Test Execution Time: ~2.1 seconds
  • Lines of Test Code: 986

🔍 Code Quality Improvements

Error Handling

  • Proper error checking in HTTP handlers
  • Graceful error recovery in tests
  • Clear error messages and assertions

Code Organization

  • Logical test grouping by functionality
  • Clear test naming conventions
  • Comprehensive test documentation

Performance

  • Efficient test execution
  • Minimal resource usage
  • Proper cleanup and teardown

✅ Checklist

  • I have formatted my code using goimport and golangci-lint.
  • All new code is covered by unit tests.
  • This PR does not decrease the overall code coverage.
  • I have reviewed the code comments and documentation for clarity.

Ready for Review

Screenshot 2025-09-22 at 6 30 22 PM

Copy link
Member

@coolwednesday coolwednesday left a comment

Choose a reason for hiding this comment

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

Here are some areas for improvement in the tests:

  1. Error Handling Coverage:

    • Some tests, like TestConnection_Bind_ErrorPaths, could include more diverse scenarios for error handling, such as network interruptions or unexpected server responses.
  2. Mock Usage:

    • Some unrelated tests use real WebSocket connections unnecessarily. Mocking could improve test speed and isolation, especially in TestConnection_Bind and TestConnection_ReadMessage. Please note not necessarily for all tests.
  3. Test Duplication:

    • There is some duplication in setup code for WebSocket servers. Extracting this into reusable helper functions could improve maintainability. Add T.Helper for them.
  4. Unimplemented Methods:

    • Tests for unimplemented methods like Param and PathParam are redundant unless these methods are expected to be implemented in the future.
  5. Test Coverage for Options:

    • Ensure all combinations of options in NewWSUpgrader are tested, especially for conflicting or invalid configurations. - Conflicting options should give error. (this will require real websocket connection)

    Other than this, @thzgajendra, Good work !

@thzgajendra
Copy link
Author

Test Improvements in WebSocket Package

This PR addresses multiple gaps and improvements in the WebSocket test suite:

  • Error Handling Coverage

  • Expanded TestConnection_Bind_ErrorPaths to cover more diverse error handling cases, including:

    • Network interruptions
    • Unexpected server responses
  • Mock Usage

  • Replaced some real WebSocket connections with mocks where appropriate.

    • This improves test speed and isolation.
    • Example: TestConnection_Bind and TestConnection_ReadMessage.
    • (Note: not applied to all tests — only where relevant.)
  • Test Duplication

  • Reduced duplication of setup code for WebSocket servers.

  • Extracted common setup logic into reusable helper functions.

  • Added t.Helper() annotations for better test stack traces.

  • Unimplemented Methods

  • Removed redundant tests for unimplemented methods (Param, PathParam).

  • Tests will be added later only if these methods are implemented.

  • Test Coverage for Options

  • Ensured all combinations of options in NewWSUpgrader are tested:

    • Valid configurations
    • Conflicting/invalid configurations → expected to return error
    • (Note: conflict validation requires a real WebSocket connection, so those tests are kept with real connections.)

Overall, this PR improves coverage, maintainability, and reliability of the WebSocket test suite while removing unnecessary or redundant tests.

Copy link
Member

@Umang01-hash Umang01-hash left a comment

Choose a reason for hiding this comment

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

  • All the Mock Tests, Constants Tests and Performance Tests can be removed as :
  1. Mock Tests are not contributing to anything in coverage.
  2. Performance tests are already set to skip in short mode, indicating they're not core tests
  3. Constants Tests just verifies constant values

@@ -1,9 +1,7 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: interfaces.go
Copy link
Member

Choose a reason for hiding this comment

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

Why they are being removed??

data = new(string)
default:
data = &map[string]any{}
if tt.expectError {
Copy link
Member

Choose a reason for hiding this comment

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

Test methods should not contains if else statements like this. If required we can break the method into two methods one for success case and other for error.

defer wg.Done()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if tt.expectError {
Copy link
Member

Choose a reason for hiding this comment

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

Test methods should not contains if else statements like this. If required we can break the method into two methods one for success case and other for error.

dialer := websocket.DefaultDialer
conn, resp, err := dialer.Dial(url, nil)

if tt.expectError {
Copy link
Member

Choose a reason for hiding this comment

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

Remove this if else also please

connections := manager.ListConnections()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if tt.expectError {
Copy link
Member

Choose a reason for hiding this comment

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

Here also we can break it into two method with and without error but no if else like this.


mockConn := &Connection{Conn: &websocket.Conn{}}
manager.AddWebsocketConnection("testService", mockConn)
if tt.expectError {
Copy link
Member

Choose a reason for hiding this comment

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

Here also

wsConn := &Connection{Conn: conn}
err = wsConn.Bind(tt.targetType)

if tt.expectError {
Copy link
Member

Choose a reason for hiding this comment

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

Please refactor this too.

@thzgajendra
Copy link
Author

Sure , I'll Update these recommended changes.

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.

Enhance Test Coverage for pkg/gofr/websocket module
3 participants