Go + PostgreSQL + Valkey backend (cmd/internal/migrations), uni-app mobile frontend, PC web (web/), admin console (admin/), Android WebView container (android_project/). Build artifacts, node_modules, local env and debug screenshots excluded.
67 lines
2.2 KiB
Go
67 lines
2.2 KiB
Go
package cache
|
||
|
||
import (
|
||
"strconv"
|
||
"strings"
|
||
"testing"
|
||
"time"
|
||
)
|
||
|
||
// 覆盖滑动续约的纯逻辑部分:值的编码格式、续约截止时间的计算、
|
||
// 旧格式兼容与异常值兜底。Redis 交互层由 GetSession/renewSession 薄封装承担。
|
||
|
||
func TestEncodeSessionValue(t *testing.T) {
|
||
ttl := 720 * time.Hour // 30 天
|
||
renew := 168 * time.Hour // 最后 7 天窗口
|
||
before := time.Now()
|
||
|
||
c := New(nil, nil).WithSessionPolicy(ttl, renew)
|
||
v := c.encodeSessionValue("u-123", ttl)
|
||
|
||
uid, renewAfter := splitSessionValue(v)
|
||
if uid != "u-123" {
|
||
t.Fatalf("uid = %q, want u-123", uid)
|
||
}
|
||
want := before.Add(ttl - renew) // 约 23 天后续约
|
||
if renewAfter < want.Add(-time.Minute).Unix() || renewAfter > want.Add(time.Minute).Unix() {
|
||
t.Fatalf("renewAfter = %d, want ≈ %d", renewAfter, want.Unix())
|
||
}
|
||
}
|
||
|
||
func TestEncodeSessionValueDisabled(t *testing.T) {
|
||
// 未注入策略
|
||
if v := New(nil, nil).encodeSessionValue("u-1", 720*time.Hour); v != "u-1" {
|
||
t.Fatalf("policy unset: v = %q, want plain uid", v)
|
||
}
|
||
// TTL 没有超过续约窗口(配置退化),不应产生会立即续约的值
|
||
c := New(nil, nil).WithSessionPolicy(168*time.Hour, 168*time.Hour)
|
||
if v := c.encodeSessionValue("u-1", 168*time.Hour); v != "u-1" {
|
||
t.Fatalf("degenerate policy: v = %q, want plain uid", v)
|
||
}
|
||
}
|
||
|
||
func TestSplitSessionValue(t *testing.T) {
|
||
// 新格式
|
||
uid, ts := splitSessionValue("u-1|" + strconv.FormatInt(1700000000, 10))
|
||
if uid != "u-1" || ts != 1700000000 {
|
||
t.Fatalf("new format: uid=%q ts=%d", uid, ts)
|
||
}
|
||
// 旧格式(升级前的存量会话)→ 0 表示待续约
|
||
if uid, ts := splitSessionValue("u-1"); uid != "u-1" || ts != 0 {
|
||
t.Fatalf("legacy format: uid=%q ts=%d", uid, ts)
|
||
}
|
||
// 尾部非数字 → 视为待续约,uid 原样保留
|
||
if uid, ts := splitSessionValue("u-1|oops"); uid != "u-1|oops" || ts != 0 {
|
||
t.Fatalf("garbage tail: uid=%q ts=%d", uid, ts)
|
||
}
|
||
}
|
||
|
||
func TestSessionValueRoundTrip(t *testing.T) {
|
||
c := New(nil, nil).WithSessionPolicy(720*time.Hour, 168*time.Hour)
|
||
v := c.encodeSessionValue("uid-with-|", 720*time.Hour) // 极端 uid:即使含分隔符也不串位
|
||
uid, _ := splitSessionValue(v)
|
||
if !strings.HasPrefix(uid, "uid-with-|") {
|
||
t.Fatalf("uid with pipe mangled: %q", uid)
|
||
}
|
||
}
|