Skip to content

Commit

Permalink
test: add test BlockHeightMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
tnv1 committed Nov 28, 2024
1 parent 1875d99 commit 63d808b
Showing 1 changed file with 90 additions and 0 deletions.
90 changes: 90 additions & 0 deletions server/middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package server

import (
"net/http"
"net/http/httptest"
"testing"

grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
)

// Dummy handler for testing
func dummyHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}

// Create router with middleware
func createRouter() *mux.Router {
router := mux.NewRouter()
router.Use(BlockHeightMiddleware)
router.HandleFunc("/", dummyHandler).Methods("GET")
return router
}

// Tests for BlockHeightMiddleware
func TestBlockHeightMiddleware(t *testing.T) {
router := createRouter()

tests := []struct {
name string
queryParam string
expectedStatus int
expectedHeader string
}{
{
name: "Valid height > 0",
queryParam: "123",
expectedStatus: http.StatusOK,
expectedHeader: "123",
},
{
name: "Height = 0",
queryParam: "0",
expectedStatus: http.StatusOK,
expectedHeader: "",
},
{
name: "Negative height",
queryParam: "-1",
expectedStatus: http.StatusBadRequest,
expectedHeader: "",
},
{
name: "Non-numeric height",
queryParam: "abc",
expectedStatus: http.StatusBadRequest,
expectedHeader: "",
},
{
name: "No height parameter",
queryParam: "",
expectedStatus: http.StatusOK,
expectedHeader: "",
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
if tc.queryParam != "" {
q := req.URL.Query()
q.Add("height", tc.queryParam)
req.URL.RawQuery = q.Encode()
}

rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)

assert.Equal(t, tc.expectedStatus, rec.Code)

if tc.expectedHeader != "" {
assert.Equal(t, tc.expectedHeader, rec.Header().Get(grpctypes.GRPCBlockHeightHeader))
} else {
assert.Empty(t, rec.Header().Get(grpctypes.GRPCBlockHeightHeader))
}
})
}
}

0 comments on commit 63d808b

Please sign in to comment.