Skip to content

Commit

Permalink
test: add Test_Logger_WithLatency_DefaultFormat
Browse files Browse the repository at this point in the history
  • Loading branch information
sixcolors committed Aug 16, 2023
1 parent f97d278 commit 6a70630
Showing 1 changed file with 53 additions and 1 deletion.
54 changes: 53 additions & 1 deletion middleware/logger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,59 @@ func Test_Logger_WithLatency(t *testing.T) {
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode)

// Assert that the log output contains the expected latency value in the current time unit
utils.AssertEqual(t, bytes.HasSuffix(buff.Bytes(), []byte(tu.unit)), true, "Expected latency to be in %s, got %s", tu.unit, buff.String())
utils.AssertEqual(t, bytes.HasSuffix(buff.Bytes(), []byte(tu.unit)), true, fmt.Sprintf("Expected latency to be in %s, got %s", tu.unit, buff.String()))

// Reset the buffer
buff.Reset()
}
}

// go test -run Test_Logger_WithLatency_DefaultFormat
func Test_Logger_WithLatency_DefaultFormat(t *testing.T) {
t.Parallel()
buff := bytebufferpool.Get()
defer bytebufferpool.Put(buff)
app := fiber.New()
logger := New(Config{
Output: buff,
})
app.Use(logger)

// Define a list of time units to test
timeUnits := []struct {
unit string
div time.Duration
}{
// {"ns", time.Nanosecond}, // TODO: Nano seconds are too fast to test
{"µs", time.Microsecond},
{"ms", time.Millisecond},
{"s", time.Second},
}

// Initialize a new time unit
sleepDuration := 1 * time.Nanosecond

// Define a test route that sleeps
app.Get("/test", func(c *fiber.Ctx) error {
time.Sleep(sleepDuration)
return c.SendStatus(fiber.StatusOK)
})

// Loop through each time unit and assert that the log output contains the expected latency value
for _, tu := range timeUnits {
// Update the sleep duration for the next iteration
sleepDuration = 1 * tu.div

// Create a new HTTP request to the test route
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int(2*time.Second))
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode)

// Assert that the log output contains the expected latency value in the current time unit
// parse out the latency value from the log output
latency := bytes.Split(buff.Bytes(), []byte(" | "))[2]
// Assert that the latency value is in the current time unit
utils.AssertEqual(t, bytes.HasSuffix(latency, []byte(tu.unit)), true, fmt.Sprintf("Expected latency to be in %s, got %s", tu.unit, latency))

// Reset the buffer
buff.Reset()
Expand Down

0 comments on commit 6a70630

Please sign in to comment.