Files
go-app/pkg/srv/http/http_test.go

89 lines
1.8 KiB
Go

package http
import (
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
)
func TestInitHTTPServer(t *testing.T) {
cfg := &config.AppConfig{
Name: "test-app",
HTTP: &config.HTTPConfig{
Enabled: true,
Listen: "127.0.0.1:0", // Use random available port
},
OTEL: &config.OTELConfig{
Enabled: true,
},
}
ctx := cfg.AddToCtx(context.Background())
ctx, _ = otel.Init(ctx)
httpOpts := &opts.AppHTTP{
Ctx: ctx,
Funcs: []opts.HTTPFunc{
{
Path: "/test",
HandlerFunc: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
},
},
},
}
shutdown, done, err := InitHTTPServer(httpOpts)
assert.NoError(t, err)
assert.NotNil(t, shutdown)
assert.NotNil(t, done)
// Shutdown the server
err = shutdown(context.Background())
assert.NoError(t, err)
}
func TestHealthCheck(t *testing.T) {
req := httptest.NewRequest("GET", "/health", nil)
w := httptest.NewRecorder()
handleHealthCheckFunc(context.Background())(w, req)
resp := w.Result()
body, _ := io.ReadAll(resp.Body)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "ok", string(body))
}
func TestLoggingMiddleware(t *testing.T) {
cfg := &config.AppConfig{
Name: "test-app",
HTTP: &config.HTTPConfig{
LogRequests: true,
},
}
ctx := cfg.AddToCtx(context.Background())
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
middleware := loggingMiddleware(ctx, handler)
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
middleware.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}