* Copyright (c) 2024 Huawei Technologies Co., Ltd.
* openFuyao is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package tools
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCreateLumberjackLogger(t *testing.T) {
conf := LogConfig{
Path: "logs",
FileName: "test.log",
MaxSize: 10,
MaxBackups: 5,
MaxAge: 30,
LocalTime: true,
Compress: true,
}
logger := createLumberjackLogger(&conf)
expectedFilename := filepath.Join("logs", "test.log")
if logger.Filename != expectedFilename {
t.Errorf("Expected filename %s, got %s", expectedFilename, logger.Filename)
}
if logger.MaxSize != 10 {
t.Errorf("Expected MaxSize 10, got %d", logger.MaxSize)
}
if logger.MaxBackups != 5 {
t.Errorf("Expected MaxBackups 5, got %d", logger.MaxBackups)
}
if logger.MaxAge != 30 {
t.Errorf("Expected MaxAge 30, got %d", logger.MaxAge)
}
if logger.LocalTime != true {
t.Errorf("Expected LocalTime true, got %v", logger.LocalTime)
}
if logger.Compress != true {
t.Errorf("Expected Compress true, got %v", logger.Compress)
}
}
func TestHandleError(t *testing.T) {
recorder := httptest.NewRecorder()
testError := fmt.Errorf("test error")
HandleError(recorder, http.StatusInternalServerError, testError)
if status := recorder.Code; status != http.StatusInternalServerError {
t.Errorf("Expected status code %d, got %d", http.StatusInternalServerError, status)
}
expectedMessage := "Error occurred: test error"
responseBody := recorder.Body.String()
if !bytes.Contains([]byte(responseBody), []byte(expectedMessage)) {
t.Errorf("Expected response body to contain '%s', got '%s'", expectedMessage, responseBody)
}
}
func TestAddContext(t *testing.T) {
newLogger := AddContext("module", "test", "id", 1)
newLogger.Info("This is a test message")
LogInfo("This is a test message")
LogDebug("This is a test message")
}
func TestGetLogWriter(t *testing.T) {
tests := []struct {
name string
outMod string
}{
{"console mode", "console"},
{"file mode", "file"},
{"both mode", "both"},
{"default mode", "invalid"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config := &LogConfig{OutMod: tt.outMod}
writer := getLogWriter(config)
assert.NotNil(t, writer)
})
}
}