Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve middleware code coverage #558

Merged
merged 15 commits into from
Jul 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 77 additions & 11 deletions middleware/compress_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package middleware

import (
"fmt"
"net/http/httptest"
"os"
"strconv"
"testing"

"github.com/gofiber/fiber"
Expand All @@ -17,18 +19,18 @@ func Test_Middleware_Compress(t *testing.T) {
app.Use(Compress())

app.Get("/", func(c *fiber.Ctx) {
c.SendFile("../ctx.go", true)
c.SendFile(compressFilePath(CompressLevelDefault), true)
})

req := httptest.NewRequest("GET", "/", nil)
req.Header.Set(fiber.HeaderAcceptEncoding, "gzip")

resp, err := app.Test(req)
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")
utils.AssertEqual(t, "gzip", resp.Header.Get(fiber.HeaderContentEncoding))
utils.AssertEqual(t, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get(fiber.HeaderContentType))
os.Remove("../ctx.go.fiber.gz")
os.Remove(compressFilePath(CompressLevelDefault, true))
}

// go test -run Test_Middleware_Compress_Config
Expand All @@ -40,7 +42,7 @@ func Test_Middleware_Compress_Config(t *testing.T) {
}))

app.Get("/", func(c *fiber.Ctx) {
c.SendFile("../ctx.go", true)
c.SendFile(compressFilePath(CompressLevelDefault), true)
})

req := httptest.NewRequest("GET", "/", nil)
Expand All @@ -51,36 +53,92 @@ func Test_Middleware_Compress_Config(t *testing.T) {
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
utils.AssertEqual(t, "gzip", resp.Header.Get(fiber.HeaderContentEncoding))
utils.AssertEqual(t, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get(fiber.HeaderContentType))
os.Remove("../ctx.go.fiber.gz")
os.Remove(compressFilePath(CompressLevelDefault, true))
}

// go test -run Test_Middleware_Compress_With_Config
func Test_Middleware_Compress_With_Config(t *testing.T) {
app := fiber.New()

app.Use(CompressWithConfig(CompressConfig{}))

app.Get("/", func(c *fiber.Ctx) {
c.SendFile(compressFilePath(CompressLevelDefault), true)
})

req := httptest.NewRequest("GET", "/", nil)
req.Header.Set(fiber.HeaderAcceptEncoding, "gzip")

resp, err := app.Test(req)
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")
utils.AssertEqual(t, "gzip", resp.Header.Get(fiber.HeaderContentEncoding))
utils.AssertEqual(t, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get(fiber.HeaderContentType))
os.Remove(compressFilePath(CompressLevelDefault, true))
}

// go test -run Test_Middleware_Compress_Level
func Test_Middleware_Compress_Level(t *testing.T) {
t.Parallel()

levels := []int{
CompressLevelDisabled,
CompressLevelDefault,
CompressLevelBestSpeed,
CompressLevelBestCompression,
}

app := fiber.New()
for _, level := range levels {
app.Get("/:level", Compress(level), func(c *fiber.Ctx) {
c.SendFile(compressFilePath(c.Params("level")), true)
})
}

for _, level := range levels {
name := strconv.FormatInt(int64(level), 10)
t.Run(name, func(t *testing.T) {
target := fmt.Sprintf("/%d", level)
req := httptest.NewRequest("GET", target, nil)
req.Header.Set(fiber.HeaderAcceptEncoding, "br")

resp, err := app.Test(req, 3000)
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")
utils.AssertEqual(t, "br", resp.Header.Get(fiber.HeaderContentEncoding))
utils.AssertEqual(t, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get(fiber.HeaderContentType))

os.Remove(compressFilePath(level, true))
})
}
}

// go test -run Test_Middleware_Compress_Skip
func Test_Middleware_Compress_Skip(t *testing.T) {
app := fiber.New()

app.Use(Compress(2))
app.Use(Compress(func(c *fiber.Ctx) bool { return true }))

app.Get("/", func(c *fiber.Ctx) {
c.SendFile("../ctx.go", true)
c.SendFile(compressFilePath(CompressLevelDefault), true)
})

req := httptest.NewRequest("GET", "/", nil)
req.Header.Set(fiber.HeaderAcceptEncoding, "br")

resp, err := app.Test(req, 3000)
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
utils.AssertEqual(t, "br", resp.Header.Get(fiber.HeaderContentEncoding))
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")
utils.AssertEqual(t, "", resp.Header.Get(fiber.HeaderContentEncoding))
utils.AssertEqual(t, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get(fiber.HeaderContentType))
os.Remove("../ctx.go.fiber.gz")
}

// go test -v -run=^$ -bench=Benchmark_Middleware_Compress -benchmem -count=4
func Benchmark_Middleware_Compress(b *testing.B) {
app := fiber.New()
app.Use(Compress())
app.Get("/", func(c *fiber.Ctx) {
c.SendFile("../ctx.go", true)
c.SendFile(compressFilePath(CompressLevelDefault), true)
})
handler := app.Handler()

Expand All @@ -93,3 +151,11 @@ func Benchmark_Middleware_Compress(b *testing.B) {
handler(c)
}
}

func compressFilePath(level interface{}, gz ...bool) string {
filePath := fmt.Sprintf("./testdata/compress_level_%v.txt", level)
if len(gz) > 0 && gz[0] {
filePath += ".fiber.gz"
}
return filePath
}
39 changes: 35 additions & 4 deletions middleware/favicon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,51 @@ func Test_Middleware_Favicon(t *testing.T) {

app.Get("/", func(c *fiber.Ctx) {})

resp, err := app.Test(httptest.NewRequest("GET", "/favicon.ico", nil))
// Skip Favicon middleware
resp, err := app.Test(httptest.NewRequest("GET", "/", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")

resp, err = app.Test(httptest.NewRequest("GET", "/favicon.ico", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 204, resp.StatusCode, "Status code")
utils.AssertEqual(t, fiber.StatusNoContent, resp.StatusCode, "Status code")

resp, err = app.Test(httptest.NewRequest("OPTIONS", "/favicon.ico", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")

resp, err = app.Test(httptest.NewRequest("PUT", "/favicon.ico", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 405, resp.StatusCode, "Status code")
utils.AssertEqual(t, fiber.StatusMethodNotAllowed, resp.StatusCode, "Status code")
utils.AssertEqual(t, "GET, HEAD, OPTIONS", resp.Header.Get(fiber.HeaderAllow))
}

// go test -run Test_Middleware_Favicon_Not_Found
func Test_Middleware_Favicon_Not_Found(t *testing.T) {
defer func() {
if err := recover(); err == nil {
t.Fatal("should cache panic")
}
}()

fiber.New().Use(Favicon("non-exist.ico"))
}

// go test -run Test_Middleware_Favicon_Found
func Test_Middleware_Favicon_Found(t *testing.T) {
app := fiber.New()

app.Use(Favicon("./testdata/favicon.ico"))

app.Get("/", func(c *fiber.Ctx) {})

resp, err := app.Test(httptest.NewRequest("GET", "/favicon.ico", nil))

utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")
utils.AssertEqual(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType))
}

// go test -v -run=^$ -bench=Benchmark_Middleware_Favicon -benchmem -count=4
func Benchmark_Middleware_Favicon(b *testing.B) {
app := fiber.New()
Expand Down
2 changes: 1 addition & 1 deletion middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ Logger allows the following config arguments in any order:
- Logger(next func(*fiber.Ctx) bool)
- Logger(output io.Writer)
- Logger(format string)
- Logger(timeformat string)
- Logger(timeFormat string)
- Logger(config LoggerConfig)
*/
func Logger(options ...interface{}) fiber.Handler {
Expand Down
80 changes: 73 additions & 7 deletions middleware/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"

"github.com/gofiber/fiber"
Expand All @@ -16,8 +17,8 @@ import (

// go test -run Test_Middleware_Logger
func Test_Middleware_Logger(t *testing.T) {
format := "${ip}-${ips}-${url}-${host}-${method}-${path}-${protocol}-${route}-${referer}-${ua}-${status}-${body}-${error}-${bytesSent}-${bytesReceived}-${header:header}-${query:query}-${cookie:cookie}"
expect := "0.0.0.0--/test?query=query-example.com-GET-/test-http-/test-ref-ua-500--error-5-0-header-query-cookie"
format := "${ip}-${ips}-${url}-${host}-${method}-${path}-${protocol}-${route}-${referer}-${ua}-${status}-${body}-${error}-${bytesSent}-${bytesReceived}-${header:header}-${query:query}-${form:form}-${cookie:cookie}"
expect := "0.0.0.0--/test?query=query-example.com-POST-/test-http-/test-ref-ua-500-form=form-error-5-9-header-query-form-cookie"

buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)
Expand All @@ -29,19 +30,20 @@ func Test_Middleware_Logger(t *testing.T) {
Output: buf,
}))

app.Get("/test", func(ctx *fiber.Ctx) {
app.Post("/test", func(ctx *fiber.Ctx) {
ctx.Next(errors.New("error"))
})

req := httptest.NewRequest("GET", "/test?query=query", nil)
req := httptest.NewRequest("POST", "/test?query=query", strings.NewReader("form=form"))
req.Header.Set("header", "header")
req.Header.Set("Cookie", "cookie=cookie")
req.Header.Set("User-Agent", "ua")
req.Header.Set("Referer", "ref")
req.Header.Set("Content-type", "application/x-www-form-urlencoded")

resp, err := app.Test(req)
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 500, resp.StatusCode, "Status code")
utils.AssertEqual(t, fiber.StatusInternalServerError, resp.StatusCode, "Status code")
utils.AssertEqual(t, expect, buf.String())

}
Expand All @@ -53,13 +55,15 @@ $`)
buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)

LoggerConfigDefault.Output = buf
config := LoggerConfigDefault
config.Output = buf
config.Output = nil

app := fiber.New(&fiber.Settings{DisableStartupMessage: true})
app.Use(Logger(config))

app.Get("/", func(ctx *fiber.Ctx) {
ctx.SendStatus(200)
ctx.SendStatus(fiber.StatusOK)
})

_, err := app.Test(httptest.NewRequest(http.MethodGet, "/", nil))
Expand All @@ -72,6 +76,68 @@ $`)
)
}

// go test -run Test_Middleware_Logger_Skip
func Test_Middleware_Logger_Skip(t *testing.T) {
buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)

LoggerConfigDefault.Output = buf

app := fiber.New()

app.Use(Logger(func(_ *fiber.Ctx) bool {
return true
}))

app.Get("/", func(_ *fiber.Ctx) {})

resp, err := app.Test(httptest.NewRequest(http.MethodGet, "/", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")
utils.AssertEqual(t, 0, buf.Len(), "buf.Len()")
}

// go test -run Test_Middleware_Logger_Options_And_WithConfig
func Test_Middleware_Logger_Options_And_WithConfig(t *testing.T) {
t.Parallel()

expectedOutputPattern := regexp.MustCompile(`^\d{2}:\d{2}:\d{2} GET / - 0\.0\.0\.0 - 200 - \d+(\.\d+)?.{1,3}
$`)

buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)

LoggerConfigDefault.Output = buf

loggers := []fiber.Handler{
Logger(buf),
Logger("15:04:05"),
Logger("${time} ${method} ${path} - ${ip} - ${status} - ${latency}\n"),
Logger(LoggerConfig{Output: buf}),
LoggerWithConfig(LoggerConfig{Output: buf}),
}

for _, logger := range loggers {
buf.Reset()

app := fiber.New()

app.Use(logger)

app.Get("/", func(_ *fiber.Ctx) {})

resp, err := app.Test(httptest.NewRequest(http.MethodGet, "/", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")
utils.AssertEqual(
t,
true,
expectedOutputPattern.MatchString(buf.String()),
fmt.Sprintf("Has: %s, expected pattern: %s", buf.String(), expectedOutputPattern.String()),
)
}
}

// go test -v -run=^$ -bench=Benchmark_Middleware_Logger -benchmem -count=4
func Benchmark_Middleware_Logger(b *testing.B) {

Expand Down
Loading