实现UpdatePlan单测

This commit is contained in:
2025-09-13 17:38:02 +08:00
parent 2228d8e879
commit 5e8ed88832
2 changed files with 408 additions and 3 deletions

View File

@@ -1,12 +1,20 @@
package repository
import (
"errors"
"fmt"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
"gorm.io/gorm"
)
// 定义仓库层可导出的公共错误
var (
ErrUpdateWithInvalidRoot = errors.New("更新操作的目标根计划无效或ID为0")
ErrNewSubPlanInUpdate = errors.New("计划树中包含一个ID为0的新子计划更新操作只允许关联已存在的计划")
ErrNodeDoesNotExist = errors.New("计划树中包含一个或多个在数据库中不存在的计划")
)
// PlanRepository 定义了与计划模型相关的数据库操作接口
// 这是为了让业务逻辑层依赖于抽象,而不是具体的数据库实现
type PlanRepository interface {
@@ -118,7 +126,7 @@ func (r *gormPlanRepository) updatePlanTx(tx *gorm.DB, plan *models.Plan) error
func (r *gormPlanRepository) validatePlanTree(tx *gorm.DB, plan *models.Plan) error {
// 1. 检查根节点
if plan == nil || plan.ID == 0 {
return fmt.Errorf("更新操作的目标计划无效或ID为0")
return ErrUpdateWithInvalidRoot
}
if len(plan.Tasks) > 0 && len(plan.SubPlans) > 0 {
return fmt.Errorf("计划 (ID: %d) 不能同时包含任务和子计划", plan.ID)
@@ -143,7 +151,7 @@ func (r *gormPlanRepository) validatePlanTree(tx *gorm.DB, plan *models.Plan) er
return fmt.Errorf("检查计划存在性时出错: %w", err)
}
if int(count) != len(idsToCheck) {
return fmt.Errorf("计划树中包含一个或多个在数据库中不存在的计划")
return ErrNodeDoesNotExist
}
}
@@ -156,7 +164,7 @@ func validateNodeAndDetectCycles(plan *models.Plan, allIDs, recursionStack map[u
return nil
}
if plan.ID == 0 {
return fmt.Errorf("错误计划树中包含一个ID为0的新计划更新操作只允许操作已存在的计划")
return ErrNewSubPlanInUpdate
}
if recursionStack[plan.ID] {
return fmt.Errorf("检测到循环引用:计划 (ID: %d) 是其自身的祖先", plan.ID)