test: 后端测试从 SQLite 全面切换到 MySQL,与生产环境对齐
测试库不再使用 SQLite 内存库,改为每个测试包独立的 MySQL 库, 表结构由 backend/migrations 的真实迁移建立。 基础设施 - 新增 internal/database/testdb.go:NewTestDB() 保持原签名(28 处调用零改动), 内部连接 MySQL 测试库,首次调用重建库并执行全部真实迁移,之后每次调用清空全表 - 库名 = 测试库基础名 + 包目录名,同包共享、跨包隔离,使 go test ./... 可并发执行 (共用一库时各包会互相 DROP/CREATE 导致 database exists) - 新增 NewDryRunDB():MySQL 方言 + DryRun,供断言 SQL 形态的 5 处测试使用 - 新增 AutoMigrateIfMissing():只对不存在的表 AutoMigrate, 避免改动迁移定义的索引与约束 - 新增 scripts/prepare-test-db.sh:建库与通配授权,可重复执行 - 33 处 sqlite.Open 全部替换,26 个测试文件改用 MySQL - 删除 46 处手写 SQLite 方言 DDL(AUTOINCREMENT / INTEGER PRIMARY KEY / TEXT), 表统一由真实迁移建立 - go.mod 移除 gorm.io/driver/sqlite 与 mattn/go-sqlite3 - 删除生产代码里 distribution/repository.go 的 sqlite 方言分支(strftime) 对齐环境后暴露并修复的真实问题 - DATE(col) 在 MySQL 返回 DATE 类型,使 Date string 字段变成 RFC3339 时间串, 大盘日期会带出时间部分;28 处改为 DATE_FORMAT(col, '%Y-%m-%d') - 系统自动创建分销结算批次时 created_by 写入 0,违反指向 admin_users 的外键, 生产会直接插入失败;改为写 NULL(新增 adminRef helper) - MySQL DATETIME 仅到秒,静默截断 Go 侧写入的时间, 导致租用时长计算与结算时点回读比对偏差; rental_orders 的 9 个业务时间列提到 DATETIME(6) - 测试数据补齐严格模式要求的 NOT NULL 列、修正超出列长的取值、补齐外键父记录 迁移 - 000065 的 ALTER TABLE rental_orders 一并完成业务时间列精度调整, feature 侧不再单开迁移文件 脚本与文档 - check.sh / check-backend-coverage.sh 去掉 -p 1 串行与 SQLite 相关注释 - 更新 docs/Repository层测试补充总结.md 的测试运行说明
This commit is contained in:
@@ -91,49 +91,49 @@ type UpdateRuleStatusRequest struct {
|
||||
}
|
||||
|
||||
type DistributionOrderDTO struct {
|
||||
OrderID uint64 `json:"order_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
SiteID uint64 `json:"site_id"`
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
AccountID uint64 `json:"account_id"`
|
||||
OwnerID uint64 `json:"owner_id"`
|
||||
RenterID uint64 `json:"renter_id"`
|
||||
Status string `json:"status"`
|
||||
HandoffStatus string `json:"handoff_status"`
|
||||
RefundStatus string `json:"refund_status"`
|
||||
SettlementStatus string `json:"settlement_status"`
|
||||
DistributionMode string `json:"distribution_mode"`
|
||||
GrossPaidAmountCent int64 `json:"gross_paid_amount_cent"`
|
||||
RefundAmountCent int64 `json:"refund_amount_cent"`
|
||||
NetPaidAmountCent int64 `json:"net_paid_amount_cent"`
|
||||
PaymentFeeCent int64 `json:"payment_fee_cent"`
|
||||
ServiceFeeCent int64 `json:"service_fee_cent"`
|
||||
MarkupAmountCent int64 `json:"markup_amount_cent"`
|
||||
TaxAmountCent int64 `json:"tax_amount_cent"`
|
||||
SplitBaseAmountCent int64 `json:"split_base_amount_cent"`
|
||||
RoundingAdjustmentCent int64 `json:"rounding_adjustment_cent"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
OrderID uint64 `json:"order_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
SiteID uint64 `json:"site_id"`
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
AccountID uint64 `json:"account_id"`
|
||||
OwnerID uint64 `json:"owner_id"`
|
||||
RenterID uint64 `json:"renter_id"`
|
||||
Status string `json:"status"`
|
||||
HandoffStatus string `json:"handoff_status"`
|
||||
RefundStatus string `json:"refund_status"`
|
||||
SettlementStatus string `json:"settlement_status"`
|
||||
DistributionMode string `json:"distribution_mode"`
|
||||
GrossPaidAmountCent int64 `json:"gross_paid_amount_cent"`
|
||||
RefundAmountCent int64 `json:"refund_amount_cent"`
|
||||
NetPaidAmountCent int64 `json:"net_paid_amount_cent"`
|
||||
PaymentFeeCent int64 `json:"payment_fee_cent"`
|
||||
ServiceFeeCent int64 `json:"service_fee_cent"`
|
||||
MarkupAmountCent int64 `json:"markup_amount_cent"`
|
||||
TaxAmountCent int64 `json:"tax_amount_cent"`
|
||||
SplitBaseAmountCent int64 `json:"split_base_amount_cent"`
|
||||
RoundingAdjustmentCent int64 `json:"rounding_adjustment_cent"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
// 关联业务与分销商收益透传字段
|
||||
ListingNo string `json:"listing_no,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
GameName string `json:"game_name,omitempty"`
|
||||
ServerRegion string `json:"server_region,omitempty"`
|
||||
LoginPlatform string `json:"login_platform,omitempty"`
|
||||
RentDurationHours int `json:"rent_duration_hours,omitempty"`
|
||||
RentedAt *time.Time `json:"rented_at,omitempty"`
|
||||
RenterPhone string `json:"renter_phone,omitempty"`
|
||||
RenterNickname string `json:"renter_nickname,omitempty"`
|
||||
OwnerRentAmountCent int64 `json:"owner_rent_amount_cent,omitempty"`
|
||||
BasePriceCent int64 `json:"base_price_cent,omitempty"`
|
||||
ShelfMarkupCent int64 `json:"shelf_markup_cent,omitempty"`
|
||||
DepositAmountCent int64 `json:"deposit_amount_cent,omitempty"`
|
||||
ListingNo string `json:"listing_no,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
GameName string `json:"game_name,omitempty"`
|
||||
ServerRegion string `json:"server_region,omitempty"`
|
||||
LoginPlatform string `json:"login_platform,omitempty"`
|
||||
RentDurationHours int `json:"rent_duration_hours,omitempty"`
|
||||
RentedAt *time.Time `json:"rented_at,omitempty"`
|
||||
RenterPhone string `json:"renter_phone,omitempty"`
|
||||
RenterNickname string `json:"renter_nickname,omitempty"`
|
||||
OwnerRentAmountCent int64 `json:"owner_rent_amount_cent,omitempty"`
|
||||
BasePriceCent int64 `json:"base_price_cent,omitempty"`
|
||||
ShelfMarkupCent int64 `json:"shelf_markup_cent,omitempty"`
|
||||
DepositAmountCent int64 `json:"deposit_amount_cent,omitempty"`
|
||||
|
||||
// 当前分销商在该订单中的收益拆解
|
||||
DistributorEarningCent int64 `json:"distributor_earning_cent"`
|
||||
DistributorRole string `json:"distributor_role,omitempty"`
|
||||
DistributorMarkupCent int64 `json:"distributor_markup_cent"`
|
||||
DistributorSplitCent int64 `json:"distributor_split_cent"`
|
||||
DistributorEarningCent int64 `json:"distributor_earning_cent"`
|
||||
DistributorRole string `json:"distributor_role,omitempty"`
|
||||
DistributorMarkupCent int64 `json:"distributor_markup_cent"`
|
||||
DistributorSplitCent int64 `json:"distributor_split_cent"`
|
||||
}
|
||||
|
||||
type DistributionOrderListQuery struct {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -402,7 +403,7 @@ func TestSnapshotPaidOrderTxSplitsPercentOfProfit(t *testing.T) {
|
||||
|
||||
func TestApplyRefundTxWithCheckoutAndDeposit(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
if err := db.AutoMigrate(&model.OrderCheckout{}); err != nil {
|
||||
if err := database.AutoMigrateIfMissing(db, &model.OrderCheckout{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now()
|
||||
@@ -471,4 +472,3 @@ func TestApplyRefundTxWithCheckoutAndDeposit(t *testing.T) {
|
||||
t.Fatalf("distributorParty.IncomeAmountCent = %d, want 2420", distributorParty.IncomeAmountCent)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -145,6 +145,17 @@ func (r *Repository) ScopeSiteID(ctx context.Context, adminID, requested uint64)
|
||||
|
||||
// ensureSiteAccess 校验管理员可访问指定站点。
|
||||
// 仅超级管理员或持有 distribution:all_view 的账号可跨站;无成员记录不再视为超管。
|
||||
// adminRef 把 adminID=0(代表系统自动操作)映射为 NULL。
|
||||
//
|
||||
// 分销规则与结算批次的 created_by 都带指向 admin_users 的外键,
|
||||
// 直接写 0 会因找不到对应管理员而违反外键约束;NULL 才是"无具体操作人"的正确表示。
|
||||
func adminRef(adminID uint64) *uint64 {
|
||||
if adminID == 0 {
|
||||
return nil
|
||||
}
|
||||
return &adminID
|
||||
}
|
||||
|
||||
func (r *Repository) ensureSiteAccess(ctx context.Context, adminID, siteID uint64) error {
|
||||
return r.ensureSiteAccessWithDB(ctx, r.db, adminID, siteID)
|
||||
}
|
||||
@@ -345,7 +356,7 @@ func (r *Repository) CreateRule(ctx context.Context, adminID uint64, req CreateR
|
||||
DistributorARatio: parsed.DistributorARatio, DistributorBRatio: parsed.DistributorBRatio,
|
||||
ServiceFeeValue: parsed.ServiceFeeValue, ServiceFeeUnit: parsed.ServiceFeeUnit,
|
||||
PaymentFeeBPS: req.PaymentFeeBPS, TaxEnabled: req.TaxEnabled, TaxRateBPS: req.TaxRateBPS,
|
||||
EffectiveFrom: effectiveFrom, CreatedBy: &adminID,
|
||||
EffectiveFrom: effectiveFrom, CreatedBy: adminRef(adminID),
|
||||
}
|
||||
if row.PaymentFeeBPS == 0 {
|
||||
row.PaymentFeeBPS = 50
|
||||
@@ -911,7 +922,7 @@ func (r *Repository) CreateSettlementBatch(ctx context.Context, adminID uint64,
|
||||
}
|
||||
var batch model.DistributionSettlementBatch
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
batch = model.DistributionSettlementBatch{SiteID: req.SiteID, BatchNo: "DS" + time.Now().Format("20060102150405.000000000"), PeriodStart: req.PeriodStart, PeriodEnd: req.PeriodEnd, Status: "draft", CreatedBy: &adminID}
|
||||
batch = model.DistributionSettlementBatch{SiteID: req.SiteID, BatchNo: "DS" + time.Now().Format("20060102150405.000000000"), PeriodStart: req.PeriodStart, PeriodEnd: req.PeriodEnd, Status: "draft", CreatedBy: adminRef(adminID)}
|
||||
if err := tx.Create(&batch).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2114,10 +2125,6 @@ func (r *Repository) GetDashboardAnalytics(ctx context.Context, adminID, siteID
|
||||
startDate := time.Now().AddDate(0, 0, -6).Format("2006-01-02")
|
||||
dateFormatExpr := "DATE_FORMAT(ro.created_at, '%Y-%m-%d')"
|
||||
dateFormatPartyExpr := "DATE_FORMAT(created_at, '%Y-%m-%d')"
|
||||
if r.db != nil && r.db.Dialector != nil && r.db.Dialector.Name() == "sqlite" {
|
||||
dateFormatExpr = "strftime('%Y-%m-%d', ro.created_at)"
|
||||
dateFormatPartyExpr = "strftime('%Y-%m-%d', created_at)"
|
||||
}
|
||||
selectTrendSQL := fmt.Sprintf("%s AS date_str, COUNT(ro.id) AS orders, COALESCE(SUM(f.gross_paid_amount_cent), 0) AS gmv", dateFormatExpr)
|
||||
_ = r.db.WithContext(ctx).Table("rental_orders ro").
|
||||
Joins("JOIN distribution_order_financials f ON f.order_id = ro.id").
|
||||
|
||||
@@ -5,19 +5,16 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func distributionTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.AdminUser{}, &model.Role{}, &model.Permission{}, &model.AdminUserRole{}, &model.RolePermission{},
|
||||
&model.ChatConversation{}, &model.RentalOrder{},
|
||||
&model.AuditLog{}, &model.PaymentMerchantConfig{}, &model.DistributionSite{},
|
||||
@@ -29,6 +26,16 @@ func distributionTestDB(t *testing.T) *gorm.DB {
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 000065 迁移为分销表加了指向 admin_users 的外键,
|
||||
// 测试数据引用的管理员必须先落库才能通过约束校验。
|
||||
if err := db.Create(&model.AdminUser{
|
||||
ID: 7,
|
||||
Username: "distribution_test_admin",
|
||||
Nickname: "分销测试管理员",
|
||||
Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
@@ -948,7 +955,24 @@ func TestLiveMoneyMovementFrozenInProduction(t *testing.T) {
|
||||
if err := db.Create(&batch).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.DistributionSettlementItem{BatchID: batch.ID, OrderID: 1, PartyID: 1, AmountCent: 100, Status: "pending"}).Error; err != nil {
|
||||
// 结算明细的 order_id / party_id 都带外键,必须先落库对应的订单与参与方。
|
||||
order := model.RentalOrder{
|
||||
OrderNo: "ORD-FROZEN", ListingID: 1, AccountID: 1, OwnerID: 1, RenterID: 1,
|
||||
Status: "completed", SettlementMode: "platform_managed",
|
||||
}
|
||||
if err := db.Create(&order).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
party := model.DistributionOrderParty{
|
||||
OrderID: order.ID, SiteID: site.ID, PartyRole: "distributor_receive",
|
||||
PartyType: "site", PartyID: site.ID, IncomeAmountCent: 100,
|
||||
}
|
||||
if err := db.Create(&party).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.DistributionSettlementItem{
|
||||
BatchID: batch.ID, OrderID: order.ID, PartyID: party.ID, AmountCent: 100, Status: "pending",
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := repo.MarkSettlementBatch(t.Context(), 0, batch.ID); err != ErrLiveMoneyMovementFrozen {
|
||||
|
||||
@@ -304,6 +304,3 @@ func (s *Service) GetDashboardAnalytics(ctx context.Context, adminID, siteID uin
|
||||
}
|
||||
return s.repo.GetDashboardAnalytics(ctx, adminID, siteID)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user