From 63d808b89d582881124157827af2cfa52d32eb1b Mon Sep 17 00:00:00 2001 From: tnv1 Date: Thu, 28 Nov 2024 11:18:05 +0700 Subject: [PATCH] test: add test BlockHeightMiddleware --- server/middleware_test.go | 90 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 server/middleware_test.go diff --git a/server/middleware_test.go b/server/middleware_test.go new file mode 100644 index 00000000..1b9bddda --- /dev/null +++ b/server/middleware_test.go @@ -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)) + } + }) + } +}