62 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			62 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package task_test
 | ||
| 
 | ||
| import (
 | ||
| 	"fmt"
 | ||
| 	"testing"
 | ||
| 	"time"
 | ||
| 
 | ||
| 	"git.huangwc.com/pig/pig-farm-controller/internal/app/service/task"
 | ||
| )
 | ||
| 
 | ||
| func TestNewDelayTask(t *testing.T) {
 | ||
| 	id := "test-delay-task-1"
 | ||
| 	duration := 100 * time.Millisecond
 | ||
| 	priority := 1
 | ||
| 
 | ||
| 	dt := task.NewDelayTask(id, duration, priority)
 | ||
| 
 | ||
| 	if dt.GetID() != id {
 | ||
| 		t.Errorf("期望任务ID为 %s, 实际为 %s", id, dt.GetID())
 | ||
| 	}
 | ||
| 	if dt.GetPriority() != priority {
 | ||
| 		t.Errorf("期望任务优先级为 %d, 实际为 %d", priority, dt.GetPriority())
 | ||
| 	}
 | ||
| 	if dt.IsDone() != false {
 | ||
| 		t.Error("任务初始状态不应为已完成")
 | ||
| 	}
 | ||
| 	// 动态生成的描述,需要匹配 GetDescription 的实现
 | ||
| 	expectedDesc := fmt.Sprintf("延迟任务,ID: %s,延迟时间: %s", id, duration)
 | ||
| 	if dt.GetDescription() != expectedDesc {
 | ||
| 		t.Errorf("期望任务描述为 %s, 实际为 %s", expectedDesc, dt.GetDescription())
 | ||
| 	}
 | ||
| }
 | ||
| 
 | ||
| func TestDelayTaskExecute(t *testing.T) {
 | ||
| 	id := "test-delay-task-execute"
 | ||
| 	duration := 50 * time.Millisecond // 使用较短的延迟以加快测试速度
 | ||
| 	priority := 1
 | ||
| 
 | ||
| 	dt := task.NewDelayTask(id, duration, priority)
 | ||
| 
 | ||
| 	if dt.IsDone() {
 | ||
| 		t.Error("任务执行前不应为已完成状态")
 | ||
| 	}
 | ||
| 
 | ||
| 	startTime := time.Now()
 | ||
| 	err := dt.Execute()
 | ||
| 	endTime := time.Now()
 | ||
| 
 | ||
| 	if err != nil {
 | ||
| 		t.Errorf("Execute 方法返回错误: %v", err)
 | ||
| 	}
 | ||
| 	if !dt.IsDone() {
 | ||
| 		t.Error("任务执行后应为已完成状态")
 | ||
| 	}
 | ||
| 
 | ||
| 	// 验证延迟时间大致正确,允许一些误差
 | ||
| 	elapsed := endTime.Sub(startTime)
 | ||
| 	if elapsed < duration || elapsed > duration*2 {
 | ||
| 		t.Errorf("期望执行时间在 %v 左右, 但实际耗时 %v", duration, elapsed)
 | ||
| 	}
 | ||
| }
 |