chore: improve codecov (#1878)

This commit is contained in:
Kevin Wan
2022-05-08 13:17:48 +08:00
committed by GitHub
parent 5451d96a81
commit 6d2b9fd904
3 changed files with 66 additions and 5 deletions

View File

@@ -1,6 +1,8 @@
package handler
import (
"bytes"
"io"
"io/ioutil"
"log"
"net/http"
@@ -44,6 +46,33 @@ func TestLogHandler(t *testing.T) {
}
}
func TestLogHandlerVeryLong(t *testing.T) {
var buf bytes.Buffer
for i := 0; i < limitBodyBytes<<1; i++ {
buf.WriteByte('a')
}
req := httptest.NewRequest(http.MethodPost, "http://localhost", &buf)
handler := LogHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Context().Value(internal.LogContext).(*internal.LogCollector).Append("anything")
io.Copy(ioutil.Discard, r.Body)
w.Header().Set("X-Test", "test")
w.WriteHeader(http.StatusServiceUnavailable)
_, err := w.Write([]byte("content"))
assert.Nil(t, err)
flusher, ok := w.(http.Flusher)
assert.True(t, ok)
flusher.Flush()
}))
resp := httptest.NewRecorder()
handler.ServeHTTP(resp, req)
assert.Equal(t, http.StatusServiceUnavailable, resp.Code)
assert.Equal(t, "test", resp.Header().Get("X-Test"))
assert.Equal(t, "content", resp.Body.String())
}
func TestLogHandlerSlow(t *testing.T) {
handlers := []func(handler http.Handler) http.Handler{
LogHandler,
@@ -106,6 +135,28 @@ func TestSetSlowThreshold(t *testing.T) {
assert.Equal(t, time.Second, slowThreshold.Load())
}
func TestWrapMethodWithColor(t *testing.T) {
// no tty
assert.Equal(t, http.MethodGet, wrapMethod(http.MethodGet))
assert.Equal(t, http.MethodPost, wrapMethod(http.MethodPost))
assert.Equal(t, http.MethodPut, wrapMethod(http.MethodPut))
assert.Equal(t, http.MethodDelete, wrapMethod(http.MethodDelete))
assert.Equal(t, http.MethodPatch, wrapMethod(http.MethodPatch))
assert.Equal(t, http.MethodHead, wrapMethod(http.MethodHead))
assert.Equal(t, http.MethodOptions, wrapMethod(http.MethodOptions))
assert.Equal(t, http.MethodConnect, wrapMethod(http.MethodConnect))
assert.Equal(t, http.MethodTrace, wrapMethod(http.MethodTrace))
}
func TestWrapStatusCodeWithColor(t *testing.T) {
// no tty
assert.Equal(t, "200", wrapStatusCode(http.StatusOK))
assert.Equal(t, "302", wrapStatusCode(http.StatusFound))
assert.Equal(t, "404", wrapStatusCode(http.StatusNotFound))
assert.Equal(t, "500", wrapStatusCode(http.StatusInternalServerError))
assert.Equal(t, "503", wrapStatusCode(http.StatusServiceUnavailable))
}
func BenchmarkLogHandler(b *testing.B) {
b.ReportAllocs()