2015-06-13 00:21:19 +08:00
|
|
|
package log
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"strings"
|
|
|
|
"testing"
|
2016-03-21 11:56:13 +08:00
|
|
|
|
|
|
|
"github.com/mholt/caddy/middleware"
|
2015-06-13 00:21:19 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type erroringMiddleware struct{}
|
|
|
|
|
|
|
|
func (erroringMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
2016-03-21 11:56:13 +08:00
|
|
|
if rr, ok := w.(*middleware.ResponseRecorder); ok {
|
|
|
|
rr.Replacer.Set("testval", "foobar")
|
|
|
|
}
|
2015-06-13 00:21:19 +08:00
|
|
|
return http.StatusNotFound, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestLoggedStatus(t *testing.T) {
|
|
|
|
var f bytes.Buffer
|
|
|
|
var next erroringMiddleware
|
|
|
|
rule := Rule{
|
|
|
|
PathScope: "/",
|
2016-03-21 11:56:13 +08:00
|
|
|
Format: DefaultLogFormat + " {testval}",
|
2015-06-13 00:21:19 +08:00
|
|
|
Log: log.New(&f, "", 0),
|
|
|
|
}
|
|
|
|
|
|
|
|
logger := Logger{
|
|
|
|
Rules: []Rule{rule},
|
|
|
|
Next: next,
|
|
|
|
}
|
|
|
|
|
|
|
|
r, err := http.NewRequest("GET", "/", nil)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
|
|
|
|
status, err := logger.ServeHTTP(rec, r)
|
|
|
|
if status != 0 {
|
2016-03-21 11:56:13 +08:00
|
|
|
t.Errorf("Expected status to be 0, but was %d", status)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("Expected error to be nil, instead got: %v", err)
|
2015-06-13 00:21:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
logged := f.String()
|
|
|
|
if !strings.Contains(logged, "404 13") {
|
2016-03-21 11:56:13 +08:00
|
|
|
t.Errorf("Expected log entry to contain '404 13', but it didn't: %s", logged)
|
|
|
|
}
|
|
|
|
|
|
|
|
// check custom placeholder
|
|
|
|
if !strings.Contains(logged, "foobar") {
|
|
|
|
t.Errorf("Expected the log entry to contain 'foobar' (custom placeholder), but it didn't: %s", logged)
|
2015-06-13 00:21:19 +08:00
|
|
|
}
|
|
|
|
}
|