package cron import ( "context" "testing" "time" ) func TestCronLogic_AddJob(t *testing.T) { ctx := context.Background() logic := New() // 测试添加任务 err := logic.AddJob(ctx, "test_job", "* * * * *", func() { t.Log("Test job executed") }) if err != nil { t.Errorf("Failed to add job: %v", err) } // 测试重复添加同名任务 err = logic.AddJob(ctx, "test_job", "* * * * *", func() { t.Log("Test job executed again") }) if err == nil { t.Error("Expected error when adding duplicate job name") } // 清理 logic.RemoveJob(ctx, "test_job") } func TestCronLogic_GetJobStatus(t *testing.T) { ctx := context.Background() logic := New() // 添加任务 err := logic.AddJob(ctx, "status_test_job", "* * * * *", func() { t.Log("Status test job executed") }) if err != nil { t.Fatalf("Failed to add job: %v", err) } // 测试获取任务状态 status, err := logic.GetJobStatus(ctx, "status_test_job") if err != nil { t.Errorf("Failed to get job status: %v", err) } if !status { t.Error("Expected job to be active") } // 测试获取不存在的任务状态 status, err = logic.GetJobStatus(ctx, "non_existent_job") if err != nil { t.Errorf("Failed to get non-existent job status: %v", err) } if status { t.Error("Expected non-existent job to be inactive") } // 清理 logic.RemoveJob(ctx, "status_test_job") } func TestCronLogic_RemoveJob(t *testing.T) { ctx := context.Background() logic := New() // 添加任务 err := logic.AddJob(ctx, "remove_test_job", "* * * * *", func() { t.Log("Remove test job executed") }) if err != nil { t.Fatalf("Failed to add job: %v", err) } // 测试移除任务 err = logic.RemoveJob(ctx, "remove_test_job") if err != nil { t.Errorf("Failed to remove job: %v", err) } // 测试移除不存在的任务 err = logic.RemoveJob(ctx, "non_existent_job") if err == nil { t.Error("Expected error when removing non-existent job") } } func TestCronLogic_StartStopJobs(t *testing.T) { ctx := context.Background() logic := New() // 启动任务 err := logic.StartAllJobs(ctx) if err != nil { t.Errorf("Failed to start jobs: %v", err) } // 等待一段时间让任务执行 time.Sleep(2 * time.Second) // 停止任务 err = logic.StopAllJobs(ctx) if err != nil { t.Errorf("Failed to stop jobs: %v", err) } }