Files
nuntius/cmd/server/main_test.go
T

53 lines
1.3 KiB
Go
Raw Normal View History

// Copyright (c) 2026 Petr Balvín <opensource@petrbalvin.org> (https://petrbalvin.org)
// SPDX-License-Identifier: MIT
//go:build linux || freebsd
package main
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
)
func TestStatusRecorder(t *testing.T) {
rec := httptest.NewRecorder()
sr := &statusRecorder{ResponseWriter: rec, status: http.StatusOK}
// Default status before WriteHeader.
if sr.status != http.StatusOK {
t.Errorf("initial status = %d, want %d", sr.status, http.StatusOK)
}
sr.WriteHeader(http.StatusNotFound)
if sr.status != http.StatusNotFound {
t.Errorf("status after WriteHeader = %d, want %d", sr.status, http.StatusNotFound)
}
// rec should also have the status set.
if rec.Code != http.StatusNotFound {
t.Errorf("rec.Code = %d, want %d", rec.Code, http.StatusNotFound)
}
}
func TestWithRequestLog(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
wrapped := withRequestLog(handler, logger, false)
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.RemoteAddr = "192.168.1.1:12345"
rec := httptest.NewRecorder()
wrapped.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want 200", rec.Code)
}
}