| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025 |
- package loaders
- import (
- "context"
- "database/sql"
- "encoding/json"
- "errors"
- "fmt"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
- "github.com/zeromicro/go-zero/core/stores/cache"
- "github.com/zeromicro/go-zero/core/stores/redis"
- "github.com/zeromicro/go-zero/core/stores/sqlx"
- "golang.org/x/crypto/bcrypt"
- "math"
- "math/rand"
- "perms-system-server/internal/consts"
- "perms-system-server/internal/model"
- deptModel "perms-system-server/internal/model/dept"
- permModel "perms-system-server/internal/model/perm"
- productModel "perms-system-server/internal/model/product"
- memberModel "perms-system-server/internal/model/productmember"
- roleModel "perms-system-server/internal/model/role"
- rolePermModel "perms-system-server/internal/model/roleperm"
- userModel "perms-system-server/internal/model/user"
- userPermModel "perms-system-server/internal/model/userperm"
- userRoleModel "perms-system-server/internal/model/userrole"
- "sort"
- "strings"
- "sync"
- "sync/atomic"
- "testing"
- "time"
- )
- var testCacheConf = cache.CacheConf{
- {
- RedisConf: redis.RedisConf{Host: "127.0.0.1:6379", Pass: "NsDmWyM@312", Type: "node"},
- Weight: 100,
- },
- }
- var testKeyPrefix = "test_perms"
- var testDataSource = "root:NsDmWyM@312@tcp(127.0.0.1:3306)/perms_system?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai"
- func testConn() sqlx.SqlConn { return sqlx.NewMysql(testDataSource) }
- func testRedis() *redis.Redis { return redis.MustNewRedis(testCacheConf[0].RedisConf) }
- func testModels() *model.Models {
- conn := testConn()
- return model.NewModels(conn, testCacheConf, testKeyPrefix)
- }
- func uniqueId() string {
- return fmt.Sprintf("t_%d_%d", time.Now().UnixNano(), rand.Intn(100000))
- }
- func hashPwd(p string) string {
- h, _ := bcrypt.GenerateFromPassword([]byte(p), bcrypt.MinCost)
- return string(h)
- }
- func cleanTable(ctx context.Context, conn sqlx.SqlConn, table string, ids ...int64) {
- for _, id := range ids {
- conn.ExecCtx(ctx, fmt.Sprintf("DELETE FROM %s WHERE `id` = ?", table), id)
- }
- }
- func cleanTableByField(ctx context.Context, conn sqlx.SqlConn, table, field string, value interface{}) {
- conn.ExecCtx(ctx, fmt.Sprintf("DELETE FROM %s WHERE `%s` = ?", table, field), value)
- }
- func newTestLoader() *UserDetailsLoader {
- rds := testRedis()
- m := testModels()
- return NewUserDetailsLoader(rds, testKeyPrefix, m)
- }
- func now() int64 { return time.Now().Unix() }
- // --------------- helpers: insert test data ---------------
- func insertUser(ctx context.Context, t *testing.T, m *model.Models, u *userModel.SysUser) int64 {
- t.Helper()
- res, err := m.SysUserModel.Insert(ctx, u)
- require.NoError(t, err)
- id, _ := res.LastInsertId()
- return id
- }
- func insertDept(ctx context.Context, t *testing.T, m *model.Models, d *deptModel.SysDept) int64 {
- t.Helper()
- res, err := m.SysDeptModel.Insert(ctx, d)
- require.NoError(t, err)
- id, _ := res.LastInsertId()
- return id
- }
- func insertProduct(ctx context.Context, t *testing.T, m *model.Models, p *productModel.SysProduct) int64 {
- t.Helper()
- res, err := m.SysProductModel.Insert(ctx, p)
- require.NoError(t, err)
- id, _ := res.LastInsertId()
- return id
- }
- func insertMember(ctx context.Context, t *testing.T, m *model.Models, mb *memberModel.SysProductMember) int64 {
- t.Helper()
- res, err := m.SysProductMemberModel.Insert(ctx, mb)
- require.NoError(t, err)
- id, _ := res.LastInsertId()
- return id
- }
- func insertRole(ctx context.Context, t *testing.T, m *model.Models, r *roleModel.SysRole) int64 {
- t.Helper()
- res, err := m.SysRoleModel.Insert(ctx, r)
- require.NoError(t, err)
- id, _ := res.LastInsertId()
- return id
- }
- func insertPerm(ctx context.Context, t *testing.T, m *model.Models, p *permModel.SysPerm) int64 {
- t.Helper()
- res, err := m.SysPermModel.Insert(ctx, p)
- require.NoError(t, err)
- id, _ := res.LastInsertId()
- return id
- }
- func insertUserRole(ctx context.Context, t *testing.T, m *model.Models, ur *userRoleModel.SysUserRole) int64 {
- t.Helper()
- res, err := m.SysUserRoleModel.Insert(ctx, ur)
- require.NoError(t, err)
- id, _ := res.LastInsertId()
- return id
- }
- func insertRolePerm(ctx context.Context, t *testing.T, m *model.Models, rp *rolePermModel.SysRolePerm) int64 {
- t.Helper()
- res, err := m.SysRolePermModel.Insert(ctx, rp)
- require.NoError(t, err)
- id, _ := res.LastInsertId()
- return id
- }
- func insertUserPerm(ctx context.Context, t *testing.T, m *model.Models, up *userPermModel.SysUserPerm) int64 {
- t.Helper()
- res, err := m.SysUserPermModel.Insert(ctx, up)
- require.NoError(t, err)
- id, _ := res.LastInsertId()
- return id
- }
- // --------------- TC-0506: Load-DB加载(缓存miss) ---------------
- func TestLoad_DBMiss(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- deptId := insertDept(ctx, t, m, &deptModel.SysDept{
- ParentId: 0, Name: "dept_" + uid, Path: "/1/", Sort: 1,
- DeptType: consts.DeptTypeNormal, Status: consts.StatusEnabled,
- CreateTime: ts, UpdateTime: ts,
- })
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Avatar: sql.NullString{}, Email: uid + "@test.com", Phone: "13800000001",
- Remark: "remark", DeptId: deptId, IsSuperAdmin: consts.IsSuperAdminNo,
- MustChangePassword: consts.MustChangePasswordNo, Status: consts.StatusEnabled,
- CreateTime: ts, UpdateTime: ts,
- })
- productId := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- roleId := insertRole(ctx, t, m, &roleModel.SysRole{
- ProductCode: pcode, Name: "role_" + uid, Remark: "test",
- Status: consts.StatusEnabled, PermsLevel: 10, CreateTime: ts, UpdateTime: ts,
- })
- permId := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "perm_" + uid, Code: "perm:" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- urId := insertUserRole(ctx, t, m, &userRoleModel.SysUserRole{
- UserId: userId, RoleId: roleId, CreateTime: ts, UpdateTime: ts,
- })
- rpId := insertRolePerm(ctx, t, m, &rolePermModel.SysRolePerm{
- RoleId: roleId, PermId: permId, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_role_perm`", rpId)
- cleanTable(ctx, conn, "`sys_user_role`", urId)
- cleanTable(ctx, conn, "`sys_perm`", permId)
- cleanTable(ctx, conn, "`sys_role`", roleId)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", productId)
- cleanTable(ctx, conn, "`sys_user`", userId)
- cleanTable(ctx, conn, "`sys_dept`", deptId)
- })
- // clear any leftover cache
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.Equal(t, userId, ud.UserId)
- assert.Equal(t, uid, ud.Username)
- assert.Equal(t, "nick_"+uid, ud.Nickname)
- assert.Equal(t, uid+"@test.com", ud.Email)
- assert.Equal(t, int64(consts.StatusEnabled), ud.Status)
- assert.Equal(t, deptId, ud.DeptId)
- assert.Equal(t, "dept_"+uid, ud.DeptName)
- assert.Equal(t, pcode, ud.ProductCode)
- assert.Equal(t, "prod_"+uid, ud.ProductName)
- assert.Equal(t, consts.MemberTypeMember, ud.MemberType)
- assert.Len(t, ud.Roles, 1)
- assert.Equal(t, roleId, ud.Roles[0].Id)
- assert.Equal(t, int64(10), ud.MinPermsLevel)
- assert.Contains(t, ud.Perms, "perm:"+uid)
- }
- // --------------- TC-0507: Load-缓存命中 ---------------
- func TestLoad_CacheHit(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000002", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- productId := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_product`", productId)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud1, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud1)
- ud2, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud2)
- assert.Equal(t, ud1.UserId, ud2.UserId)
- assert.Equal(t, ud1.Username, ud2.Username)
- assert.Equal(t, ud1.ProductName, ud2.ProductName)
- }
- // --------------- TC-0508: Load-用户不存在 ---------------
- func TestLoad_UserNotExist(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- nonExistId := int64(999999999)
- loader.Del(ctx, nonExistId, "nonexist_product")
- ud, _ := loader.Load(ctx, nonExistId, "nonexist_product")
- require.NotNil(t, ud)
- assert.Equal(t, int64(0), ud.Status)
- assert.Empty(t, ud.Username)
- assert.Empty(t, ud.Perms)
- assert.Empty(t, ud.Roles)
- loader.Del(ctx, nonExistId, "nonexist_product")
- }
- // --------------- TC-0509: Load-productCode为空 ---------------
- func TestLoad_EmptyProductCode(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000003", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, "")
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, "")
- ud, _ := loader.Load(ctx, userId, "")
- require.NotNil(t, ud)
- assert.Equal(t, uid, ud.Username)
- assert.Equal(t, int64(consts.StatusEnabled), ud.Status)
- assert.Empty(t, ud.ProductCode)
- assert.Empty(t, ud.ProductName)
- assert.Empty(t, ud.MemberType)
- assert.Empty(t, ud.Roles)
- assert.Empty(t, ud.Perms)
- }
- // --------------- TC-0510: Del删除指定缓存 ---------------
- func TestDel(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000004", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- productId := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_product`", productId)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud1, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud1)
- assert.Equal(t, uid, ud1.Username)
- loader.Del(ctx, userId, pcode)
- ud2, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud2)
- assert.Equal(t, uid, ud2.Username)
- }
- // --------------- TC-0511: Clean清除用户所有产品缓存 ---------------
- func TestClean(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode1 := "p1_" + uid
- pcode2 := "p2_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000005", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid1 := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode1, Name: "prod1_" + uid, AppKey: "ak1_" + uid, AppSecret: "as1_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid2 := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode2, Name: "prod2_" + uid, AppKey: "ak2_" + uid, AppSecret: "as2_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode1)
- loader.Del(ctx, userId, pcode2)
- cleanTable(ctx, conn, "`sys_product`", pid1, pid2)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode1)
- loader.Del(ctx, userId, pcode2)
- ud1, _ := loader.Load(ctx, userId, pcode1)
- ud2, _ := loader.Load(ctx, userId, pcode2)
- require.NotNil(t, ud1)
- require.NotNil(t, ud2)
- rds := testRedis()
- key1 := loader.cacheKey(userId, pcode1)
- key2 := loader.cacheKey(userId, pcode2)
- v1, _ := rds.GetCtx(ctx, key1)
- v2, _ := rds.GetCtx(ctx, key2)
- assert.NotEmpty(t, v1)
- assert.NotEmpty(t, v2)
- loader.Clean(ctx, userId)
- v1After, _ := rds.GetCtx(ctx, key1)
- v2After, _ := rds.GetCtx(ctx, key2)
- assert.Empty(t, v1After)
- assert.Empty(t, v2After)
- }
- // --------------- TC-0512: CleanByProduct清除产品所有用户 ---------------
- func TestCleanByProduct(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid1 := uniqueId()
- uid2 := uniqueId()
- ts := now()
- pcode := "p_" + uid1
- userId1 := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid1, Password: hashPwd("pass123"), Nickname: "nick_" + uid1,
- Email: uid1 + "@test.com", Phone: "13800000006", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- userId2 := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid2, Password: hashPwd("pass123"), Nickname: "nick_" + uid2,
- Email: uid2 + "@test.com", Phone: "13800000007", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid1, AppKey: "ak_" + uid1, AppSecret: "as_" + uid1,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId1, pcode)
- loader.Del(ctx, userId2, pcode)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId1, userId2)
- })
- loader.Del(ctx, userId1, pcode)
- loader.Del(ctx, userId2, pcode)
- _, _ = loader.Load(ctx, userId1, pcode)
- _, _ = loader.Load(ctx, userId2, pcode)
- rds := testRedis()
- k1 := loader.cacheKey(userId1, pcode)
- k2 := loader.cacheKey(userId2, pcode)
- v1, _ := rds.GetCtx(ctx, k1)
- v2, _ := rds.GetCtx(ctx, k2)
- assert.NotEmpty(t, v1)
- assert.NotEmpty(t, v2)
- loader.CleanByProduct(ctx, pcode)
- v1After, _ := rds.GetCtx(ctx, k1)
- v2After, _ := rds.GetCtx(ctx, k2)
- assert.Empty(t, v1After)
- assert.Empty(t, v2After)
- }
- // --------------- TC-0513: BatchDel批量删除 ---------------
- func TestBatchDel(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid1 := uniqueId()
- uid2 := uniqueId()
- ts := now()
- pcode := "p_" + uid1
- userId1 := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid1, Password: hashPwd("pass123"), Nickname: "nick_" + uid1,
- Email: uid1 + "@test.com", Phone: "13800000008", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- userId2 := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid2, Password: hashPwd("pass123"), Nickname: "nick_" + uid2,
- Email: uid2 + "@test.com", Phone: "13800000009", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid1, AppKey: "ak_" + uid1, AppSecret: "as_" + uid1,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId1, pcode)
- loader.Del(ctx, userId2, pcode)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId1, userId2)
- })
- loader.Del(ctx, userId1, pcode)
- loader.Del(ctx, userId2, pcode)
- _, _ = loader.Load(ctx, userId1, pcode)
- _, _ = loader.Load(ctx, userId2, pcode)
- rds := testRedis()
- k1 := loader.cacheKey(userId1, pcode)
- k2 := loader.cacheKey(userId2, pcode)
- v1, _ := rds.GetCtx(ctx, k1)
- v2, _ := rds.GetCtx(ctx, k2)
- assert.NotEmpty(t, v1)
- assert.NotEmpty(t, v2)
- loader.BatchDel(ctx, []int64{userId1, userId2}, pcode)
- v1After, _ := rds.GetCtx(ctx, k1)
- v2After, _ := rds.GetCtx(ctx, k2)
- assert.Empty(t, v1After)
- assert.Empty(t, v2After)
- }
- // --------------- TC-0514: BatchDel空数组 ---------------
- func TestBatchDel_EmptySlice(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- loader.BatchDel(ctx, []int64{}, "some_code")
- }
- // --------------- TC-0515: loadPerms-超管拥有全部权限 ---------------
- func TestLoadPerms_SuperAdmin(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000010", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminYes, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- permCode1 := "perm1:" + uid
- permCode2 := "perm2:" + uid
- permId1 := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "p1_" + uid, Code: permCode1,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- permId2 := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "p2_" + uid, Code: permCode2,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_perm`", permId1, permId2)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.True(t, ud.IsSuperAdmin)
- assert.Equal(t, consts.MemberTypeSuperAdmin, ud.MemberType)
- sort.Strings(ud.Perms)
- expected := []string{permCode1, permCode2}
- sort.Strings(expected)
- assert.Equal(t, expected, ud.Perms)
- }
- // --------------- TC-0516: loadPerms-ADMIN成员拥有全部权限 ---------------
- func TestLoadPerms_AdminMember(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000011", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeAdmin,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- permCode := "perm:" + uid
- permId := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "p_" + uid, Code: permCode,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_perm`", permId)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.Equal(t, consts.MemberTypeAdmin, ud.MemberType)
- assert.Contains(t, ud.Perms, permCode)
- }
- // --------------- TC-0517: loadPerms-DEVELOPER成员拥有全部权限 ---------------
- func TestLoadPerms_DeveloperMember(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000012", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeDeveloper,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- permCode := "perm:" + uid
- permId := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "p_" + uid, Code: permCode,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_perm`", permId)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.Equal(t, consts.MemberTypeDeveloper, ud.MemberType)
- assert.Contains(t, ud.Perms, permCode)
- }
- // --------------- TC-0518: loadPerms-DEV部门成员拥有全部权限 ---------------
- func TestLoadPerms_DevDept(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- deptId := insertDept(ctx, t, m, &deptModel.SysDept{
- ParentId: 0, Name: "devdept_" + uid, Path: "/1/", Sort: 1,
- DeptType: consts.DeptTypeDev, Status: consts.StatusEnabled,
- CreateTime: ts, UpdateTime: ts,
- })
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000013", DeptId: deptId,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- permCode := "perm:" + uid
- permId := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "p_" + uid, Code: permCode,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_perm`", permId)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- cleanTable(ctx, conn, "`sys_dept`", deptId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.Equal(t, consts.DeptTypeDev, ud.DeptType)
- assert.Contains(t, ud.Perms, permCode)
- }
- // --------------- TC-0519: MEMBER角色权限+ALLOW-DENY ---------------
- func TestLoadPerms_MemberRolePermWithAllowDeny(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000014", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- roleId := insertRole(ctx, t, m, &roleModel.SysRole{
- ProductCode: pcode, Name: "role_" + uid, Remark: "test",
- Status: consts.StatusEnabled, PermsLevel: 10, CreateTime: ts, UpdateTime: ts,
- })
- urId := insertUserRole(ctx, t, m, &userRoleModel.SysUserRole{
- UserId: userId, RoleId: roleId, CreateTime: ts, UpdateTime: ts,
- })
- // role perm: permA, permB
- permIdA := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "permA_" + uid, Code: "permA:" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- permIdB := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "permB_" + uid, Code: "permB:" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- // user ALLOW perm: permC
- permIdC := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "permC_" + uid, Code: "permC:" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- // user DENY perm: permB (should remove permB from result)
- rpIdA := insertRolePerm(ctx, t, m, &rolePermModel.SysRolePerm{
- RoleId: roleId, PermId: permIdA, CreateTime: ts, UpdateTime: ts,
- })
- rpIdB := insertRolePerm(ctx, t, m, &rolePermModel.SysRolePerm{
- RoleId: roleId, PermId: permIdB, CreateTime: ts, UpdateTime: ts,
- })
- upAllow := insertUserPerm(ctx, t, m, &userPermModel.SysUserPerm{
- UserId: userId, PermId: permIdC, Effect: consts.PermEffectAllow,
- CreateTime: ts, UpdateTime: ts,
- })
- upDeny := insertUserPerm(ctx, t, m, &userPermModel.SysUserPerm{
- UserId: userId, PermId: permIdB, Effect: consts.PermEffectDeny,
- CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_user_perm`", upAllow, upDeny)
- cleanTable(ctx, conn, "`sys_role_perm`", rpIdA, rpIdB)
- cleanTable(ctx, conn, "`sys_perm`", permIdA, permIdB, permIdC)
- cleanTable(ctx, conn, "`sys_user_role`", urId)
- cleanTable(ctx, conn, "`sys_role`", roleId)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- // permA (from role) + permC (from ALLOW) should be present
- // permB (denied) should NOT be present
- assert.Contains(t, ud.Perms, "permA:"+uid)
- assert.Contains(t, ud.Perms, "permC:"+uid)
- assert.NotContains(t, ud.Perms, "permB:"+uid)
- }
- // --------------- TC-0522: loadRoles-多角色取最小permsLevel ---------------
- func TestLoadRoles_MinPermsLevel(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000015", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- roleId1 := insertRole(ctx, t, m, &roleModel.SysRole{
- ProductCode: pcode, Name: "roleH_" + uid, Remark: "high",
- Status: consts.StatusEnabled, PermsLevel: 10, CreateTime: ts, UpdateTime: ts,
- })
- roleId2 := insertRole(ctx, t, m, &roleModel.SysRole{
- ProductCode: pcode, Name: "roleL_" + uid, Remark: "low",
- Status: consts.StatusEnabled, PermsLevel: 5, CreateTime: ts, UpdateTime: ts,
- })
- urId1 := insertUserRole(ctx, t, m, &userRoleModel.SysUserRole{
- UserId: userId, RoleId: roleId1, CreateTime: ts, UpdateTime: ts,
- })
- urId2 := insertUserRole(ctx, t, m, &userRoleModel.SysUserRole{
- UserId: userId, RoleId: roleId2, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_user_role`", urId1, urId2)
- cleanTable(ctx, conn, "`sys_role`", roleId1, roleId2)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.Len(t, ud.Roles, 2)
- assert.Equal(t, int64(5), ud.MinPermsLevel)
- }
- // --------------- TC-0523: loadRoles-无角色 ---------------
- func TestLoadRoles_NoRoles(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000016", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.Equal(t, int64(math.MaxInt64), ud.MinPermsLevel)
- }
- // --------------- TC-0524: loadRoles-角色跨产品过滤 ---------------
- func TestLoadRoles_CrossProductFilter(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcodeA := "pA_" + uid
- pcodeB := "pB_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000017", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pidA := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcodeA, Name: "prodA_" + uid, AppKey: "akA_" + uid, AppSecret: "asA_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pidB := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcodeB, Name: "prodB_" + uid, AppKey: "akB_" + uid, AppSecret: "asB_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memA := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcodeA, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- roleA := insertRole(ctx, t, m, &roleModel.SysRole{
- ProductCode: pcodeA, Name: "roleA_" + uid, Remark: "A",
- Status: consts.StatusEnabled, PermsLevel: 10, CreateTime: ts, UpdateTime: ts,
- })
- roleB := insertRole(ctx, t, m, &roleModel.SysRole{
- ProductCode: pcodeB, Name: "roleB_" + uid, Remark: "B",
- Status: consts.StatusEnabled, PermsLevel: 20, CreateTime: ts, UpdateTime: ts,
- })
- urA := insertUserRole(ctx, t, m, &userRoleModel.SysUserRole{
- UserId: userId, RoleId: roleA, CreateTime: ts, UpdateTime: ts,
- })
- urB := insertUserRole(ctx, t, m, &userRoleModel.SysUserRole{
- UserId: userId, RoleId: roleB, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcodeA)
- loader.Del(ctx, userId, pcodeB)
- cleanTable(ctx, conn, "`sys_user_role`", urA, urB)
- cleanTable(ctx, conn, "`sys_role`", roleA, roleB)
- cleanTable(ctx, conn, "`sys_product_member`", memA)
- cleanTable(ctx, conn, "`sys_product`", pidA, pidB)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcodeA)
- ud, _ := loader.Load(ctx, userId, pcodeA)
- require.NotNil(t, ud)
- assert.Len(t, ud.Roles, 1)
- assert.Equal(t, roleA, ud.Roles[0].Id)
- assert.Equal(t, int64(10), ud.MinPermsLevel)
- }
- // --------------- TC-0525: loadRoles-禁用角色不计入 ---------------
- func TestLoadRoles_DisabledRoleExcluded(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000018", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- enabledRole := insertRole(ctx, t, m, &roleModel.SysRole{
- ProductCode: pcode, Name: "rEnabled_" + uid, Remark: "enabled",
- Status: consts.StatusEnabled, PermsLevel: 5, CreateTime: ts, UpdateTime: ts,
- })
- disabledRole := insertRole(ctx, t, m, &roleModel.SysRole{
- ProductCode: pcode, Name: "rDisabled_" + uid, Remark: "disabled",
- Status: consts.StatusDisabled, PermsLevel: 1, CreateTime: ts, UpdateTime: ts,
- })
- ur1 := insertUserRole(ctx, t, m, &userRoleModel.SysUserRole{
- UserId: userId, RoleId: enabledRole, CreateTime: ts, UpdateTime: ts,
- })
- ur2 := insertUserRole(ctx, t, m, &userRoleModel.SysUserRole{
- UserId: userId, RoleId: disabledRole, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_user_role`", ur1, ur2)
- cleanTable(ctx, conn, "`sys_role`", enabledRole, disabledRole)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.Len(t, ud.Roles, 1)
- assert.Equal(t, enabledRole, ud.Roles[0].Id)
- assert.Equal(t, int64(5), ud.MinPermsLevel)
- }
- // --------------- TC-0526: loadMembership-超管自动SUPER_ADMIN ---------------
- func TestLoadMembership_SuperAdminAuto(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000019", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminYes, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.True(t, ud.IsSuperAdmin)
- assert.Equal(t, consts.MemberTypeSuperAdmin, ud.MemberType)
- }
- // --------------- TC-0527: loadMembership-非成员MemberType为空 ---------------
- func TestLoadMembership_NonMemberEmpty(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000020", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.False(t, ud.IsSuperAdmin)
- assert.Empty(t, ud.MemberType)
- }
- // --------------- TC-0520: loadPerms-用户ALLOW权限不跨产品泄漏(修复验证) ---------------
- func TestLoadPerms_CrossProductPermIsolation(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcodeA := "pA_" + uid
- pcodeB := "pB_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000030", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pidA := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcodeA, Name: "prodA_" + uid, AppKey: "akA_" + uid, AppSecret: "asA_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pidB := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcodeB, Name: "prodB_" + uid, AppKey: "akB_" + uid, AppSecret: "asB_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memA := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcodeA, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memB := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcodeB, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- permA := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcodeA, Name: "permA_" + uid, Code: "permA:" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- permB := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcodeB, Name: "permB_" + uid, Code: "permB:" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- upA := insertUserPerm(ctx, t, m, &userPermModel.SysUserPerm{
- UserId: userId, PermId: permA, Effect: consts.PermEffectAllow,
- CreateTime: ts, UpdateTime: ts,
- })
- upB := insertUserPerm(ctx, t, m, &userPermModel.SysUserPerm{
- UserId: userId, PermId: permB, Effect: consts.PermEffectAllow,
- CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcodeA)
- loader.Del(ctx, userId, pcodeB)
- cleanTable(ctx, conn, "`sys_user_perm`", upA, upB)
- cleanTable(ctx, conn, "`sys_perm`", permA, permB)
- cleanTable(ctx, conn, "`sys_product_member`", memA, memB)
- cleanTable(ctx, conn, "`sys_product`", pidA, pidB)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcodeA)
- udA, _ := loader.Load(ctx, userId, pcodeA)
- require.NotNil(t, udA)
- assert.Contains(t, udA.Perms, "permA:"+uid, "产品A应包含自身权限")
- assert.NotContains(t, udA.Perms, "permB:"+uid, "产品A不应包含产品B的权限")
- loader.Del(ctx, userId, pcodeB)
- udB, _ := loader.Load(ctx, userId, pcodeB)
- require.NotNil(t, udB)
- assert.Contains(t, udB.Perms, "permB:"+uid, "产品B应包含自身权限")
- assert.NotContains(t, udB.Perms, "permA:"+uid, "产品B不应包含产品A的权限")
- }
- // --------------- TC-0528: loadMembership-禁用成员MemberType为空(修复验证) ---------------
- func TestLoadMembership_DisabledMemberEmpty(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000031", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusDisabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.Empty(t, ud.MemberType, "禁用成员的MemberType应为空")
- }
- // --------------- TC-0521: loadPerms-DEV部门禁用后不再拥有全部权限(修复验证) ---------------
- func TestLoadPerms_DisabledDevDeptNoFullPerms(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- deptId := insertDept(ctx, t, m, &deptModel.SysDept{
- ParentId: 0, Name: "devdept_disabled_" + uid, Path: "/1/", Sort: 1,
- DeptType: consts.DeptTypeDev, Status: consts.StatusDisabled,
- CreateTime: ts, UpdateTime: ts,
- })
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800000032", DeptId: deptId,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- permCode := "perm_devtest:" + uid
- permId := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "p_" + uid, Code: permCode,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_perm`", permId)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- cleanTable(ctx, conn, "`sys_dept`", deptId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- assert.Equal(t, consts.DeptTypeDev, ud.DeptType)
- assert.Equal(t, int64(consts.StatusDisabled), ud.DeptStatus)
- assert.Empty(t, ud.Perms, "禁用的DEV部门成员不应拥有全部权限")
- }
- // ---------------------------------------------------------------------------
- // audit 回归:DEV 部门用户即使 dept.status=Enabled,
- // 一旦产品成员被禁用 (MemberType 清空),也不得继续获得全量权限。
- // ---------------------------------------------------------------------------
- // TC-0704: DEV 部门 + 产品成员已禁用 → 不应获得全量权限
- func TestLoadPerms_DevDept_DisabledMember_NoFullPerms(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- uid := uniqueId()
- ts := now()
- pcode := "p_" + uid
- // DEV 部门本身启用
- deptId := insertDept(ctx, t, m, &deptModel.SysDept{
- ParentId: 0, Name: "devdept_h3_" + uid, Path: "/1/", Sort: 1,
- DeptType: consts.DeptTypeDev, Status: consts.StatusEnabled,
- CreateTime: ts, UpdateTime: ts,
- })
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pass123"), Nickname: "nick_" + uid,
- Email: uid + "@test.com", Phone: "13800099901", DeptId: deptId,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "prod_" + uid, AppKey: "ak_" + uid, AppSecret: "as_" + uid,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- // 关键:产品成员被禁用 (Status=2)
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: pcode, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusDisabled, CreateTime: ts, UpdateTime: ts,
- })
- permCode := "perm_h3:" + uid
- permId := insertPerm(ctx, t, m, &permModel.SysPerm{
- ProductCode: pcode, Name: "p_" + uid, Code: permCode,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, pcode)
- cleanTable(ctx, conn, "`sys_perm`", permId)
- cleanTable(ctx, conn, "`sys_product_member`", memberId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId)
- cleanTable(ctx, conn, "`sys_dept`", deptId)
- })
- loader.Del(ctx, userId, pcode)
- ud, _ := loader.Load(ctx, userId, pcode)
- require.NotNil(t, ud)
- // 部门信息正常载入
- assert.Equal(t, consts.DeptTypeDev, ud.DeptType)
- assert.Equal(t, int64(consts.StatusEnabled), ud.DeptStatus)
- // 关键:禁用的产品成员,MemberType 被清空
- assert.Equal(t, "", ud.MemberType, "禁用产品成员的 MemberType 应被清空")
- // 关键:DEV 部门 + MemberType='' → 修复后不再命中全量权限分支
- assert.Empty(t, ud.Perms,
- "产品成员被禁用的 DEV 部门用户不应再被授予全量权限")
- }
- // ---------------------------------------------------------------------------
- // audit 回归:当用户不存在时,Load 不应缓存零值 UserDetails
- // ---------------------------------------------------------------------------
- // TC-0705: Load 不存在用户时应返回 nil 且不在 Redis 中留下空缓存
- func TestLoad_NonExistentUser_NotCached(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- nonExistentUserId := int64(999999999)
- pcode := "p_" + uniqueId()
- // 预先确保缓存中没有该 key
- loader.Del(ctx, nonExistentUserId, pcode)
- ud, _ := loader.Load(ctx, nonExistentUserId, pcode)
- // 按当前实现,Load 返回的是 ud(可能是 nil 或零值的 UserDetails),调用方通过 ud.Username == "" 判定不存在。
- // 的关键断言:不论返回什么,Redis 里必须没有缓存的 key(即下次 Load 依然走 DB)
- // 通过再读一次 Redis 判定:间接用 loader.Del 的 key 规则读取
- // 这里简化为:第二次 Load 依然必须从 DB 查询(不能命中缓存)
- // 验证方式:调用 Del 不报错 + 再次 Load 也应得到空 Username
- if ud != nil {
- assert.Empty(t, ud.Username, "不存在用户返回的 ud 必须是空 Username")
- }
- ud2, _ := loader.Load(ctx, nonExistentUserId, pcode)
- if ud2 != nil {
- assert.Empty(t, ud2.Username)
- }
- }
- func TestCleanByUserIds_WipesAllUserProductKeysAndIndexes(t *testing.T) {
- rds := testRedis()
- loader := newTestLoader()
- ctx := context.Background()
- type cell struct {
- uid int64
- pc string
- }
- cells := []cell{
- {1000001, "pcX"}, {1000001, "pcY"},
- {1000002, "pcX"}, {1000002, "pcY"},
- {1000003, "pcX"}, {1000003, "pcY"},
- }
- // 预埋缓存:每个 cell 写一条 value 到 cacheKey,并 SADD 到 user / product 索引。
- cacheKeys := make([]string, 0, len(cells))
- for _, c := range cells {
- ck := loader.cacheKey(c.uid, c.pc)
- require.NoError(t, rds.SetCtx(ctx, ck, "dummy"))
- _, _ = rds.SaddCtx(ctx, loader.userIndexKey(c.uid), ck)
- _, _ = rds.SaddCtx(ctx, loader.productIndexKey(c.pc), ck)
- cacheKeys = append(cacheKeys, ck)
- }
- // 调用 CleanByUserIds 触发 SUNION + 批 DEL。
- loader.CleanByUserIds(ctx, []int64{1000001, 1000002, 1000003})
- // 6 条 ud: key 必须全消失。
- for _, ck := range cacheKeys {
- exist, err := rds.ExistsCtx(ctx, ck)
- require.NoError(t, err)
- assert.False(t, exist, "cacheKey %s 必须被清理", ck)
- }
- // 3 条 user 索引 key 必须也被清掉(否则会漏缓存)。
- for _, uid := range []int64{1000001, 1000002, 1000003} {
- exist, err := rds.ExistsCtx(ctx, loader.userIndexKey(uid))
- require.NoError(t, err)
- assert.False(t, exist,
- "user 索引集合必须被 DEL,否则下次 Clean 会复活假指针")
- }
- // 清理 product 索引残留(修复 SLA 不负责 product 索引,其残留 key 已在 user 索引里一并清掉
- // 的那一组;但为了测试幂等性,手动 cleanup)。
- t.Cleanup(func() {
- _, _ = rds.DelCtx(ctx, loader.productIndexKey("pcX"), loader.productIndexKey("pcY"))
- })
- }
- // TC-0847: 空 ids 切片必须直接返回,不打 Redis。
- // 如果源码退化成把空 SUNION 交给 Redis,会收到 "SUNION wrong number of arguments" 错误;
- // 我们通过断言 Redis 未产生任何错误以及函数未 panic 来验证。
- func TestCleanByUserIds_EmptyIds_NoOp(t *testing.T) {
- loader := newTestLoader()
- // 只要不 panic、返回即可;如果源码 foundation 有 wrong-args 会 logx.Errorf 输出,
- // 这里做最小断言:调用返回控制权。
- loader.CleanByUserIds(context.Background(), nil)
- loader.CleanByUserIds(context.Background(), []int64{})
- // 若走到了 SUNION 分支,Redis 会在 wrong-args 下被 logx 记 Errorf,
- // 业务回调仍然返回,此时不应 panic;通过到达本行说明 OK。
- }
- func TestUserDetailsLoader_MN2_BatchDelClearsUserAndProductIndexes(t *testing.T) {
- ctx := context.Background()
- conn := testConn()
- m := testModels()
- loader := newTestLoader()
- rds := testRedis()
- ts := now()
- pcode := "mn2_" + uniqueId()
- // 插入两个用户 + 一个真实产品,确保 Load 走到 5 分钟正缓存分支并注册索引
- uid1 := uniqueId()
- uid2 := uniqueId()
- userId1 := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid1, Password: hashPwd("pass123"), Nickname: "nick_" + uid1,
- Email: uid1 + "@t.com", Phone: "13800000008", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- userId2 := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid2, Password: hashPwd("pass123"), Nickname: "nick_" + uid2,
- Email: uid2 + "@t.com", Phone: "13800000009", DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: pcode, Name: "p_" + pcode, AppKey: "ak_" + pcode, AppSecret: "as_" + pcode,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId1, pcode)
- loader.Del(ctx, userId2, pcode)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTable(ctx, conn, "`sys_user`", userId1, userId2)
- })
- // 把缓存一次预热,让 userIndex/productIndex 被 registerCacheKey 真实写入
- _, err := loader.Load(ctx, userId1, pcode)
- require.NoError(t, err)
- _, err = loader.Load(ctx, userId2, pcode)
- require.NoError(t, err)
- k1 := loader.cacheKey(userId1, pcode)
- k2 := loader.cacheKey(userId2, pcode)
- pIdx := loader.productIndexKey(pcode)
- u1Idx := loader.userIndexKey(userId1)
- u2Idx := loader.userIndexKey(userId2)
- // 预检:主 key 写入、productIndex / userIndex 存在对应元素
- for _, k := range []string{k1, k2} {
- val, gerr := rds.GetCtx(ctx, k)
- require.NoError(t, gerr)
- require.NotEmpty(t, val, "主 cacheKey 必须被写入才有意义")
- }
- has, _ := rds.SismemberCtx(ctx, pIdx, k1)
- require.True(t, has, "productIndex 必须含 k1")
- has, _ = rds.SismemberCtx(ctx, pIdx, k2)
- require.True(t, has, "productIndex 必须含 k2")
- has, _ = rds.SismemberCtx(ctx, u1Idx, k1)
- require.True(t, has, "userIndex(u1) 必须含 k1")
- has, _ = rds.SismemberCtx(ctx, u2Idx, k2)
- require.True(t, has, "userIndex(u2) 必须含 k2")
- // 触发被测路径:BatchDel(pipelined SREM)
- loader.BatchDel(ctx, []int64{userId1, userId2}, pcode)
- // 主 key 被清空(原 TC-0513 已保障)
- for _, k := range []string{k1, k2} {
- val, _ := rds.GetCtx(ctx, k)
- assert.Empty(t, val, "BatchDel 必须删除主 cacheKey")
- }
- // userIndex / productIndex 中的对应 cacheKey 必须被 SREM 清除(本 TC 核心断言)
- has, _ = rds.SismemberCtx(ctx, u1Idx, k1)
- assert.False(t, has, "BatchDel 必须把 k1 从 userIndex(u1) SREM 出去")
- has, _ = rds.SismemberCtx(ctx, u2Idx, k2)
- assert.False(t, has, "BatchDel 必须把 k2 从 userIndex(u2) SREM 出去")
- has, _ = rds.SismemberCtx(ctx, pIdx, k1)
- assert.False(t, has, "BatchDel 必须把 k1 从 productIndex SREM 出去")
- has, _ = rds.SismemberCtx(ctx, pIdx, k2)
- assert.False(t, has, "BatchDel 必须把 k2 从 productIndex SREM 出去")
- }
- // TC-1014: productCode 为空时 BatchDel 仅 SREM userIndex,不得 panic 或误访问 productIndex。
- // 目前业务侧 BatchDel 的所有调用都传了 productCode;但 pipeline 分支必须对空串 fail-safe,
- // 防止未来调用方误传时 pipeline 里塞空 key 把 Redis 侧写脏。
- func TestUserDetailsLoader_MN2_BatchDelEmptyProductCodeDoesNotPanic(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- // 即便 uid 不存在,pipelined SREM 对不存在的集合是 no-op,不应报错/panic
- require.NotPanics(t, func() {
- loader.BatchDel(ctx, []int64{9999999991, 9999999992}, "")
- })
- }
- func TestUserDetailsLoader_Load_NotExist_ReturnsUdWithNilErr(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- nonExistId := int64(900_100_000 + time.Now().UnixNano()%100_000)
- productCode := "pc_nxud_" + uniqueId()
- t.Cleanup(func() { loader.Del(ctx, nonExistId, productCode) })
- ud, err := loader.Load(ctx, nonExistId, productCode)
- require.NoError(t, err,
- "用户不存在必须走 (ud,nil) 语义;否则中间件会把 DB 抖动同化成 401 强制下线引发雪崩")
- require.NotNil(t, ud)
- assert.Equal(t, nonExistId, ud.UserId)
- assert.Equal(t, productCode, ud.ProductCode)
- assert.Empty(t, ud.Username, "Username 必须为空以便调用方判定为 404 用户")
- }
- // TC-0914: 并发时序:CreateUser 成功但 Load 已经走到"写负缓存哨兵"分支之前,
- // 再次 FindOne 复核必须把"刚创建的用户"识别出来,跳过哨兵写入,避免新用户被投毒。
- //
- // 本测试构造的时序:先 Insert 一个真实用户(这步 Insert 会 DEL 用户主键缓存),
- // 再立即 Load 该 userId+productCode。 的 freshCheck 必须让"这个第一 Load"拿到用户数据,
- // 而不是把 ud:<id>:<pc> 写为 _NOT_FOUND_。
- func TestUserDetailsLoader_Load_L6_CreateUserThenLoadDoesNotWriteSentinel(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- conn := testConn()
- m := testModels()
- ts := now()
- uid := uniqueId()
- productCode := "pc_l6_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pw"), Nickname: "l6",
- Avatar: sql.NullString{}, IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- // 修复后,Load 要求 productCode 对应的产品真实存在才能进入正缓存分支;否则
- // loadProduct 失败会被提升为 ErrLoaderDegraded。 的主题是"新用户写入后首次 Load
- // 不得被自身写的负缓存哨兵投毒",与"产品不存在"正交,因此这里补一条真实产品。
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: productCode, Name: "l6_prod", AppKey: "ak", AppSecret: "as",
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, productCode)
- cleanTable(ctx, conn, "`sys_user`", userId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- })
- loader.Del(ctx, userId, productCode)
- ud, err := loader.Load(ctx, userId, productCode)
- require.NoError(t, err)
- require.NotNil(t, ud)
- assert.Equal(t, uid, ud.Username, "Load 必须识别出这是真实用户而不是写哨兵")
- // 关键断言:Redis key 里的值绝不能是哨兵。
- val, err := loader.rds.GetCtx(ctx, loader.cacheKey(userId, productCode))
- require.NoError(t, err)
- assert.NotEqual(t, negativeCacheMarker, val,
- "新创建的用户首次 Load 不得被写入负缓存哨兵,否则 10s 内所有请求都会被判为'已删除'")
- }
- // TC-0915 (重写 · ): partial load 失败必须返回 ErrLoaderDegraded(而非 (ud,nil) 半成品),
- // 让调用方统一把它映射为 503 / codes.Unavailable;同时 5 分钟正缓存绝不能被写入。
- //
- // 历史契约:loadOk=false 时 Load 返回 (ud, nil),ud 是 Username 非空但 DeptPath=""/Perms=nil 的
- // 半成品,然后 jwtauth / refreshToken / GetUserPerms 等调用方因 MemberType=="" 或
- // ProductStatus!=Enabled 错把它当成"产品已被禁用 / 无权限" 返 403,一次 DB 抖动全站静默 403。
- // 新契约():loadOk=false → (nil, ErrLoaderDegraded);调用方 err!=nil 分支自然映射
- // 503 / codes.Unavailable,SOC 侧能明确观测到基础设施故障。
- func TestUserDetailsLoader_Load_MN1_PartialLoadReturnsErrDegradedAndSkipsCache(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- conn := testConn()
- m := testModels()
- ts := now()
- uid := uniqueId()
- productCode := "pc_mn1_" + uid
- // 用一个极大的 DeptId 指向不存在的部门,让 loadDept 报 ErrNotFound → loadFromDB loadOk=false。
- phantomDeptId := int64(999_000_000_000)
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pw"), Nickname: "mn1",
- Avatar: sql.NullString{}, DeptId: phantomDeptId,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- // 给产品落一条真实数据,让 loadProduct 本身成功,单独锁定"dept 子步骤失败"这个变量。
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: productCode, Name: "mn1_prod", AppKey: "ak", AppSecret: "as",
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- t.Cleanup(func() {
- loader.Del(ctx, userId, productCode)
- cleanTable(ctx, conn, "`sys_user`", userId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- })
- loader.Del(ctx, userId, productCode)
- ud, err := loader.Load(ctx, userId, productCode)
- // 新契约:partial load 必须向上冒 ErrLoaderDegraded;ud 必须为 nil,避免调用方误用半成品。
- require.ErrorIs(t, err, ErrLoaderDegraded,
- "partial load 必须返回 ErrLoaderDegraded,而不是把半成品 ud 静默当成业务拒绝")
- assert.Nil(t, ud, "err 非 nil 时 ud 必须为 nil,杜绝上层误用半成品字段")
- // 断言 1:Redis 里没有 5 分钟正缓存,主 key 要么完全未写,要么仅留空串。
- val, err := loader.rds.GetCtx(ctx, loader.cacheKey(userId, productCode))
- require.NoError(t, err)
- if val != "" {
- assert.NotContains(t, val, "\"username\":\""+uid+"\"",
- "partial-load 不得把半残 UD 写进 5 分钟正缓存")
- }
- }
- // TC-0917 (新增 · ): ErrLoaderDegraded 必须是可用 errors.Is 断言的独立 sentinel,
- // 供调用方在 HTTP 中间件 / gRPC 拦截器里做到"统一映射 503"而不需要字符串匹配。
- func TestUserDetailsLoader_ErrLoaderDegraded_IsStableSentinel(t *testing.T) {
- require.NotNil(t, ErrLoaderDegraded, "必须导出 sentinel 便于调用方识别")
- // 再次发生的派生错误仍应 errors.Is 成立(防御"被包一层后调用方失配")。
- wrapped := errors.New("extra: " + ErrLoaderDegraded.Error())
- assert.False(t, errors.Is(wrapped, ErrLoaderDegraded),
- "新 error 与 sentinel 不应共享身份;如需传染请显式 fmt.Errorf(\"%%w\", ErrLoaderDegraded)")
- assert.True(t, errors.Is(ErrLoaderDegraded, ErrLoaderDegraded),
- "自身 Is 必须为 true(sanity check)")
- }
- // TC-0916: deny 查询失败时 fail-close 保底()。通过写一个完全无 perm 的普通 MEMBER,
- // 再通过 productCode 设为 disabled 让 loadPerms 走 ProductStatus != Enabled 提前返回;再切回
- // Enabled 状态,确保 perm 分支被正常 reach 到,覆盖 "allowIds 查询路径正常结束" 的成功契约。
- // 这里的反面(fail-close)契约已经由上面 TC-0915 的 "dept 失败不写缓存" 验证;单独断言 deny 失败
- // 路径需要 mock 数据库错误,属于下一轮覆盖。
- func TestUserDetailsLoader_Load_H1_EnabledProductMemberPermsNonNil(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- conn := testConn()
- m := testModels()
- ts := now()
- uid := uniqueId()
- productCode := "pc_h1_" + uid
- userId := insertUser(ctx, t, m, &userModel.SysUser{
- Username: uid, Password: hashPwd("pw"), Nickname: "h1",
- Avatar: sql.NullString{}, DeptId: 0,
- IsSuperAdmin: consts.IsSuperAdminNo, MustChangePassword: consts.MustChangePasswordNo,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- pid := insertProduct(ctx, t, m, &productModel.SysProduct{
- Code: productCode, Name: "h1_prod", AppKey: "ak", AppSecret: "as",
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- memberId := insertMember(ctx, t, m, &memberModel.SysProductMember{
- ProductCode: productCode, UserId: userId, MemberType: consts.MemberTypeMember,
- Status: consts.StatusEnabled, CreateTime: ts, UpdateTime: ts,
- })
- _ = memberId
- t.Cleanup(func() {
- loader.Del(ctx, userId, productCode)
- cleanTable(ctx, conn, "`sys_user`", userId)
- cleanTable(ctx, conn, "`sys_product`", pid)
- cleanTableByField(ctx, conn, "`sys_product_member`", "productCode", productCode)
- })
- loader.Del(ctx, userId, productCode)
- ud, err := loader.Load(ctx, userId, productCode)
- require.NoError(t, err)
- require.NotNil(t, ud)
- // 这里不强制 Perms 非 nil —— 用户没有任何角色 / allow,Perms 为空 slice 或 nil 都合理;
- // 重点是 Load 不返回 error、不被 deny 查询(null 结果)污染。
- assert.Equal(t, uid, ud.Username)
- assert.Equal(t, productCode, ud.ProductCode)
- // 再次 Load 必须命中正缓存:GET 出的 value 一定是合法 JSON 且能反序列化回同样的 UD。
- val, err := loader.rds.GetCtx(ctx, loader.cacheKey(userId, productCode))
- require.NoError(t, err)
- require.NotEmpty(t, val, "正常路径必须落正缓存")
- if strings.HasPrefix(val, "{") {
- var cached UserDetails
- require.NoError(t, json.Unmarshal([]byte(val), &cached))
- assert.Equal(t, uid, cached.Username)
- }
- }
- func TestUserDetailsLoader_NegativeCache_HitsOnSecondCall(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- // 随便选一个几乎肯定不存在的 id(避免与真实测试数据冲突)。
- nonExistId := int64(900_000_000 + time.Now().UnixNano()%100_000)
- productCode := "pc_neg_" + uniqueId()
- // 确保无残留缓存。
- loader.Del(ctx, nonExistId, productCode)
- // 第 1 次 Load:预期回写负缓存哨兵。
- // 后 Load 的返回契约从 *UserDetails 扩展为 (*UserDetails, error);
- // 不存在用户走的是 (ud, nil) 语义 (ud.Username == ""),而不是 (nil, err)。
- ud1, err := loader.Load(ctx, nonExistId, productCode)
- require.NoError(t, err, "用户不存在应走 (ud,nil) 语义而不是 (nil,err)")
- require.NotNil(t, ud1)
- assert.Empty(t, ud1.Username, "不存在的用户 Load 后 Username 必须为空")
- // 直接读 Redis,验证哨兵值真的写进去了。
- key := loader.cacheKey(nonExistId, productCode)
- val, err := loader.rds.GetCtx(ctx, key)
- require.NoError(t, err)
- assert.Equal(t, negativeCacheMarker, val,
- "不存在的用户必须写入负缓存哨兵 %q,以便后续命中直接返回空 UserDetails", negativeCacheMarker)
- // 第 2 次 Load:必须命中哨兵分支;哨兵应当返回空 UserDetails(Username 依然为空),
- // 且不得再做 DB 查询(这里没有 mock DB counter,但结果的契约仍然成立)。
- ud2, err := loader.Load(ctx, nonExistId, productCode)
- require.NoError(t, err)
- require.NotNil(t, ud2)
- assert.Empty(t, ud2.Username)
- assert.Equal(t, nonExistId, ud2.UserId)
- assert.Equal(t, productCode, ud2.ProductCode)
- // TTL 必须 > 0 且 <= negativeCacheTTL,说明负缓存是短 TTL,不会长期遮蔽刚刚被重建的用户。
- ttl, err := loader.rds.TtlCtx(ctx, key)
- require.NoError(t, err)
- assert.Greater(t, ttl, 0, "负缓存必须是带 TTL 的短窗口")
- assert.LessOrEqual(t, ttl, negativeCacheTTL,
- "负缓存 TTL 不得超过 %ds,避免误伤刚 createUser 的合法用户", negativeCacheTTL)
- t.Cleanup(func() { loader.Del(ctx, nonExistId, productCode) })
- }
- // TC-0822: 负缓存必须"不挂到 userIndex/productIndex 集合里",
- // 否则 CleanByProduct / Clean 在 DEL 其它真实 key 的同时会顺带 DEL 哨兵,带来短暂"放穿"。
- // 该测试验证:写入负缓存之后,userIndex/productIndex 集合为空。
- func TestUserDetailsLoader_NegativeCache_NotIndexed(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- nonExistId := int64(900_000_123 + time.Now().UnixNano()%10_000)
- productCode := "pc_idx_" + uniqueId()
- loader.Del(ctx, nonExistId, productCode)
- _, _ = loader.Load(ctx, nonExistId, productCode)
- uidx, err := loader.rds.SmembersCtx(ctx, loader.userIndexKey(nonExistId))
- require.NoError(t, err)
- assert.Empty(t, uidx,
- "负缓存不得注册到 user index,否则 Clean(userId) 会把哨兵一起抹掉导致立刻再次击穿 DB")
- pidx, err := loader.rds.SmembersCtx(ctx, loader.productIndexKey(productCode))
- require.NoError(t, err)
- assert.Empty(t, pidx,
- "负缓存同样不得进入 product index")
- t.Cleanup(func() { loader.Del(ctx, nonExistId, productCode) })
- }
- // TC-0823: 多并发同一 nonExistId 只穿透 DB 一次(singleflight + 负缓存联动)。
- // 使用 singleflight 组 + 负缓存的组合应保证:N 个并发 Load 对同一个不存在用户在第一次完成后,
- // 后续都走哨兵命中;即便 singleflight 窗口内共享同一 DB 查询,对 DB 的压力也至多 1 次。
- // 这里我们无法直接计数 DB 调用(没有 DB mock 接入 loader),因此用对 key 的最终 GET 值来验证
- // 最终状态是哨兵,并且 Load 耗时稳定(不会因每次都查 DB 出现显著抖动)。
- func TestUserDetailsLoader_NegativeCache_ConcurrentLoadsStabilize(t *testing.T) {
- ctx := context.Background()
- loader := newTestLoader()
- nonExistId := int64(900_000_456 + time.Now().UnixNano()%10_000)
- productCode := "pc_conc_" + uniqueId()
- loader.Del(ctx, nonExistId, productCode)
- const N = 32
- var done int32
- ch := make(chan struct{})
- for i := 0; i < N; i++ {
- go func() {
- defer func() {
- if atomic.AddInt32(&done, 1) == N {
- close(ch)
- }
- }()
- _, _ = loader.Load(ctx, nonExistId, productCode)
- }()
- }
- select {
- case <-ch:
- case <-time.After(5 * time.Second):
- t.Fatal("并发 Load 未在 5s 内收敛,singleflight/负缓存可能失效")
- }
- val, err := loader.rds.GetCtx(ctx, loader.cacheKey(nonExistId, productCode))
- require.NoError(t, err)
- assert.Equal(t, negativeCacheMarker, val)
- t.Cleanup(func() { loader.Del(ctx, nonExistId, productCode) })
- }
- type countingUserModel struct {
- userModel.SysUserModel
- findOneHits int64
- }
- func (c *countingUserModel) FindOne(ctx context.Context, id int64) (*userModel.SysUser, error) {
- atomic.AddInt64(&c.findOneHits, 1)
- return c.SysUserModel.FindOne(ctx, id)
- }
- // TC-0792: 延伸 —— UserDetailsLoader 必须用 singleflight 合并同一 key 的并发 Load,
- // 保证缓存 miss 时 DB 只被打一次, 防止冷启动/缓存击穿。
- // 实现方式: 用 countingUserModel 拦截 SysUserModel.FindOne, 断言 N 个并发 Load
- // 触发的 FindOne 次数远少于 N (严格来说, 在我们控制的并发时序下必须恰好 1 次)。
- // 为避免 "第一个 goroutine 太快, 写完缓存后其他 goroutine 走 cache 路径也只是少调用"
- // 这种"假阳性平局", 本用例刻意先 Del 缓存 + 用 WaitGroup barrier 同时释放所有 goroutine,
- // 把所有 goroutine 都塞进 singleflight.Do 的同一 key flight 里。
- func TestLoader_Load_SingleflightCollapsesConcurrentCalls(t *testing.T) {
- ctx := context.Background()
- rds := testRedis()
- realModels := testModels()
- counting := &countingUserModel{SysUserModel: realModels.SysUserModel}
- // 替换 models 里的 SysUserModel 为计数包装; 其他模型保持真实以便 loader 的产品/成员/部门/角色/权限流转能跑通
- wrappedModels := *realModels
- wrappedModels.SysUserModel = counting
- loader := NewUserDetailsLoader(rds, testKeyPrefix, &wrappedModels)
- u := &userModel.SysUser{
- Username: "ld_sf_" + uniqueId(), Password: hashPwd("x"), Nickname: "sf",
- Avatar: sql.NullString{}, IsSuperAdmin: consts.IsSuperAdminNo,
- MustChangePassword: consts.MustChangePasswordNo, Status: consts.StatusEnabled,
- CreateTime: now(), UpdateTime: now(),
- }
- userId := insertUser(ctx, t, realModels, u)
- t.Cleanup(func() { cleanTable(ctx, testConn(), "sys_user", userId) })
- // 确保缓存为空
- loader.Del(ctx, userId, "")
- loader.Clean(ctx, userId)
- const workers = 50
- var (
- wg sync.WaitGroup
- start = make(chan struct{})
- ptrs = make([]*UserDetails, workers)
- )
- for i := 0; i < workers; i++ {
- wg.Add(1)
- go func(idx int) {
- defer wg.Done()
- <-start
- ud, _ := loader.Load(ctx, userId, "")
- ptrs[idx] = ud
- }(i)
- }
- close(start)
- wg.Wait()
- // 每个 goroutine 都应拿到完整的用户数据
- for i, p := range ptrs {
- require.NotNil(t, p, "worker %d 返回 nil", i)
- assert.Equal(t, u.Username, p.Username, "worker %d 读到的 Username 错乱", i)
- }
- hits := atomic.LoadInt64(&counting.findOneHits)
- assert.LessOrEqual(t, hits, int64(workers/5),
- "singleflight 必须把 DB 命中压到极少次 (远低于 workers=%d); 实际 FindOne 被调 %d 次", workers, hits)
- assert.Greater(t, hits, int64(0), "至少要有一次 DB 命中 (否则说明缓存未被真正清空)")
- }
- // TC-0793: 延伸 —— 第二波 Load 必须命中缓存, FindOne 不再增加。
- // 这是对 TC-0762 的成对断言: singleflight 合并仅作用于"同一飞行中的并发",
- // 而一旦首次加载完成并写入 Redis, 后续读取应进入 cache fast-path 而非再次走 DB。
- func TestLoader_Load_SecondRoundHitsCache(t *testing.T) {
- ctx := context.Background()
- rds := testRedis()
- realModels := testModels()
- counting := &countingUserModel{SysUserModel: realModels.SysUserModel}
- wrappedModels := *realModels
- wrappedModels.SysUserModel = counting
- loader := NewUserDetailsLoader(rds, testKeyPrefix, &wrappedModels)
- u := &userModel.SysUser{
- Username: "ld_sf2_" + uniqueId(), Password: hashPwd("x"), Nickname: "sf2",
- Avatar: sql.NullString{}, IsSuperAdmin: consts.IsSuperAdminNo,
- MustChangePassword: consts.MustChangePasswordNo, Status: consts.StatusEnabled,
- CreateTime: now(), UpdateTime: now(),
- }
- userId := insertUser(ctx, t, realModels, u)
- t.Cleanup(func() { cleanTable(ctx, testConn(), "sys_user", userId) })
- loader.Del(ctx, userId, "")
- loader.Clean(ctx, userId)
- _, _ = loader.Load(ctx, userId, "")
- firstHits := atomic.LoadInt64(&counting.findOneHits)
- require.Equal(t, int64(1), firstHits, "首次 Load 应命中 DB 一次")
- for i := 0; i < 20; i++ {
- _, _ = loader.Load(ctx, userId, "")
- }
- secondRoundHits := atomic.LoadInt64(&counting.findOneHits) - firstHits
- assert.Equal(t, int64(0), secondRoundHits,
- "后续 Load 必须命中 Redis 缓存; 若持续打到 DB, 说明 cache 写入失败或 TTL 异常")
- }
|