Files
github-auto-sync-golang/cron_test.go
T

54 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"testing"
"time"
)
func TestParseCron(t *testing.T) {
for _, spec := range []string{"*/5 * * * *", "0 9 * * 1-5", "30 8 1,15 * *", "* * * * *", "0 */2 * * *", "0 8-18/2 * * 1-5"} {
if _, err := parseCron(spec); err != nil {
t.Errorf("parseCron(%q) 应当成功,却得到: %v", spec, err)
}
}
for _, spec := range []string{"* * * *", "61 * * * *", "* * * * 8", "a * * * *", "* * * * * *"} {
if _, err := parseCron(spec); err == nil {
t.Errorf("parseCron(%q) 应当失败", spec)
}
}
}
func TestCronNext(t *testing.T) {
// 每日 09:30:从当天 10:00 出发应得到次日 09:30
spec, _ := parseCron("30 9 * * *")
next := cronNext(spec, time.Date(2026, 9, 8, 10, 0, 0, 0, time.Local))
want := time.Date(2026, 9, 9, 9, 30, 0, 0, time.Local)
if !next.Equal(want) {
t.Fatalf("每日 09:30:期望 %v,得到 %v", want, next)
}
// 每 15 分钟
spec2, _ := parseCron("*/15 * * * *")
next2 := cronNext(spec2, time.Date(2026, 9, 8, 10, 7, 0, 0, time.Local))
want2 := time.Date(2026, 9, 8, 10, 15, 0, 0, time.Local)
if !next2.Equal(want2) {
t.Fatalf("*/15:期望 %v,得到 %v", want2, next2)
}
// 仅周五 12:00:2026-09-08 是周二,应得到 2026-09-11(周五)
spec3, _ := parseCron("0 12 * * 5")
next3 := cronNext(spec3, time.Date(2026, 9, 8, 12, 0, 0, 0, time.Local))
want3 := time.Date(2026, 9, 11, 12, 0, 0, 0, time.Local)
if !next3.Equal(want3) {
t.Fatalf("仅周五:期望 %v,得到 %v", want3, next3)
}
// 7 表示周日:2026-09-13 是周日
spec4, _ := parseCron("0 0 * * 7")
next4 := cronNext(spec4, time.Date(2026, 9, 12, 0, 0, 0, 0, time.Local)) // 周六
want4 := time.Date(2026, 9, 13, 0, 0, 0, 0, time.Local)
if !next4.Equal(want4) {
t.Fatalf("7=周日:期望 %v,得到 %v", want4, next4)
}
}