Skip to content

Commit

Permalink
test modem middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Bretterklieber committed May 24, 2024
1 parent 3828e7f commit 422c826
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
2 changes: 1 addition & 1 deletion middleware/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"testing"
)

func TestLogger(t *testing.T) {
func TestHttpLoggerMiddleware(t *testing.T) {
const requestIdField = "requestId"
const requestId = "657483"

Expand Down
70 changes: 70 additions & 0 deletions middleware/modem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package middleware

import (
"bytes"
"context"
"github.com/go-chi/chi/v5"
"github.com/stretchr/testify/assert"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
)

func TestHttpModemMiddleware(t *testing.T) {
tests := []struct {
name string
modem string
expectStatusCode int
}{
{
"Success",
"1",
http.StatusOK,
},
{
"Success Empty",
"",
http.StatusOK,
},
{
"Error invalid modem id",
".*'",
http.StatusBadRequest,
},
}

for _, tt := range tests {
var buff bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buff, nil))

req := httptest.NewRequest("GET", "http://localhost/?modem="+tt.modem, nil)
ctx := context.WithValue(req.Context(), "logger", logger)

chiCtx := chi.NewRouteContext()
ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
req = req.WithContext(ctx)

rr := httptest.NewRecorder()

mw := HttpModemMiddleware(logger)

// Run the middleware function
mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
modem, ok := r.Context().Value("modem").(string)

if tt.expectStatusCode == http.StatusOK {
if tt.modem != "" {
assert.Contains(t, buff.String(), "level=INFO msg=HttpModemMiddleware modem="+tt.modem)
}

assert.Equal(t, modem, tt.modem)
assert.True(t, ok)
} else {
assert.False(t, ok)
}
})).ServeHTTP(rr, req)

assert.Equal(t, tt.expectStatusCode, rr.Code)
}
}

0 comments on commit 422c826

Please sign in to comment.