log_test.go

79 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
package router

import (
	"bytes"
	"log"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"testing"
)

func TestWithLogger_CapturesStatus(t *testing.T) {
	handler := WithLogger()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNotFound)
	}))

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

	if rec.Code != http.StatusNotFound {
		t.Errorf("expected 404, got %d", rec.Code)
	}
}

func TestWithLogger_DevFormat(t *testing.T) {
	t.Setenv("ENV", "development")

	var buf bytes.Buffer
	log.SetOutput(&buf)
	defer log.SetOutput(os.Stderr)

	handler := WithLogger()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))

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

	output := buf.String()
	if !strings.Contains(output, "GET") || !strings.Contains(output, "/hello") || !strings.Contains(output, "200") {
		t.Errorf("dev log should contain method, path, status; got: %s", output)
	}
	if strings.Contains(output, `"method"`) {
		t.Errorf("dev log should not be JSON; got: %s", output)
	}
}

func TestWithLogger_ProductionJSON(t *testing.T) {
	t.Setenv("ENV", "production")

	var buf bytes.Buffer
	log.SetOutput(&buf)
	defer log.SetOutput(os.Stderr)

	handler := WithLogger()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusCreated)
	}))

	rec := httptest.NewRecorder()
	req := httptest.NewRequest("POST", "/api/items", nil)
	handler.ServeHTTP(rec, req)

	output := buf.String()
	if !strings.Contains(output, `"method":"POST"`) {
		t.Errorf("production log should be JSON with method; got: %s", output)
	}
	if !strings.Contains(output, `"status":201`) {
		t.Errorf("production log should contain status 201; got: %s", output)
	}
}

func TestLogWriter_Flush(t *testing.T) {
	rec := httptest.NewRecorder()
	lw := &logWriter{ResponseWriter: rec, status: 200}
	lw.Flush() // should not panic
}