package perm_test import ( "context" "testing" "time" "perms-system-server/internal/model/perm" "perms-system-server/internal/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/zeromicro/go-zero/core/stores/sqlx" ) // --------------------------------------------------------------------------- // 覆盖目标:审计 M-6 修复的预留基础设施 —— FindMapByProductCodeWithTx。 // 它目前尚未在 SyncPermsService 的路径里被连起来使用(service.go 的 NOTE 也说明了这一点), // 但作为供后续 SELECT FOR UPDATE 串行化用的基础方法,必须满足两个契约: // 1) 必须能在 tx 内跑通,并且返回结果与 tx 外的 FindMapByProductCode 完全一致; // 2) 当 productCode 没有任何行时,返回 empty map 而不是 nil(便于上层 `_, ok := map[x]` 安全查询)。 // 如果未来有人改这个方法让它忘记填充 map 或返回 nil,这些测试会立即失败,避免 M-6 的串行化路径被悄悄破坏。 // --------------------------------------------------------------------------- // TC-0807: FindMapByProductCodeWithTx 与 tx 外 FindMapByProductCode 数据一致。 func TestSysPermModel_FindMapByProductCodeWithTx_EqualsNonTx(t *testing.T) { ctx := context.Background() m := newTestSysPermModel(t) conn := testutil.GetTestSqlConn() productCode := "pc_fmwtx_" + testutil.UniqueId() now := time.Now().Unix() res1, err := m.Insert(ctx, &perm.SysPerm{ ProductCode: productCode, Name: "a", Code: "a_" + testutil.UniqueId(), Status: 1, CreateTime: now, UpdateTime: now, }) require.NoError(t, err) id1, _ := res1.LastInsertId() res2, err := m.Insert(ctx, &perm.SysPerm{ ProductCode: productCode, Name: "b", Code: "b_" + testutil.UniqueId(), Status: 2, CreateTime: now, UpdateTime: now, }) require.NoError(t, err) id2, _ := res2.LastInsertId() t.Cleanup(func() { testutil.CleanTable(ctx, conn, "`sys_perm`", id1, id2) }) nonTx, err := m.FindMapByProductCode(ctx, productCode) require.NoError(t, err) require.Len(t, nonTx, 2) var withTx map[string]*perm.SysPerm require.NoError(t, m.TransactCtx(ctx, func(c context.Context, session sqlx.Session) error { var err error withTx, err = m.FindMapByProductCodeWithTx(c, session, productCode) return err })) require.Len(t, withTx, 2) for code, p := range nonTx { gotWithTx, ok := withTx[code] require.True(t, ok, "tx 版本必须返回与非 tx 版本相同的 code 集合") assert.Equal(t, p.Id, gotWithTx.Id) assert.Equal(t, p.Status, gotWithTx.Status, "status(尤其是禁用态)必须真实透传,不能被过滤") assert.Equal(t, p.Name, gotWithTx.Name) } } // TC-0808: 空 productCode 下 FindMapByProductCodeWithTx 返回非 nil 的空 map。 // 上层同步逻辑里会对 map 直接做 `_, ok := existingMap[item.Code]`;如果是 nil 依然安全, // 但若不慎写成 `existingMap[item.Code] = ...` 就会炸,因此约定为"空 map"更稳。 func TestSysPermModel_FindMapByProductCodeWithTx_EmptyIsNonNil(t *testing.T) { ctx := context.Background() m := newTestSysPermModel(t) productCode := "pc_empty_" + testutil.UniqueId() var withTx map[string]*perm.SysPerm require.NoError(t, m.TransactCtx(ctx, func(c context.Context, session sqlx.Session) error { var err error withTx, err = m.FindMapByProductCodeWithTx(c, session, productCode) return err })) require.NotNil(t, withTx, "空集必须是 empty map,而不是 nil(避免上层误用 map 赋值时 panic)") assert.Empty(t, withTx) }