lolly/internal/middleware/accesslog/accesslog_test.go
xfy f2352ab9cc docs(config,stream,logging,handler,proxy,cache,server,ssl,middleware): 为核心模块添加详细 GoDoc 文档注释
- config: 为 Config 和所有子配置结构添加完整文档,包含使用示例和注意事项
- stream: 为负载均衡器和服务器添加详细的参数、返回值和功能说明
- logging: 为日志格式化和输出函数添加文档,说明支持的变量替换
- handler: 为路由器、静态文件和 sendfile 处理器添加文档
- proxy: 为健康检查器和代理功能添加完整文档
- cache/server/ssl/middleware: 补充相关模块的文档注释
- config.example.yaml: 添加可信代理配置、加密套件示例,更新压缩级别说明

Co-Authored-By: Claude <noreply@anthropic.com>
2026-04-07 15:36:09 +08:00

89 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package accesslog 提供访问日志功能的测试。
//
// 该文件测试访问日志模块的各项功能,包括:
// - 访问日志中间件创建
// - 请求处理和响应记录
// - 请求持续时间记录
// - 日志格式化
//
// 作者xfy
package accesslog
import (
"bytes"
"testing"
"time"
"github.com/valyala/fasthttp"
"rua.plus/lolly/internal/config"
)
func TestAccessLog_Name(t *testing.T) {
al := New(&config.LoggingConfig{})
if al.Name() != "accesslog" {
t.Errorf("expected name 'accesslog', got '%s'", al.Name())
}
}
func TestAccessLog_Process(t *testing.T) {
al := New(&config.LoggingConfig{
Access: config.AccessLogConfig{Format: "json"},
})
// 创建一个简单的 handler
handler := func(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(200)
ctx.SetBodyString("hello")
}
// 包装 handler
wrapped := al.Process(handler)
// 创建模拟请求上下文
var ctx fasthttp.RequestCtx
ctx.Init(&fasthttp.Request{}, nil, nil)
// 执行
wrapped(&ctx)
// 验证响应未被修改
if ctx.Response.StatusCode() != 200 {
t.Errorf("expected status 200, got %d", ctx.Response.StatusCode())
}
if !bytes.Equal(ctx.Response.Body(), []byte("hello")) {
t.Errorf("expected body 'hello', got '%s'", ctx.Response.Body())
}
// 清理
_ = al.Close()
}
func TestAccessLog_ProcessWithDuration(t *testing.T) {
al := New(&config.LoggingConfig{
Access: config.AccessLogConfig{Format: "json"},
})
// 创建一个有延迟的 handler
handler := func(ctx *fasthttp.RequestCtx) {
time.Sleep(10 * time.Millisecond)
ctx.SetStatusCode(201)
ctx.SetBodyString("created")
}
wrapped := al.Process(handler)
var ctx fasthttp.RequestCtx
ctx.Init(&fasthttp.Request{}, nil, nil)
start := time.Now()
wrapped(&ctx)
elapsed := time.Since(start)
// 验证延迟被记录(至少 10ms
if elapsed < 10*time.Millisecond {
t.Errorf("expected duration >= 10ms, got %v", elapsed)
}
_ = al.Close()
}