Skip to content

test: Add testcase for http middleware #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 120 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package main

import (
"bytes"
"context"
"encoding/json"
"flag"
"io"
"log"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
Expand Down Expand Up @@ -95,6 +98,123 @@ func TestGetOpenapi(t *testing.T) {
testContains(t, "version: ", sb.String())
}

// TestAccessLogMiddleware tests accesslog middleware
func TestAccessLogMiddleware(t *testing.T) {
t.Parallel()

type record struct {
Method string `json:"method"`
Path string `json:"path"`
Query string `json:"query"`
Status int `json:"status"`
body []byte `json:"-"`
Bytes int `json:"bytes"`
}

tests := []record{
{
Method: "GET",
Path: "/test",
Query: "?key=value",
Status: http.StatusOK,
body: []byte(`{"hello":"world"}`),
},
{
Method: "POST",
Path: "/api",
Status: http.StatusCreated,
body: []byte(`{"id":1}`),
},
{
Method: "DELETE",
Path: "/users/1",
Status: http.StatusNoContent,
},
}

for _, tt := range tests {
name := strings.Join([]string{tt.Method, tt.Path, tt.Query, strconv.Itoa(tt.Status)}, " ")
t.Run(name, func(t *testing.T) {
t.Parallel()

var buffer strings.Builder
handler := accesslog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.Status)
w.Write(tt.body) //nolint:errcheck
}), slog.New(slog.NewJSONHandler(&buffer, nil)))

req := httptest.NewRequest(tt.Method, tt.Path+tt.Query, bytes.NewReader(tt.body))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

var log record
err := json.NewDecoder(strings.NewReader(buffer.String())).Decode(&log)
testNil(t, err)

testEqual(t, tt.Method, log.Method)
testEqual(t, tt.Path, log.Path)
testEqual(t, strings.TrimPrefix(tt.Query, "?"), log.Query)
testEqual(t, len(tt.body), log.Bytes)
testEqual(t, tt.Status, log.Status)
})
}
}

// TestRecoveryMiddleware tests recovery middleware
func TestRecoveryMiddleware(t *testing.T) {
t.Parallel()

tests := []struct {
name string
hf func(w http.ResponseWriter, r *http.Request)
wantCode int
wantPanic bool
}{
{
name: "no panic on normal http.Handler",
hf: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("success")) //nolint:errcheck
},
wantCode: http.StatusOK,
wantPanic: false,
},
{
name: "no panic on http.ErrAbortHandler",
hf: func(w http.ResponseWriter, r *http.Request) {
panic(http.ErrAbortHandler)
},
wantCode: http.StatusOK,
wantPanic: false,
},
{
name: "panic on http.Handler",
hf: func(w http.ResponseWriter, r *http.Request) {
panic("something went wrong")
},
wantCode: http.StatusInternalServerError,
wantPanic: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var buffer strings.Builder
handler := recovery(http.HandlerFunc(tt.hf), slog.New(slog.NewTextHandler(&buffer, nil)))

req := httptest.NewRequest("GET", "/test", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

testEqual(t, rec.Code, tt.wantCode)
if tt.wantPanic {
testContains(t, "panic!", buffer.String())
}
})
}
}

func testEqual[T comparable](t testing.TB, want, got T) {
t.Helper()
if want != got {
Expand Down
Loading