// redis_options_test.go — FCB_REDIS_DB / URL 库号解析单测。 package cache import "testing" func TestBuildRedisOptionsPlainAddr(t *testing.T) { opts, err := buildRedisOptions("127.0.0.1:6379", 0) if err != nil { t.Fatalf("plain addr: %v", err) } if opts.DB != 0 { t.Fatalf("默认库号应为 0, got %d", opts.DB) } opts, err = buildRedisOptions("127.0.0.1:6379", 5) if err != nil { t.Fatalf("plain addr db=5: %v", err) } if opts.Addr != "127.0.0.1:6379" || opts.DB != 5 { t.Fatalf("host:port + db: got addr=%s db=%d", opts.Addr, opts.DB) } } func TestBuildRedisOptionsURL(t *testing.T) { cases := []struct { name string url string dbParam int wantDB int wantPw string }{ {"URL 无库号用参数", "redis://127.0.0.1:6379", 3, 3, ""}, {"URL 显式库号优先", "redis://127.0.0.1:6379/7", 3, 7, ""}, {"URL 带密码", "redis://:secretpw@127.0.0.1:6379/2", 0, 2, "secretpw"}, {"rediss 无库号用参数", "rediss://127.0.0.1:6379", 9, 9, ""}, {"URL 根路径视为无库号", "redis://127.0.0.1:6379/", 4, 4, ""}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { opts, err := buildRedisOptions(tc.url, tc.dbParam) if err != nil { t.Fatalf("buildRedisOptions(%q): %v", tc.url, err) } if opts.DB != tc.wantDB { t.Fatalf("db = %d, want %d", opts.DB, tc.wantDB) } if opts.Password != tc.wantPw { t.Fatalf("password = %q, want %q", opts.Password, tc.wantPw) } if opts.Addr != "127.0.0.1:6379" { t.Fatalf("addr = %q", opts.Addr) } }) } } func TestBuildRedisOptionsInvalidURL(t *testing.T) { if _, err := buildRedisOptions("redis://[bad", 0); err == nil { t.Fatal("非法 URL 应报错") } } func TestURLHasDBPath(t *testing.T) { if urlHasDBPath("redis://h:6379") || urlHasDBPath("redis://h:6379/") { t.Fatal("无路径或根路径应视为 false") } if !urlHasDBPath("redis://h:6379/5") { t.Fatal("/5 应视为 true") } }