Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_datime/tests/zone_oracle.rs

18.2 KiB, 15 runs

created by r1870400018:63093, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! The zone rules checked against GNU date, which reads the host's own
2//! zoneinfo. Zones with and without daylight saving, a 30 minute shift
3//! (Lord Howe) and a +05:45 offset (Kathmandu) are taken across both of
4//! 2026's transitions and well past the end of a "fat" file's table, and "slim"
5//! files, which end their table and leave the rest to the footer, are made with
6//! the host's `zic` and run the same way.
7//!
8//! Where a wall time falls in a fold, GNU date picks one occurrence by the
9//! accident of its search, not always the earlier, so the check there is that
10//! both occurrences display as that wall time and GNU's choice is one of them.
11
12mod common;
13
14use common::*;
15
16use oxedyne_fe2o3_core::prelude::*;
17use oxedyne_fe2o3_datime::time::{
18 CalClockZone,
19 LocalTimeResult,
20 LocalTimeType,
21 TZifData,
22 TZifParser,
23};
24
25use std::{
26 fs,
27 path::{Path, PathBuf},
28 process::Command,
29};
30
31const ZONES: [&str; 5] = [
32 "America/New_York",
33 "Europe/London",
34 "Australia/Perth",
35 "Australia/Lord_Howe",
36 "Asia/Kathmandu",
37];
38
39// The embedded table's zones, which new_embedded answers without the host.
40const EMBEDDED: [&str; 3] = [
41 "America/New_York",
42 "Europe/London",
43 "Australia/Sydney",
44];
45
46// Offsets over a grid of UTC seconds, and at the second either side of every
47// change the zone reports. Returns how many changes there were.
48fn offsets_agree(
49 zone: &CalClockZone,
50 tz: &str,
51 tzdir: Option<&Path>,
52 from: i64,
53 to: i64,
54 step: i64,
55)
56 -> Outcome<usize>
57{
58 offsets_agree_tz(zone, Some(tz), tzdir, from, to, step)
59}
60
61// As `offsets_agree`, with TZ left unset for GNU date where `tz` is None.
62fn offsets_agree_tz(
63 zone: &CalClockZone,
64 tz: Option<&str>,
65 tzdir: Option<&Path>,
66 from: i64,
67 to: i64,
68 step: i64,
69)
70 -> Outcome<usize>
71{
72 let grid: Vec<i64> = (from..to).step_by(step as usize).collect();
73 let lines: Vec<String> = grid.iter().map(|t| fmt!("@{}", t)).collect();
74 let said = res!(date_batch_tz(tz, tzdir, &lines, "+%z"));
75 let mut prev: Option<(i64, i64)> = None;
76 let mut edges: Vec<(i64, i64, i64)> = Vec::new(); // first second under the new offset, old, new
77 for (i, t) in grid.iter().enumerate() {
78 let mine = res!(zone.offset_millis_at_time(t * 1000)) as i64 / 1000;
79 let theirs = z_secs(said[i].as_deref().unwrap_or("+0000"));
80 assert_eq!(mine, theirs, "TZ={:?} at UTC second {}", tz, t);
81 if let Some((pt, po)) = prev {
82 if po != mine {
83 // Bisect to the first second under the new offset.
84 let (mut lo, mut hi) = (pt, *t);
85 while hi - lo > 1 {
86 let mid = lo + (hi - lo) / 2;
87 if res!(zone.offset_millis_at_time(mid * 1000)) as i64 / 1000 == po {
88 lo = mid;
89 } else {
90 hi = mid;
91 }
92 }
93 edges.push((hi, po, mine));
94 }
95 }
96 prev = Some((*t, mine));
97 }
98 let around: Vec<String> = edges.iter().flat_map(|(t, _, _)| [fmt!("@{}", t - 1), fmt!("@{}", t)]).collect();
99 let said = res!(date_batch_tz(tz, tzdir, &around, "+%z"));
100 for (k, (t, old, new)) in edges.iter().enumerate() {
101 let before = z_secs(said[2 * k].as_deref().unwrap_or("+0000"));
102 let after = z_secs(said[2 * k + 1].as_deref().unwrap_or("+0000"));
103 assert_eq!(before, *old, "TZ={:?} one second before the change at {}", tz, t);
104 assert_eq!(after, *new, "TZ={:?} at the change at {}", tz, t);
105 }
106 Ok(edges.len())
107}
108
109// Wall times over a grid of local seconds: a time GNU date refuses is one the
110// zone must report as skipped, and one it dates is one the zone must reach
111// there. Returns how many grid times were skipped and how many came twice.
112fn locals_agree(
113 zone: &CalClockZone,
114 tz: &str,
115 tzdir: Option<&Path>,
116 from: i64,
117 to: i64,
118 step: i64,
119)
120 -> Outcome<(usize, usize)>
121{
122 let locals: Vec<i64> = (from..to).step_by(step as usize).collect();
123 let wall = res!(walls(&locals));
124 let said = res!(date_batch(tz, tzdir, &wall, "+%s"));
125 let (mut gaps, mut folds) = (0, 0);
126 let mut twice: Vec<(usize, i64, i64)> = Vec::new();
127 for (i, n) in locals.iter().enumerate() {
128 let theirs: Option<i64> = said[i].as_deref().and_then(|s| s.parse().ok());
129 match (zone.local_to_utc(n * 1000), theirs) {
130 (LocalTimeResult::Single(u), Some(g)) => {
131 assert_eq!(u, g * 1000, "{} reads {} at a different instant", tz, wall[i]);
132 },
133 (LocalTimeResult::None, None) => gaps += 1,
134 (LocalTimeResult::Ambiguous(a, b), Some(g)) => {
135 folds += 1;
136 assert!(a < b, "{} {}: the occurrences are not in order", tz, wall[i]);
137 assert!(g == a / 1000 || g == b / 1000,
138 "{} {}: GNU date's {} is neither of {} and {}", tz, wall[i], g, a / 1000, b / 1000);
139 twice.push((i, a / 1000, b / 1000));
140 },
141 (mine, theirs) => panic!(
142 "{} {}: the zone says {:?} and GNU date says {:?}", tz, wall[i], mine, theirs),
143 }
144 }
145 // Each instant of a fold must itself show the wall time.
146 let both: Vec<String> = twice.iter().flat_map(|(_, a, b)| [fmt!("@{}", a), fmt!("@{}", b)]).collect();
147 let shown = res!(date_batch(tz, tzdir, &both, "+%F %T"));
148 for (k, (i, a, b)) in twice.iter().enumerate() {
149 assert_eq!(shown[2 * k].as_deref(), Some(wall[*i].as_str()), "{} the earlier, {}", tz, a);
150 assert_eq!(shown[2 * k + 1].as_deref(), Some(wall[*i].as_str()), "{} the later, {}", tz, b);
151 }
152 Ok((gaps, folds))
153}
154
155#[test]
156fn offsets_match_gnu_date_across_2026() -> Outcome<()> {
157 if skip_without_oracle() { return Ok(()); }
158 // Transitions per zone in 2026, from zdump.
159 let changes = [2, 2, 0, 2, 0];
160 for (name, want) in ZONES.iter().zip(changes) {
161 if let Some(zone) = res!(zone_from(ZONEINFO, name)) {
162 let got = res!(offsets_agree(&zone, name, None, Y2026, Y2027, 1200));
163 assert_eq!(got, want, "{} changes in 2026", name);
164 }
165 }
166 Ok(())
167}
168
169#[test]
170fn local_times_match_gnu_date_across_2026() -> Outcome<()> {
171 if skip_without_oracle() { return Ok(()); }
172 // A 15 minute grid puts 4 times in an hour's gap and fold, 2 in half an hour's.
173 let skipped_and_twice = [(4, 4), (4, 4), (0, 0), (2, 2), (0, 0)];
174 for (name, want) in ZONES.iter().zip(skipped_and_twice) {
175 if let Some(zone) = res!(zone_from(ZONEINFO, name)) {
176 let got = res!(locals_agree(&zone, name, None, Y2026, Y2027, 900));
177 assert_eq!(got, want, "{} gap and fold times in 2026", name);
178 }
179 }
180 Ok(())
181}
182
183#[test]
184fn the_embedded_rules_match_gnu_date_across_2026() -> Outcome<()> {
185 if skip_without_oracle() { return Ok(()); }
186 // New York and London go through both changes; Sydney, in the other
187 // hemisphere, is in summer time across the new year.
188 let skipped_and_twice = [(4, 4), (4, 4), (4, 4)];
189 for (name, want) in EMBEDDED.iter().zip(skipped_and_twice) {
190 let zone = res!(CalClockZone::new_embedded(*name));
191 assert!(zone.tzif_data().is_none(), "{} was meant to be the embedded rules", name);
192 assert_eq!(res!(offsets_agree(&zone, name, None, Y2026, Y2027, 1200)), 2, "{}", name);
193 let got = res!(locals_agree(&zone, name, None, Y2026, Y2027, 900));
194 assert_eq!(got, want, "{} gap and fold times in 2026", name);
195 }
196 Ok(())
197}
198
199#[test]
200fn years_past_a_fat_table_follow_the_footer() -> Outcome<()> {
201 if skip_without_oracle() { return Ok(()); }
202 for name in ZONES {
203 if let Some(zone) = res!(zone_from(ZONEINFO, name)) {
204 if let Some(data) = zone.tzif_data() {
205 // Fat or not, the table must end before the span tested.
206 let last = data.transition_times.last().copied().unwrap_or(0);
207 assert!(last < Y2043, "{} has a table that outruns the test", name);
208 }
209 res!(offsets_agree(&zone, name, None, Y2038, Y2043, 3600));
210 res!(locals_agree(&zone, name, None, Y2038 + 86400 * 400, Y2038 + 86400 * 770, 900));
211 }
212 }
213 Ok(())
214}
215
216#[test]
217fn slim_files_agree_with_gnu_date() -> Outcome<()> {
218 if skip_without_oracle() { return Ok(()); }
219 let source = Path::new(ZONEINFO).join("tzdata.zi");
220 if !source.is_file() {
221 eprintln!("skipped: no {:?} to make slim files from", source);
222 return Ok(());
223 }
224 let out: PathBuf = std::env::temp_dir().join(fmt!("datime-slim-{}", std::process::id()));
225 let _ = fs::remove_dir_all(&out);
226 let made = Command::new("zic").arg("-b").arg("slim").arg("-d").arg(&out).arg(&source).output();
227 match made {
228 Ok(o) if o.status.success() => (),
229 _ => {
230 eprintln!("skipped: zic could not make slim files");
231 return Ok(());
232 },
233 }
234 let slim_dir = out.to_string_lossy().to_string();
235 for name in ZONES {
236 let (fat, slim) = match (res!(zone_from(ZONEINFO, name)), res!(zone_from(&slim_dir, name))) {
237 (Some(f), Some(s)) => (f, s),
238 _ => continue,
239 };
240 let (fat_data, slim_data) = match (fat.tzif_data(), slim.tzif_data()) {
241 (Some(f), Some(s)) => (f, s),
242 _ => continue,
243 };
244 let footer = slim_data.posix_tz_string.clone().unwrap_or_default();
245 assert!(!footer.is_empty(), "{} slim file has no footer", name);
246 if name == "America/New_York" || name == "Europe/London" {
247 // The tables must differ for the footer to be what answers.
248 assert!(slim_data.transition_times.len() < fat_data.transition_times.len(),
249 "{} slim has {} transitions to fat's {}", name,
250 slim_data.transition_times.len(), fat_data.transition_times.len());
251 let last = slim_data.transition_times.last().copied().unwrap_or(0);
252 assert!(last < Y2026, "{} slim table still runs to {}", name, last);
253 }
254 res!(offsets_agree(&slim, name, Some(&out), Y2026, Y2027, 1200));
255 res!(offsets_agree(&slim, name, Some(&out), Y2038, Y2043, 3600));
256 res!(locals_agree(&slim, name, Some(&out), Y2026, Y2027, 900));
257 res!(locals_agree(&slim, name, Some(&out), Y2038 + 86400 * 400, Y2038 + 86400 * 770, 900));
258 }
259 let _ = fs::remove_dir_all(&out);
260 Ok(())
261}
262
263// A zone that is nothing but a footer, so the rule is all that answers.
264fn footer_zone(rule: &str) -> Outcome<CalClockZone> {
265 let data = TZifData {
266 version: 3,
267 transition_times: Vec::new(),
268 transition_types: Vec::new(),
269 local_time_types: vec![LocalTimeType { utc_offset: 0, is_dst: false, abbreviation_index: 0 }],
270 abbreviations: String::new(),
271 leap_seconds: Vec::new(),
272 standard_wall_indicators: Vec::new(),
273 ut_local_indicators: Vec::new(),
274 posix_tz_string: Some(rule.to_string()),
275 };
276 CalClockZone::from_tzif_data("footer", data)
277}
278
279#[test]
280fn footer_rules_match_gnu_date() -> Outcome<()> {
281 if skip_without_oracle() { return Ok(()); }
282 // Both hemispheres, a rule time other than 02:00, a negative one, one past
283 // a day, the last week of a month, a half hour of daylight saving, a
284 // negative one (Dublin's, where winter is the daylight time), and the two
285 // day-of-year forms.
286 let rules = [
287 "EST5EDT,M3.2.0,M11.1.0",
288 "CET-1CEST,M3.5.0,M10.5.0/3",
289 "<+1030>-10:30<+11>-11,M10.1.0,M4.1.0",
290 "AEST-10AEDT,M10.1.0,M4.1.0/3",
291 "NZST-12NZDT,M9.5.0,M4.1.0/3",
292 "<-0330>3:30<-0230>,M3.2.0,M11.1.0",
293 "IST-1GMT0,M10.5.0,M3.5.0/1",
294 "EST5EDT,M3.2.0/-1,M11.1.0/26",
295 "EST5EDT,J60,J300",
296 "EST5EDT,59,299",
297 "<+05>-5",
298 ];
299 for rule in rules {
300 let zone = res!(footer_zone(rule));
301 res!(offsets_agree(&zone, rule, None, Y2026, Y2027, 1800));
302 res!(offsets_agree(&zone, rule, None, Y2038, Y2043, 7200));
303 res!(locals_agree(&zone, rule, None, Y2026, Y2027, 1800));
304 }
305 Ok(())
306}
307
308#[test]
309fn a_footer_that_cannot_be_read_is_an_error_not_a_guess() -> Outcome<()> {
310 for rule in ["EST5EDT,M13.1.0,M11.1.0", "EST5EDT,M3.2.0", "ES", "EST5EDT,M3.2.0,M11.1.0,x", "EST"] {
311 let zone = res!(footer_zone(rule));
312 assert!(zone.offset_millis_at_time(Y2026 * 1000).is_err(), "'{}' was read", rule);
313 assert_eq!(zone.local_to_utc(Y2026 * 1000), LocalTimeResult::None, "'{}'", rule);
314 }
315 Ok(())
316}
317
318// Answers taken from GNU date once and kept, so a machine with none still checks
319// the transitions. Each wall time is given as seconds of local time read as UTC,
320// and each answer as the UTC milliseconds of the occurrence or occurrences.
321#[test]
322fn fixed_answers_across_the_transitions() -> Outcome<()> {
323 use LocalTimeResult::{Ambiguous, None as Skipped, Single};
324 let ms = |secs: i64| secs * 1000;
325 // America/New_York: 2026-03-08 02:30 is skipped, 2026-11-01 01:30 comes twice.
326 let mut zones = vec![res!(CalClockZone::new_embedded("America/New_York"))];
327 zones.extend(res!(zone_from(ZONEINFO, "America/New_York")));
328 for zone in &zones {
329 assert_eq!(zone.local_to_utc(ms(1_772_933_400)), Single(ms(1_772_951_400)), "01:30 is EST");
330 assert_eq!(zone.local_to_utc(ms(1_772_937_000)), Skipped, "02:30 is skipped");
331 assert_eq!(zone.local_to_utc(ms(1_772_940_600)), Single(ms(1_772_955_000)), "03:30 is EDT");
332 assert_eq!(zone.local_to_utc(ms(1_793_496_600)), Ambiguous(ms(1_793_511_000), ms(1_793_514_600)),
333 "01:30 on 2026-11-01 comes in EDT and then EST");
334 // A time between the seconds keeps its milliseconds.
335 assert_eq!(zone.local_to_utc(ms(1_793_496_600) + 250),
336 Ambiguous(ms(1_793_511_000) + 250, ms(1_793_514_600) + 250));
337 }
338 // Europe/London: 01:30 on 2026-03-29 is skipped, 01:30 on 2026-10-25 comes twice.
339 let mut zones = vec![res!(CalClockZone::new_embedded("Europe/London"))];
340 zones.extend(res!(zone_from(ZONEINFO, "Europe/London")));
341 for zone in &zones {
342 assert_eq!(zone.local_to_utc(ms(1_774_747_800)), Skipped);
343 assert_eq!(zone.local_to_utc(ms(1_792_891_800)), Ambiguous(ms(1_792_888_200), ms(1_792_891_800)));
344 }
345 // Australia/Sydney, the other hemisphere: 02:30 on 2026-04-05 comes twice.
346 let mut zones = vec![res!(CalClockZone::new_embedded("Australia/Sydney"))];
347 zones.extend(res!(zone_from(ZONEINFO, "Australia/Sydney")));
348 for zone in &zones {
349 assert_eq!(zone.local_to_utc(ms(1_775_356_200)), Ambiguous(ms(1_775_316_600), ms(1_775_320_200)));
350 assert_eq!(zone.local_to_utc(ms(1_768_478_400)), Single(ms(1_768_438_800)),
351 "2026-01-15 12:00 is summer time");
352 }
353 // Australia/Lord_Howe, half an hour: 02:15 on 2026-10-04 is skipped, 01:45
354 // on 2026-04-05 comes twice.
355 if let Some(zone) = res!(zone_from(ZONEINFO, "Australia/Lord_Howe")) {
356 assert_eq!(zone.local_to_utc(ms(1_791_080_100)), Skipped);
357 assert_eq!(zone.local_to_utc(ms(1_775_353_500)), Ambiguous(ms(1_775_313_900), ms(1_775_315_700)));
358 }
359 // Asia/Kathmandu is +05:45 all year.
360 if let Some(zone) = res!(zone_from(ZONEINFO, "Asia/Kathmandu")) {
361 assert_eq!(zone.local_to_utc(ms(1_782_907_200)), Single(ms(1_782_886_500)));
362 }
363 Ok(())
364}
365
366// Puts TZ back as it was, whether the test that changed it returns or panics.
367// This file's other tests never read TZ, and the oracle runs they start set it
368// for the child alone, so the one test that changes it needs no lock.
369struct TzRestored(Option<String>);
370
371impl Drop for TzRestored {
372 fn drop(&mut self) {
373 match &self.0 {
374 Some(tz) => std::env::set_var("TZ", tz),
375 None => std::env::remove_var("TZ"),
376 }
377 }
378}
379
380// What `here()` makes of each way of writing TZ, with the number of changes it
381// has in 2026. GNU date, which reads TZ as libc does, is asked at every instant.
382#[test]
383fn here_reads_tz_as_libc_does() -> Outcome<()> {
384 if skip_without_oracle() { return Ok(()); }
385 let _restored = TzRestored(std::env::var("TZ").ok());
386 let forms: [(Option<&str>, usize); 19] = [
387 (None, 0), // this host's /etc/localtime
388 (Some(""), 0), // UTC, not "unset"
389 (Some(":"), 0),
390 (Some("UTC"), 0),
391 (Some(":/etc/localtime"), 0),
392 (Some(":Australia/Perth"), 0),
393 (Some("Australia/Lord_Howe"), 2),
394 (Some("/usr/share/zoneinfo/America/New_York"), 2), // a path to a TZif file
395 (Some("AEST-10AEDT,M10.1.0,M4.1.0/3"), 2), // a rule string, southern
396 (Some(":AEST-10AEDT,M10.1.0,M4.1.0/3"), 2),
397 (Some("EST5EDT,M3.2.0,M11.1.0"), 2), // and northern, if no file by that name
398 (Some("<+0530>-5:30"), 0),
399 (Some("<+05>-5"), 0),
400 (Some("EST5"), 0),
401 (Some("UTC+5"), 0), // five hours west: POSIX's sign, not Java's
402 (Some("UTC-3"), 0),
403 (Some("GMT+5"), 0),
404 (Some("garbage/Nowhere"), 0), // what nothing reads is UTC
405 (Some("Etc/GMT+5"), 0),
406 ];
407 for (tz, changes) in forms {
408 match tz {
409 Some(tz) => std::env::set_var("TZ", tz),
410 None => std::env::remove_var("TZ"),
411 }
412 let zone = CalClockZone::here();
413 let got = res!(offsets_agree_tz(&zone, tz, None, Y2026, Y2027, 1200));
414 assert_eq!(got, changes, "TZ={:?} changes in 2026", tz);
415 if tz == Some("garbage/Nowhere") {
416 // The fallback is named in the zone, which is what a command prints of it.
417 assert_eq!(zone.id(), "garbage/Nowhere");
418 }
419 }
420 Ok(())
421}
422
423// A rule string as a zone in its own right: both hemispheres, a rule time other
424// than 02:00, a negative one, one past a day, the last week, half an hour of
425// daylight saving, a negative one, the day-of-year forms and a rule that never
426// changes. GNU date answers offsets and wall times; the abbreviations are the
427// rule's own names.
428#[test]
429fn a_posix_rule_makes_a_zone_that_matches_gnu_date() -> Outcome<()> {
430 if skip_without_oracle() { return Ok(()); }
431 let rules = [
432 "EST5EDT,M3.2.0,M11.1.0",
433 "CET-1CEST,M3.5.0,M10.5.0/3",
434 "<+1030>-10:30<+11>-11,M10.1.0,M4.1.0",
435 "AEST-10AEDT,M10.1.0,M4.1.0/3",
436 "NZST-12NZDT,M9.5.0,M4.1.0/3",
437 "<-0330>3:30<-0230>,M3.2.0,M11.1.0",
438 "IST-1GMT0,M10.5.0,M3.5.0/1",
439 "EST5EDT,M3.2.0/-1,M11.1.0/26",
440 "EST5EDT,J60,J300",
441 "EST5EDT,59,299",
442 "<+05>-5",
443 "UTC+5",
444 ];
445 // A rule with no dates, such as `AEST-10AEDT`, is left out: POSIX leaves its dates to
446 // the implementation, and glibc takes them from the host's `posixrules` file.
447 for rule in rules {
448 let zone = res!(CalClockZone::from_posix_rule(rule));
449 assert_eq!(zone.id(), rule);
450 res!(offsets_agree(&zone, rule, None, Y2026, Y2027, 1800));
451 res!(offsets_agree(&zone, rule, None, Y2038, Y2043, 7200));
452 res!(locals_agree(&zone, rule, None, Y2026, Y2027, 1800));
453 }
454 let data = res!(TZifData::from_posix_rule("<+1030>-10:30<+11>-11,M10.1.0,M4.1.0"));
455 let names: Vec<&str> = data.local_time_types.iter()
456 .map(|t| data.get_abbreviation(t).unwrap_or("?"))
457 .collect();
458 assert_eq!(names, ["+1030", "+11"], "angle brackets are not part of a name");
459 let data = res!(TZifData::from_posix_rule("AEST-10AEDT,M10.1.0,M4.1.0/3"));
460 let seen: Vec<(&str, i32, bool)> = data.local_time_types.iter()
461 .map(|t| (data.get_abbreviation(t).unwrap_or("?"), t.utc_offset, t.is_dst))
462 .collect();
463 assert_eq!(seen, [("AEST", 36_000, false), ("AEDT", 39_600, true)]);
464 let zone = res!(CalClockZone::from_posix_rule("AEST-10AEDT,M10.1.0,M4.1.0/3"));
465 assert_eq!(zone.raw_offset_millis(), 36_000_000, "the standard offset, as Java's getRawOffset");
466 Ok(())
467}
468
469// What is not a rule is an error here, and `here()` keeps its fallback for it.
470#[test]
471fn text_that_is_not_a_rule_is_refused() -> Outcome<()> {
472 for text in ["", "garbage/Nowhere", "EST", "ES", "EST5EDT,M13.1.0,M11.1.0", "EST5EDT,M3.2.0", "+05:00"] {
473 assert!(CalClockZone::from_posix_rule(text).is_err(), "'{}' was read as a rule", text);
474 assert!(TZifData::from_posix_rule(text).is_err(), "'{}' was read as rule data", text);
475 }
476 Ok(())
477}