9e11f8f007
按"同一能力只保留一个主入口、框架不替上层吞错、安全路径默认 fail-closed"原则, 收敛历史双轨 API。自定义 CacheService/Storage 实现需同步更新签名(编译失败即迁移信号)。 cache: - CacheService.Get/Exists 改为 (bool, error):命中 (true,nil)、未命中 (false,nil)、 Redis 未就绪/命令错误/反序列化失败返回 (false,err) - 删除 cache.GetE/cache.ExistsE/CacheGetter/CacheExistChecker/redisCache.GetE/redisCache.ExistsE (不保留 deprecated wrapper) - 新增包级 cache.Get/cache.Exists(带 error);GetWithPrefix 改为 (bool,error) jwt: - TokenBlacklist.IsBlacklisted 改为 (bool, error),删除 IsBlacklistedE - IsTokenRevoked 改为 (bool, error) - ParseToken 默认从 fail-open 改为 fail-closed:黑名单后端不可检查时返回 ErrBlacklistUnavailable 拒绝该 Token(无 Redis 部署不再支持可靠撤销) - 删除 ParseTokenFailClosed(主 API 已 fail-closed) - 保留 ParseTokenWithBlacklistPolicy + BlacklistPolicy/BlacklistFailOpen/BlacklistFailClosed 供显式 fail-open(仅无 Redis 或低安全场景) storage: - Storage.Exists 改为 (bool, error):存在 (true,nil)、不存在 (false,nil)、 未初始化/路径非法/穿越/后端错误返回 (false,err) - LocalStorage.Exists 区分 os.IsNotExist 与其他 Stat 错误 - OSSStorage.Exists 区分 OSS 404/NoSuchKey 与鉴权/网络错误 - 包级 storage.Exists 同步签名,未初始化返回 ErrStorageNotInitialized - 新增 ErrReadTooLarge:Local/OSSStorage.Get 读取超 maxReadBytes 上限原误用 ErrInvalidPath(语义不贴切),改为 ErrReadTooLarge ratelimit: - NewRedisRateLimiter 加 opts ...RedisRateLimiterOption,新增 WithFailClosed(bool) 替代原 NewRedisRateLimiterFailClosed - RedisRateLimit/CustomRedisRateLimit/RedisRateLimitWithIdentifier 同步加 opts 参数 - 删除 NewRedisRateLimiterFailClosed/RedisRateLimitFailClosed/CustomRedisRateLimitFailClosed - UploadRedisRateLimit 由 fail-open 改为 fail-closed(资源敏感操作,Redis 故障时拒绝) 测试与文档: - cache_m10_internal_test.go 重写 4 个 M10 测试为 Get/Exists 契约测试,新增 mock 编译覆盖 - jwt_test.go 改 4 处;jwt_c9c_internal_test.go 改 IsTokenRevoked 2-value - examples/full/main_test.go 加 miniredis 注入(ParseToken fail-closed 后认证需 Redis) - middleware_test.go 改 5 处 FailClosed 调用为 WithFailClosed(true);auth_test.go 加 Redis - storage 测试改 6 处 Exists/Get 断言为新签名/错误类型 - README/GUIDE 同步示例为新签名;CHANGELOG 新增 Breaking 升级说明与迁移示例 验证:go build / go vet / go test -race -count=1 ./... 全绿。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
172 lines
4.3 KiB
Go
172 lines
4.3 KiB
Go
package storage_test
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/EthanCodeCraft/xlgo-core/config"
|
|
"github.com/EthanCodeCraft/xlgo-core/logger"
|
|
"github.com/EthanCodeCraft/xlgo-core/storage"
|
|
)
|
|
|
|
func init() {
|
|
// 初始化日志(测试需要)
|
|
cfg := &config.Config{
|
|
Log: config.LogConfig{
|
|
Dir: os.TempDir(),
|
|
MaxSize: 10,
|
|
MaxBackups: 1,
|
|
MaxAge: 1,
|
|
Compress: false,
|
|
},
|
|
}
|
|
logger.Init(cfg)
|
|
}
|
|
|
|
func TestStorageNotInitialized(t *testing.T) {
|
|
storage.SetStorage(nil)
|
|
|
|
if _, err := storage.UploadFromBytes([]byte("test"), "test.txt", "docs"); !errors.Is(err, storage.ErrStorageNotInitialized) {
|
|
t.Fatalf("expected ErrStorageNotInitialized, got %v", err)
|
|
}
|
|
if err := storage.Delete("missing"); !errors.Is(err, storage.ErrStorageNotInitialized) {
|
|
t.Fatalf("expected ErrStorageNotInitialized, got %v", err)
|
|
}
|
|
if _, err := storage.Get("missing"); !errors.Is(err, storage.ErrStorageNotInitialized) {
|
|
t.Fatalf("expected ErrStorageNotInitialized, got %v", err)
|
|
}
|
|
if url := storage.GetURL("missing"); url != "" {
|
|
t.Fatalf("expected empty URL, got %q", url)
|
|
}
|
|
if ok, err := storage.Exists("missing"); ok || !errors.Is(err, storage.ErrStorageNotInitialized) {
|
|
t.Fatalf("expected (false, ErrStorageNotInitialized) without storage, got (%v, %v)", ok, err)
|
|
}
|
|
}
|
|
|
|
func TestLocalStorage(t *testing.T) {
|
|
cfg := &config.LocalStorageConfig{
|
|
Path: "/tmp/uploads",
|
|
BaseURL: "http://localhost/uploads",
|
|
}
|
|
|
|
local := storage.NewLocalStorage(cfg)
|
|
if local == nil {
|
|
t.Error("NewLocalStorage should not return nil")
|
|
}
|
|
}
|
|
|
|
func TestStorageInterface(t *testing.T) {
|
|
cfg := &config.LocalStorageConfig{
|
|
Path: "/tmp/uploads",
|
|
BaseURL: "http://localhost/uploads",
|
|
}
|
|
|
|
var s storage.Storage = storage.NewLocalStorage(cfg)
|
|
if s == nil {
|
|
t.Error("LocalStorage should implement Storage interface")
|
|
}
|
|
}
|
|
|
|
func TestLocalStorageGetURL(t *testing.T) {
|
|
cfg := &config.LocalStorageConfig{
|
|
Path: "/uploads",
|
|
BaseURL: "http://example.com",
|
|
}
|
|
|
|
local := storage.NewLocalStorage(cfg)
|
|
url := local.GetURL("images/test.jpg")
|
|
|
|
expected := "http://example.com/images/test.jpg"
|
|
if url != expected {
|
|
t.Errorf("GetURL = %s, want %s", url, expected)
|
|
}
|
|
}
|
|
|
|
func TestLocalStorageDeleteGetExists(t *testing.T) {
|
|
// 创建临时目录
|
|
tmpDir := filepath.Join(os.TempDir(), "xlgo_storage_test")
|
|
if err := os.MkdirAll(tmpDir, 0755); err != nil {
|
|
t.Fatalf("Failed to create temp dir: %v", err)
|
|
}
|
|
defer os.RemoveAll(tmpDir)
|
|
|
|
cfg := &config.LocalStorageConfig{
|
|
Path: tmpDir,
|
|
BaseURL: "http://localhost/uploads",
|
|
}
|
|
|
|
local := storage.NewLocalStorage(cfg)
|
|
|
|
// 创建测试文件
|
|
testFile := filepath.Join(tmpDir, "test.txt")
|
|
testData := []byte("hello world")
|
|
if err := os.WriteFile(testFile, testData, 0644); err != nil {
|
|
t.Fatalf("Failed to write test file: %v", err)
|
|
}
|
|
|
|
// 测试 Exists
|
|
ok, err := local.Exists("test.txt")
|
|
if err != nil || !ok {
|
|
t.Errorf("Exists should return (true, nil) for existing file, got (%v, %v)", ok, err)
|
|
}
|
|
|
|
// 测试 Get
|
|
data, err := local.Get("test.txt")
|
|
if err != nil {
|
|
t.Errorf("Get failed: %v", err)
|
|
}
|
|
if string(data) != "hello world" {
|
|
t.Errorf("Get data = %s, want 'hello world'", string(data))
|
|
}
|
|
|
|
// 测试 Delete
|
|
err = local.Delete("test.txt")
|
|
if err != nil {
|
|
t.Errorf("Delete failed: %v", err)
|
|
}
|
|
|
|
// 验证删除后不存在
|
|
ok, err = local.Exists("test.txt")
|
|
if err != nil || ok {
|
|
t.Errorf("Exists should return (false, nil) after delete, got (%v, %v)", ok, err)
|
|
}
|
|
|
|
// 删除不存在的文件应该失败
|
|
err = local.Delete("nonexistent.txt")
|
|
if err == nil {
|
|
t.Error("Delete should fail for nonexistent file")
|
|
}
|
|
|
|
// Get 不存在的文件应该失败
|
|
_, err = local.Get("nonexistent.txt")
|
|
if err == nil {
|
|
t.Error("Get should fail for nonexistent file")
|
|
}
|
|
}
|
|
|
|
func TestStorageInitInvalidDriver(t *testing.T) {
|
|
cfg := &config.StorageConfig{
|
|
Driver: "invalid",
|
|
}
|
|
|
|
err := storage.Init(cfg)
|
|
if err == nil {
|
|
t.Error("Init should fail with invalid driver")
|
|
}
|
|
}
|
|
|
|
func TestOSSStorageConfig(t *testing.T) {
|
|
cfg := &config.OSSStorageConfig{
|
|
Endpoint: "oss-cn-hangzhou.aliyuncs.com",
|
|
Bucket: "test-bucket",
|
|
AccessKeyID: "test-id",
|
|
AccessKeySecret: "test-secret",
|
|
BaseURL: "https://test.oss-cn-hangzhou.aliyuncs.com",
|
|
}
|
|
|
|
if cfg.Endpoint != "oss-cn-hangzhou.aliyuncs.com" {
|
|
t.Error("OSSStorageConfig Endpoint failed")
|
|
}
|
|
} |