middleware/logger/body_util_test.go

55 lines
1012 B
Go
Raw Permalink Normal View History

2020-11-07 11:59:33 +00:00
package logger
import (
"errors"
2023-12-25 00:47:12 +00:00
"io"
2020-11-07 11:59:33 +00:00
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
type errReader struct{}
func (errReader) Read(_ []byte) (n int, err error) {
return 0, errors.New("test error")
}
func TestLoggerPeek(t *testing.T) {
cases := []struct {
body string
n int64
excerpt string
hasMore bool
}{
{"", -1, "", false},
{"", 0, "", false},
{"", 1024, "", false},
{"123456", -1, "", true},
{"123456", 0, "", true},
{"123456", 4, "1234", true},
{"123456", 5, "12345", true},
{"123456", 6, "123456", false},
{"123456", 7, "123456", false},
}
for _, c := range cases {
r, excerpt, hasMore, err := peek(strings.NewReader(c.body), c.n)
if !assert.NoError(t, err) {
continue
}
2023-12-25 00:47:12 +00:00
body, err := io.ReadAll(r)
2020-11-07 11:59:33 +00:00
if !assert.NoError(t, err) {
continue
}
assert.Equal(t, c.body, string(body))
assert.Equal(t, c.excerpt, excerpt)
assert.Equal(t, c.hasMore, hasMore)
}
_, _, _, err := peek(errReader{}, 1024)
assert.Error(t, err)
}