Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX OS Automation9// File : Packages/ORIXScheduler/Tests/ORIXSchedulerTests/CronExpressionTests.swift10// Description : Unit tests for cron parsing, day matching, calendar edge11// cases, daylight-saving behaviour in America/Toronto and12// Europe/Paris, and a monotonicity property test.13// Module : ORIXSchedulerTests14// Repository : https://git.spboucher.ai/orix-automation15// Created : 2026-11-2116// Last Modified : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : Proprietary, all rights reserved (see license file)83// License File : LICENSE84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import Testing93@testable import ORIXScheduler9495/// Parses `2026-03-08T07:00:00Z`.96func utc(_ text: String) -> Date {97 let f = ISO8601DateFormatter()98 f.formatOptions = [.withInternetDateTime]99 guard let d = f.date(from: text) else { fatalError("bad test date \(text)") }100 return d101}102103let utcZone = TimeZone(identifier: "UTC")!104let toronto = TimeZone(identifier: "America/Toronto")!105let paris = TimeZone(identifier: "Europe/Paris")!106107/// Deterministic generator for the property tests.108struct SplitMix64: RandomNumberGenerator {109 var state: UInt64110 mutating func next() -> UInt64 {111 state &+= 0x9E37_79B9_7F4A_7C15112 var z = state113 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9114 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB115 return z ^ (z >> 31)116 }117}118119@Suite("Cron parsing (unit)")120struct CronParsingTests {121 @Test(arguments: [122 ("", "empty"),123 ("* * * *", "expected 5 fields"),124 ("* * * * * *", "expected 5 fields"),125 ("60 * * * *", "minute: value 60 is out of range 0-59"),126 ("* 24 * * *", "hour: value 24 is out of range 0-23"),127 ("* * 0 * *", "day-of-month: value 0 is out of range 1-31"),128 ("* * 32 * *", "day-of-month: value 32 is out of range 1-31"),129 ("* * * 13 *", "month: value 13 is out of range 1-12"),130 ("* * * * 8", "day-of-week: value 8 is out of range 0-7"),131 ("*/0 * * * *", "step must be greater than 0"),132 ("*/61 * * * *", "exceeds the field range"),133 ("*/x * * * *", "is not a positive integer"),134 ("5-1 * * * *", "range start 5 is greater than range end 1"),135 ("1,,2 * * * *", "empty list element"),136 ("1/2/3 * * * *", "more than one '/'"),137 ("a * * * *", "minute: 'a' is not a valid value"),138 ("-5 * * * *", "malformed range"),139 ("* * * FOO *", "month: 'FOO' is not a valid value"),140 ("* * * * MONDAY", "day-of-week: 'MONDAY' is not a valid value"),141 ("* * ? * *", "day-of-month: '?' is not a valid value"),142 ("* * L * *", "day-of-month: 'L' is not a valid value"),143 ("@reboot", "unknown macro '@reboot'"),144 ("@every 5m", "unknown macro"),145 ])146 func rejectsInvalidInputWithAPreciseMessage(_ c: (String, String)) {147 do {148 _ = try CronExpression(c.0)149 Issue.record("'\(c.0)' should have been rejected")150 } catch let error as CronParseError {151 #expect(error.description.contains(c.1), "message for '\(c.0)' was: \(error.description)")152 #expect(error.errorDescription == error.description)153 } catch {154 Issue.record("unexpected error type \(error)")155 }156 }157158 private func minutes(_ expr: String) throws -> [Int] {159 let cron = try CronExpression(expr)160 return cron.fireDates(between: utc("2026-01-01T00:00:00Z").addingTimeInterval(-1), and: utc("2026-01-01T00:59:59Z"), in: utcZone)161 .map { Int($0.timeIntervalSince(utc("2026-01-01T00:00:00Z"))) / 60 }162 }163164 @Test func listsRangesAndSteps() throws {165 #expect(try minutes("*/15 * * * *") == [0, 15, 30, 45])166 #expect(try minutes("1,15,59 * * * *") == [1, 15, 59])167 #expect(try minutes("10-13 * * * *") == [10, 11, 12, 13])168 #expect(try minutes("10-40/10 * * * *") == [10, 20, 30, 40])169 #expect(try minutes("5/20 * * * *") == [5, 25, 45])170 #expect(try minutes("0-5,50-59/3,30 * * * *") == [0, 1, 2, 3, 4, 5, 30, 50, 53, 56, 59])171 #expect(try minutes("7 * * * *") == [7])172 }173174 @Test func namesAreCaseInsensitiveAndEquivalentToNumbers() throws {175 let named = try CronExpression("0 9 * jan-MAR Mon-Fri")176 let numeric = try CronExpression("0 9 * 1-3 1-5")177 let start = utc("2026-01-01T00:00:00Z"), end = utc("2026-12-31T00:00:00Z")178 let a = named.fireDates(between: start, and: end, in: toronto, limit: 500)179 #expect(a == numeric.fireDates(between: start, and: end, in: toronto, limit: 500))180 #expect(a.count == 64) // weekdays in January–March 2026: 22 + 20 + 22181 #expect(named.months == numeric.months && named.daysOfWeek == numeric.daysOfWeek)182 }183184 @Test func sundayIsZeroAndSeven() throws {185 let zero = try CronExpression("0 0 * * 0"), seven = try CronExpression("0 0 * * 7"), name = try CronExpression("0 0 * * SUN")186 #expect(zero.daysOfWeek == seven.daysOfWeek && zero.daysOfWeek == name.daysOfWeek)187 // 4 January 2026 is a Sunday.188 #expect(zero.nextFireDate(after: utc("2026-01-01T00:00:00Z"), in: utcZone) == utc("2026-01-04T00:00:00Z"))189 let weekend = try CronExpression("0 0 * * 6-7")190 #expect(weekend.fireDates(between: utc("2026-01-01T00:00:00Z"), and: utc("2026-01-12T00:00:00Z"), in: utcZone)191 == [utc("2026-01-03T00:00:00Z"), utc("2026-01-04T00:00:00Z"), utc("2026-01-10T00:00:00Z"), utc("2026-01-11T00:00:00Z")])192 }193194 @Test func macros() throws {195 let cases = ["@hourly": "0 * * * *", "@daily": "0 0 * * *", "@midnight": "0 0 * * *", "@weekly": "0 0 * * 0",196 "@monthly": "0 0 1 * *", "@yearly": "0 0 1 1 *", "@ANNUALLY": "0 0 1 1 *"]197 let start = utc("2026-01-01T00:00:00Z"), end = utc("2028-01-01T00:00:00Z")198 for (macro, expansion) in cases {199 let a = try CronExpression(macro).fireDates(between: start, and: end, in: paris, limit: 50)200 let b = try CronExpression(expansion).fireDates(between: start, and: end, in: paris, limit: 50)201 #expect(a == b && !a.isEmpty, "\(macro)")202 }203 }204205 @Test func codableRoundTripsAsAString() throws {206 let cron = try CronExpression(" */5 9-17 * * MON-FRI ")207 #expect(cron.source == "*/5 9-17 * * MON-FRI" && cron.description == cron.source)208 let data = try JSONEncoder().encode([cron])209 #expect(String(decoding: data, as: UTF8.self) == #"["*\/5 9-17 * * MON-FRI"]"#)210 #expect(try JSONDecoder().decode([CronExpression].self, from: data) == [cron])211 #expect(throws: DecodingError.self) { try JSONDecoder().decode([CronExpression].self, from: Data(#"["61 * * * *"]"#.utf8)) }212 }213}214215@Suite("Cron calendar rules (unit)")216struct CronCalendarTests {217 @Test func dayOfMonthAndDayOfWeekAreOredWhenBothRestricted() throws {218 // 1 January 2026 is a Thursday: Fridays are 2, 9, 16…; the 13th is a Tuesday.219 let cron = try CronExpression("0 0 13 * FRI")220 let dates = cron.fireDates(between: utc("2026-01-01T00:00:00Z"), and: utc("2026-01-17T00:00:00Z"), in: utcZone)221 #expect(dates == ["2026-01-02", "2026-01-09", "2026-01-13", "2026-01-16"].map { utc($0 + "T00:00:00Z") })222 }223224 @Test func aWildcardDayFieldMeansBothMustMatch() throws {225 let onlyFridays = try CronExpression("0 0 * * FRI")226 #expect(onlyFridays.fireDates(between: utc("2026-01-01T00:00:00Z"), and: utc("2026-01-17T00:00:00Z"), in: utcZone)227 == ["2026-01-02", "2026-01-09", "2026-01-16"].map { utc($0 + "T00:00:00Z") })228 let only13th = try CronExpression("0 0 13 * *")229 #expect(only13th.nextFireDate(after: utc("2026-01-01T00:00:00Z"), in: utcZone) == utc("2026-01-13T00:00:00Z"))230 // `*/2` starts with a star: odd days that are also Fridays.231 let oddFridays = try CronExpression("0 0 */2 * FRI")232 #expect(oddFridays.fireDates(between: utc("2026-01-01T00:00:00Z"), and: utc("2026-01-31T00:00:00Z"), in: utcZone)233 == ["2026-01-09", "2026-01-23"].map { utc($0 + "T00:00:00Z") })234 }235236 @Test func february29OnlyFiresInLeapYears() throws {237 let cron = try CronExpression("0 0 29 2 *")238 let first = cron.nextFireDate(after: utc("2026-01-01T00:00:00Z"), in: utcZone)239 #expect(first == utc("2028-02-29T00:00:00Z"))240 #expect(cron.nextFireDate(after: first!, in: utcZone) == utc("2032-02-29T00:00:00Z"))241 // 2100 is not a leap year: the gap is eight years.242 #expect(cron.nextFireDate(after: utc("2096-03-01T00:00:00Z"), in: utcZone) == utc("2104-02-29T00:00:00Z"))243 }244245 @Test func impossibleDatesNeverFire() throws {246 #expect(try CronExpression("0 0 30 2 *").nextFireDate(after: utc("2026-01-01T00:00:00Z"), in: utcZone) == nil)247 #expect(try CronExpression("0 0 31 4,6,9,11 *").nextFireDate(after: utc("2026-01-01T00:00:00Z"), in: toronto) == nil)248 #expect(try CronExpression("0 0 31 4 *").fireDates(between: utc("2026-01-01T00:00:00Z"), and: utc("2030-01-01T00:00:00Z"), in: utcZone).isEmpty)249 }250251 @Test func the31stSkipsShortMonths() throws {252 let cron = try CronExpression("0 0 31 * *")253 let dates = cron.fireDates(between: utc("2026-01-31T00:00:00Z"), and: utc("2026-12-31T23:00:00Z"), in: utcZone)254 #expect(dates == ["2026-03-31", "2026-05-31", "2026-07-31", "2026-08-31", "2026-10-31", "2026-12-31"].map { utc($0 + "T00:00:00Z") })255 // Last days of February and the year boundary.256 let daily = try CronExpression("59 23 * * *")257 #expect(daily.nextFireDate(after: utc("2026-02-28T23:59:00Z"), in: utcZone) == utc("2026-03-01T23:59:00Z"))258 #expect(daily.nextFireDate(after: utc("2028-02-28T23:59:00Z"), in: utcZone) == utc("2028-02-29T23:59:00Z"))259 #expect(daily.nextFireDate(after: utc("2026-12-31T23:59:00Z"), in: utcZone) == utc("2027-01-01T23:59:00Z"))260 }261262 @Test func nextIsStrictlyAfterAndHonoursSubSecondInput() throws {263 let cron = try CronExpression("0 9 * * *")264 let nine = utc("2026-06-01T09:00:00Z")265 #expect(cron.nextFireDate(after: nine.addingTimeInterval(-0.5), in: utcZone) == nine)266 #expect(cron.nextFireDate(after: nine, in: utcZone) == utc("2026-06-02T09:00:00Z"))267 #expect(cron.nextFireDate(after: nine.addingTimeInterval(0.5), in: utcZone) == utc("2026-06-02T09:00:00Z"))268 #expect(cron.fires(at: nine, in: utcZone) && !cron.fires(at: nine.addingTimeInterval(60), in: utcZone))269 }270271 @Test func fireDatesHonoursBoundsAndLimit() throws {272 let cron = try CronExpression("* * * * *")273 let start = utc("2026-06-01T00:00:00Z")274 #expect(cron.fireDates(between: start, and: start.addingTimeInterval(600), in: utcZone).count == 10)275 #expect(cron.fireDates(between: start, and: start.addingTimeInterval(600), in: utcZone, limit: 3)276 == [60, 120, 180].map { start.addingTimeInterval($0) })277 #expect(cron.fireDates(between: start, and: start, in: utcZone).isEmpty)278 }279280 @Test func civilDateArithmeticMatchesFoundation() {281 var calendar = Calendar(identifier: .gregorian)282 calendar.timeZone = utcZone283 var rng = SplitMix64(state: 42)284 for _ in 0..<2000 {285 let days = Int.random(in: -100_000...200_000, using: &rng)286 let date = Date(timeIntervalSince1970: TimeInterval(days) * 86_400)287 let c = calendar.dateComponents([.year, .month, .day, .weekday], from: date)288 let (y, m, d) = CivilDate.civil(fromDays: days)289 #expect(y == c.year && m == c.month && d == c.day)290 #expect(CivilDate.weekday(ofDays: days) == c.weekday! - 1)291 #expect(CivilDate.days(year: y, month: m, day: d) == days)292 }293 }294}295296@Suite("Cron daylight saving, America/Toronto and Europe/Paris (unit)")297struct CronDSTTests {298 /// (zone, day before the change at noon UTC, expected firing on the change day, expected firing the day after).299 static let springForward: [(String, String, String, String)] = [300 // Toronto: 02:00 EST → 03:00 EDT at 07:00Z. 02:30 does not exist; fire at 03:00 EDT.301 ("America/Toronto", "2026-03-07T12:00:00Z", "2026-03-08T07:00:00Z", "2026-03-09T06:30:00Z"),302 ("America/Toronto", "2027-03-13T12:00:00Z", "2027-03-14T07:00:00Z", "2027-03-15T06:30:00Z"),303 // Paris: 02:00 CET → 03:00 CEST at 01:00Z.304 ("Europe/Paris", "2026-03-28T12:00:00Z", "2026-03-29T01:00:00Z", "2026-03-30T00:30:00Z"),305 ("Europe/Paris", "2027-03-27T12:00:00Z", "2027-03-28T01:00:00Z", "2027-03-29T00:30:00Z"),306 ]307308 @Test(arguments: springForward)309 func aSkippedLocalTimeFiresOnceAtTheFirstValidInstantAfterTheGap(_ c: (String, String, String, String)) throws {310 let zone = TimeZone(identifier: c.0)!311 let cron = try CronExpression("30 2 * * *")312 let onChangeDay = cron.nextFireDate(after: utc(c.1), in: zone)313 #expect(onChangeDay == utc(c.2))314 #expect(cron.nextFireDate(after: utc(c.2), in: zone) == utc(c.3))315 // Exactly one firing on the change day.316 #expect(cron.fireDates(between: utc(c.1), and: utc(c.3).addingTimeInterval(-1), in: zone) == [utc(c.2)])317 // The first valid instant is 03:00 local.318 var calendar = Calendar(identifier: .gregorian)319 calendar.timeZone = zone320 let local = calendar.dateComponents([.hour, .minute], from: utc(c.2))321 #expect(local.hour == 3 && local.minute == 0)322 }323324 @Test(arguments: springForward)325 func severalTimesInsideTheGapCollapseIntoOneFiring(_ c: (String, String, String, String)) throws {326 let zone = TimeZone(identifier: c.0)!327 let end = utc(c.2).addingTimeInterval(3 * 3600)328 for expr in ["0,15,30,45 2 * * *", "0 2,3 * * *", "0-59 2 * * *", "30 2 * * *"] {329 let dates = try CronExpression(expr).fireDates(between: utc(c.1), and: end, in: zone)330 #expect(dates.filter { $0 >= utc(c.2).addingTimeInterval(-3600) } == [utc(c.2)], "\(expr) in \(c.0)")331 }332 }333334 /// (zone, day before at noon UTC, first occurrence of the repeated time, same local time the day after, the second occurrence that must not fire).335 static let fallBack: [(String, String, String, String, String, String)] = [336 // Toronto: 02:00 EDT → 01:00 EST at 06:00Z; 01:30 happens at 05:30Z (EDT) and 06:30Z (EST).337 ("America/Toronto", "30 1 * * *", "2026-10-31T12:00:00Z", "2026-11-01T05:30:00Z", "2026-11-02T06:30:00Z", "2026-11-01T06:30:00Z"),338 ("America/Toronto", "30 1 * * *", "2027-11-06T12:00:00Z", "2027-11-07T05:30:00Z", "2027-11-08T06:30:00Z", "2027-11-07T06:30:00Z"),339 // Paris: 03:00 CEST → 02:00 CET at 01:00Z; 02:30 happens at 00:30Z (CEST) and 01:30Z (CET).340 ("Europe/Paris", "30 2 * * *", "2026-10-24T12:00:00Z", "2026-10-25T00:30:00Z", "2026-10-26T01:30:00Z", "2026-10-25T01:30:00Z"),341 ("Europe/Paris", "30 2 * * *", "2027-10-30T12:00:00Z", "2027-10-31T00:30:00Z", "2027-11-01T01:30:00Z", "2027-10-31T01:30:00Z"),342 ]343344 @Test(arguments: fallBack)345 func aRepeatedLocalTimeFiresOnceOnTheFirstOccurrence(_ c: (String, String, String, String, String, String)) throws {346 let zone = TimeZone(identifier: c.0)!347 let cron = try CronExpression(c.1)348 #expect(cron.nextFireDate(after: utc(c.2), in: zone) == utc(c.3))349 #expect(cron.nextFireDate(after: utc(c.3), in: zone) == utc(c.4))350 let dates = cron.fireDates(between: utc(c.2), and: utc(c.4), in: zone)351 #expect(dates == [utc(c.3), utc(c.4)])352 #expect(!dates.contains(utc(c.5)))353 #expect(!cron.fires(at: utc(c.5), in: zone))354 }355356 @Test(arguments: ["America/Toronto", "Europe/Paris"], [2026, 2027])357 func aDailyJobFiresExactlyOncePerLocalDayAllYear(_ zoneID: String, _ year: Int) throws {358 let zone = TimeZone(identifier: zoneID)!359 var calendar = Calendar(identifier: .gregorian)360 calendar.timeZone = zone361 let start = calendar.date(from: DateComponents(year: year, month: 1, day: 1))!362 let end = calendar.date(from: DateComponents(year: year + 1, month: 1, day: 1))!363 for expr in ["30 2 * * *", "30 1 * * *", "0 0 * * *", "59 23 * * *", "0 3 * * *"] {364 let dates = try CronExpression(expr).fireDates(between: start.addingTimeInterval(-1), and: end.addingTimeInterval(-1), in: zone, limit: 1000)365 #expect(dates.count == 365, "\(expr) \(zoneID) \(year): \(dates.count)")366 let days = Set(dates.map { calendar.dateComponents([.year, .month, .day], from: $0) })367 #expect(days.count == 365, "\(expr) \(zoneID) \(year): a day fired twice or was skipped")368 #expect(zip(dates, dates.dropFirst()).allSatisfy { $0 < $1 })369 }370 }371372 @Test func hourlyStyleJobsKeepTheirElapsedTimeRhythm() throws {373 let halfPast = try CronExpression("30 * * * *")374 // Toronto spring forward: 01:30 EST, then 03:30 EDT — one real hour apart, nothing invented at 03:00.375 #expect(halfPast.fireDates(between: utc("2026-03-08T06:00:00Z"), and: utc("2026-03-08T09:00:00Z"), in: toronto)376 == ["2026-03-08T06:30:00Z", "2026-03-08T07:30:00Z", "2026-03-08T08:30:00Z"].map(utc))377 // Toronto fall back: 01:30 runs on both passes, so the job never goes silent for two hours.378 #expect(halfPast.fireDates(between: utc("2026-11-01T05:00:00Z"), and: utc("2026-11-01T08:00:00Z"), in: toronto)379 == ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z", "2026-11-01T07:30:00Z"].map(utc))380 // Every five minutes: 12 firings per real hour through both Paris changes.381 let fiveMinutes = try CronExpression("*/5 * * * *")382 for window in [("2026-03-29T00:00:00Z", "2026-03-29T03:00:00Z"), ("2026-10-25T00:00:00Z", "2026-10-25T03:00:00Z")] {383 let dates = fiveMinutes.fireDates(between: utc(window.0), and: utc(window.1), in: paris)384 #expect(dates.count == 36)385 #expect(zip(dates, dates.dropFirst()).allSatisfy { $1.timeIntervalSince($0) == 300 })386 }387 }388389 @Test func localTimeResolutionClassifiesGapsAndOverlaps() {390 func local(_ y: Int, _ m: Int, _ d: Int, _ h: Int, _ min: Int) -> Int { CivilDate.days(year: y, month: m, day: d) * 86_400 + h * 3600 + min * 60 }391 #expect(LocalTime.resolve(local(2026, 3, 8, 2, 30), in: toronto) == .skipped(firstValidInstant: Int(utc("2026-03-08T07:00:00Z").timeIntervalSince1970)))392 #expect(LocalTime.resolve(local(2026, 3, 8, 3, 0), in: toronto) == .unique(Int(utc("2026-03-08T07:00:00Z").timeIntervalSince1970)))393 #expect(LocalTime.resolve(local(2026, 3, 8, 1, 59), in: toronto) == .unique(Int(utc("2026-03-08T06:59:00Z").timeIntervalSince1970)))394 #expect(LocalTime.resolve(local(2026, 11, 1, 1, 30), in: toronto)395 == .repeated(first: Int(utc("2026-11-01T05:30:00Z").timeIntervalSince1970), second: Int(utc("2026-11-01T06:30:00Z").timeIntervalSince1970)))396 #expect(LocalTime.resolve(local(2026, 11, 1, 2, 0), in: toronto) == .unique(Int(utc("2026-11-01T07:00:00Z").timeIntervalSince1970)))397 #expect(LocalTime.resolve(local(2026, 10, 25, 2, 59), in: paris)398 == .repeated(first: Int(utc("2026-10-25T00:59:00Z").timeIntervalSince1970), second: Int(utc("2026-10-25T01:59:00Z").timeIntervalSince1970)))399 #expect(LocalTime.resolve(local(2026, 7, 1, 12, 0), in: paris) == .unique(Int(utc("2026-07-01T10:00:00Z").timeIntervalSince1970)))400 }401}402403@Suite("Cron properties over random expressions (unit)")404struct CronPropertyTests {405 static func randomField(_ range: ClosedRange<Int>, _ rng: inout SplitMix64) -> String {406 switch Int.random(in: 0..<6, using: &rng) {407 case 0: return "*"408 case 1: return "*/\(Int.random(in: 1...max(1, (range.upperBound - range.lowerBound) / 2), using: &rng))"409 case 2:410 let a = Int.random(in: range, using: &rng), b = Int.random(in: range, using: &rng)411 return "\(min(a, b))-\(max(a, b))"412 case 3:413 return (0..<Int.random(in: 1...4, using: &rng)).map { _ in String(Int.random(in: range, using: &rng)) }.joined(separator: ",")414 case 4:415 let a = Int.random(in: range, using: &rng)416 return "\(a)/\(Int.random(in: 1...max(1, (range.upperBound - range.lowerBound) / 3), using: &rng))"417 default: return String(Int.random(in: range, using: &rng))418 }419 }420421 static func randomExpression(_ rng: inout SplitMix64) -> String {422 [randomField(0...59, &rng), randomField(0...23, &rng), randomField(1...31, &rng), randomField(1...12, &rng), randomField(0...7, &rng)]423 .joined(separator: " ")424 }425426 @Test func nextFireDatesAreStrictlyIncreasingStableAndMatchTheFields() throws {427 var rng = SplitMix64(state: 20_261_121)428 let zones = [utcZone, toronto, paris, TimeZone(identifier: "Australia/Lord_Howe")!, TimeZone(identifier: "Asia/Kathmandu")!]429 var checked = 0430 for i in 0..<300 {431 let text = Self.randomExpression(&rng)432 let cron = try CronExpression(text)433 let zone = zones[i % zones.count]434 // Start anywhere in 2026–2027, including the hours around the DST changes.435 var cursor = utc("2026-01-01T00:00:00Z").addingTimeInterval(Double(Int.random(in: 0..<(730 * 86_400), using: &rng)))436 var previous: Date?437 for _ in 0..<12 {438 guard let next = cron.nextFireDate(after: cursor, in: zone) else { break }439 #expect(next > cursor, "\(text): not strictly after")440 if let previous { #expect(next > previous, "\(text): not increasing") }441 // Stable: asking again from just before gives the same instant, and nothing lies in between.442 #expect(cron.nextFireDate(after: next.addingTimeInterval(-1), in: zone) == next, "\(text): unstable")443 #expect(cron.nextFireDate(after: cursor.addingTimeInterval((next.timeIntervalSince(cursor)) / 2), in: zone) == next, "\(text): a firing was missed")444 #expect(next.timeIntervalSince1970 == next.timeIntervalSince1970.rounded(), "\(text): not a whole second")445 if zone == utcZone {446 var calendar = Calendar(identifier: .gregorian)447 calendar.timeZone = zone448 let c = calendar.dateComponents([.minute, .hour, .day, .month, .weekday, .second], from: next)449 #expect(c.second == 0)450 #expect(cron.minutes & (1 << UInt64(c.minute!)) != 0 && cron.hours & (1 << UInt64(c.hour!)) != 0, "\(text)")451 #expect(cron.matchesDay(month: c.month!, day: c.day!, weekday: c.weekday! - 1), "\(text)")452 }453 previous = next454 cursor = next455 checked += 1456 }457 }458 #expect(checked > 2000)459 }460461 @Test func latestFireDateAgreesWithForwardEnumeration() throws {462 var rng = SplitMix64(state: 7)463 for _ in 0..<60 {464 let text = Self.randomExpression(&rng)465 let trigger = TriggerSpec.cron(expression: text, timezone: "America/Toronto")466 let lower = utc("2026-10-30T00:00:00Z").addingTimeInterval(Double(Int.random(in: 0..<86_400, using: &rng)))467 let upper = lower.addingTimeInterval(Double(Int.random(in: 60..<(2 * 86_400), using: &rng)))468 let forward = try CronExpression(text).fireDates(between: lower, and: upper, in: toronto, limit: 100_000)469 #expect(trigger.latestFireDate(after: lower, atOrBefore: upper, anchor: lower) == forward.last, "\(text)")470 }471 }472}473