| 1 | package timeperiod |
| 2 | |
| 3 | import ( |
| 4 | "testing" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | func TestCompileAndAllows(t *testing.T) { |
| 9 | cfgs := EnsureDefault([]Config{}) |
| 10 | set, err := Compile(cfgs) |
| 11 | if err != nil { |
| 12 | t.Fatalf("compile: %v", err) |
| 13 | } |
| 14 | per, err := set.Resolve(DefaultPeriodName) |
| 15 | if err != nil { |
| 16 | t.Fatalf("resolve: %v", err) |
| 17 | } |
| 18 | if !per.Allows(time.Now()) { |
| 19 | t.Fatalf("default period should allow now") |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | func TestWeeklyRule(t *testing.T) { |
| 24 | cfgs := []Config{ |
| 25 | { |
| 26 | Name: "work", |
| 27 | Rules: []RuleConfig{{Type: "weekly", Days: []string{"monday"}, Ranges: []string{"09:00-17:00"}}}, |
| 28 | }, |
| 29 | } |
| 30 | set, err := Compile(cfgs) |
| 31 | if err != nil { |
| 32 | t.Fatalf("compile: %v", err) |
| 33 | } |
| 34 | per, _ := set.Resolve("work") |
| 35 | mon := time.Date(2025, time.January, 6, 10, 0, 0, 0, time.UTC) // Monday |
| 36 | if !per.Allows(mon) { |
| 37 | t.Fatalf("expected monday 10:00 to be allowed") |
| 38 | } |
| 39 | sun := time.Date(2025, time.January, 5, 10, 0, 0, 0, time.UTC) |
| 40 | if per.Allows(sun) { |
| 41 | t.Fatalf("expected sunday to be disallowed") |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | func TestExcludeCycles(t *testing.T) { |
| 46 | cfgs := []Config{ |
| 47 | { |
| 48 | Name: "self", |
| 49 | Rules: []RuleConfig{{Type: "weekly", Ranges: []string{"00:00-24:00"}}}, |
| 50 | Exclude: []string{"self"}, |
| 51 | }, |
| 52 | { |
| 53 | Name: "a", |
| 54 | Rules: []RuleConfig{{Type: "weekly", Ranges: []string{"00:00-24:00"}}}, |
| 55 | Exclude: []string{"b"}, |
| 56 | }, |
| 57 | { |
| 58 | Name: "b", |
| 59 | Rules: []RuleConfig{{Type: "weekly", Ranges: []string{"00:00-24:00"}}}, |
| 60 | Exclude: []string{"a"}, |
| 61 | }, |
| 62 | } |
| 63 | set, err := Compile(cfgs) |
| 64 | if err != nil { |
| 65 | t.Fatalf("compile: %v", err) |
| 66 | } |
| 67 | self, _ := set.Resolve("self") |
| 68 | if !self.Allows(time.Now()) { |
| 69 | t.Fatalf("self-excluding period should still evaluate without errors") |
| 70 | } |
| 71 | a, _ := set.Resolve("a") |
| 72 | if a.Allows(time.Now()) { |
| 73 | t.Fatalf("mutually excluding periods should not allow any time") |
| 74 | } |
| 75 | } |