| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162 |
- 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 异常")
- }
- // TC-1205: NORMAL 部门冻结(DeptStatus=Disabled)后成员 Perms 为空 []。
- // loadPerms 在新增的 DeptStatus 前置检查下,NORMAL 部门被禁用后成员重登应立即无权。
- func TestLoadPerms_NormalDeptDisabled_NoPerms(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: "normdept_dis_" + uid, Path: "/1/", Sort: 1,
- DeptType: consts.DeptTypeNormal, 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: "13900000001", 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_normdis:" + 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, err := loader.Load(ctx, userId, pcode)
- require.NoError(t, err)
- require.NotNil(t, ud)
- assert.Equal(t, consts.DeptTypeNormal, ud.DeptType)
- assert.Equal(t, int64(consts.StatusDisabled), ud.DeptStatus)
- assert.NotNil(t, ud.Perms,
- "Perms 必须是非 nil 的空 slice([]string{}),而非 nil;下游 JSON 输出必须为 [] 而非 null")
- assert.Empty(t, ud.Perms,
- "NORMAL 部门冻结后,成员不应拥有任何权限;冻结部门的'会话吊销'需要 loadPerms 也配合清零才能闭环")
- }
- // TC-1206: loadPerms 出口 Perms 恒为非 nil 数组。
- // 普通成员无任何角色和附加权限时,Perms 应为 []string{} 而非 nil。
- // encoding/json 对 nil slice 输出 null,对 []string{} 输出 [];两种空表达不一致会给前端带来冗余 defensive check。
- func TestLoadPerms_EmptyPerms_IsNotNilSlice(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: "13900000002", 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,
- })
- 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, err := loader.Load(ctx, userId, pcode)
- require.NoError(t, err)
- require.NotNil(t, ud)
- // 关键断言:Perms 必须为非 nil 的空 slice,不能是 nil。
- assert.NotNil(t, ud.Perms,
- "无权限成员的 Perms 必须是 []string{}(非 nil);"+
- "Go encoding/json 对 nil 输出 null,对 [] 输出 [],两种'空'造成下游 defensive check 不一致")
- // 验证 JSON 序列化确实输出 []。
- type wrapper struct {
- Perms []string `json:"perms"`
- }
- jsonBytes, marshalErr := json.Marshal(wrapper{Perms: ud.Perms})
- require.NoError(t, marshalErr)
- jsonStr := string(jsonBytes)
- assert.Contains(t, jsonStr, `"perms":[]`,
- "空 Perms 序列化必须为 [],不得为 null;实际 JSON: %s", jsonStr)
- }
- // TC-1207: loadMembership errors.Is 语义稳健性契约测试。
- // productmember.ErrNotFound = sqlx.ErrNotFound;当前代码已改为 errors.Is,确保未来 model 层包装
- // 后 ErrNotFound 仍能被识别,而不会把"用户非成员"退化为 ErrLoaderDegraded 503。
- func TestLoadMembership_ErrNotFound_IsStableContract(t *testing.T) {
- // productmember.ErrNotFound 应等于 sqlx.ErrNotFound。
- require.True(t, errors.Is(memberModel.ErrNotFound, sqlx.ErrNotFound),
- "productmember.ErrNotFound 必须是 sqlx.ErrNotFound 或其包装,"+
- "否则 loadMembership 的 errors.Is 检查无法识别'用户非成员'场景")
- // 包装一层后 errors.Is 仍应成立——防止未来 model 层引入 fmt.Errorf("%w", err) 时失配。
- wrapped := fmt.Errorf("model wrap: %w", memberModel.ErrNotFound)
- require.True(t, errors.Is(wrapped, sqlx.ErrNotFound),
- "单层 fmt.Errorf 包装后 errors.Is 仍须成立;若失败说明 ErrNotFound 不是通过 %%w 传播的哨兵")
- }
|