定义静音日志对象

This commit is contained in:
2025-09-14 16:08:39 +08:00
parent 55d32dad5f
commit 389c2f9846
3 changed files with 20 additions and 34 deletions

View File

@@ -17,8 +17,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gorm.io/datatypes"
"gorm.io/gorm"
)
@@ -82,17 +80,6 @@ func (m *MockDeviceRepository) Delete(id uint) error {
return args.Error(0)
}
// getSilentLogger 创建一个不输出日志的 logs.Logger 实例,用于测试
func getSilentLogger() *logs.Logger {
discardSyncer := zapcore.AddSync(io.Discard)
encoderConfig := zap.NewProductionEncoderConfig()
encoder := zapcore.NewConsoleEncoder(encoderConfig)
core := zapcore.NewCore(encoder, discardSyncer, zap.DebugLevel)
zapLogger := zap.New(core)
sugaredLogger := zapLogger.Sugar()
return &logs.Logger{SugaredLogger: sugaredLogger}
}
// testCase 结构体定义了所有测试用例的通用参数
type testCase struct {
name string
@@ -309,7 +296,7 @@ func TestCreateDevice(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
runTest(t, tc, func(ctx *gin.Context, repo *MockDeviceRepository) {
device.NewController(repo, getSilentLogger()).CreateDevice(ctx)
device.NewController(repo, logs.NewSilentLogger()).CreateDevice(ctx)
})
})
}
@@ -394,7 +381,7 @@ func TestGetDevice(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
runTest(t, tc, func(ctx *gin.Context, repo *MockDeviceRepository) {
device.NewController(repo, getSilentLogger()).GetDevice(ctx)
device.NewController(repo, logs.NewSilentLogger()).GetDevice(ctx)
})
})
}
@@ -492,7 +479,7 @@ func TestListDevices(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
runTest(t, tc, func(ctx *gin.Context, repo *MockDeviceRepository) {
device.NewController(repo, getSilentLogger()).ListDevices(ctx)
device.NewController(repo, logs.NewSilentLogger()).ListDevices(ctx)
})
})
}
@@ -681,7 +668,7 @@ func TestUpdateDevice(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
runTest(t, tc, func(ctx *gin.Context, repo *MockDeviceRepository) {
device.NewController(repo, getSilentLogger()).UpdateDevice(ctx)
device.NewController(repo, logs.NewSilentLogger()).UpdateDevice(ctx)
})
})
}
@@ -747,7 +734,7 @@ func TestDeleteDevice(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
runTest(t, tc, func(ctx *gin.Context, repo *MockDeviceRepository) {
device.NewController(repo, getSilentLogger()).DeleteDevice(ctx)
device.NewController(repo, logs.NewSilentLogger()).DeleteDevice(ctx)
})
})
}