oxedyne/fe2o3/fe2o3_datime/tests/common/mod.rs
5.5 KiB, 7 runs
created by r1870400018:63089, 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 | //! GNU date as the oracle for the zone and moment tests. |
| 2 | //! |
| 3 | //! The machine's own `date` may not be GNU's (Ubuntu 25.10 ships uutils), so |
| 4 | //! `gnudate`, `gdate` and `date` are tried in turn and the first whose |
| 5 | //! `--version` says GNU coreutils is used. A machine with none skips the |
| 6 | //! oracle tests with a message and still runs the fixed-answer ones. |
| 7 | #![allow(dead_code)] |
| 8 | |
| 9 | use oxedyne_fe2o3_core::prelude::*; |
| 10 | use oxedyne_fe2o3_datime::time::{ |
| 11 | CalClockZone, |
| 12 | TZifParser, |
| 13 | }; |
| 14 | |
| 15 | use std::{ |
| 16 | collections::HashSet, |
| 17 | fs, |
| 18 | io::Write, |
| 19 | path::{Path, PathBuf}, |
| 20 | process::{Command, Stdio}, |
| 21 | sync::{ |
| 22 | atomic::{AtomicUsize, Ordering}, |
| 23 | OnceLock, |
| 24 | }, |
| 25 | }; |
| 26 | |
| 27 | pub const ZONEINFO: &str = "/usr/share/zoneinfo"; |
| 28 | |
| 29 | // Whole-year bounds, in UTC seconds. |
| 30 | pub const Y2026: i64 = 1_767_225_600; // 2026-01-01T00:00:00Z |
| 31 | pub const Y2027: i64 = 1_798_761_600; // 2027-01-01T00:00:00Z |
| 32 | pub const Y2038: i64 = 2_145_916_800; // 2038-01-01T00:00:00Z |
| 33 | pub const Y2043: i64 = 2_303_683_200; // 2043-01-01T00:00:00Z |
| 34 | |
| 35 | /// The GNU date to ask, if the machine has one. |
| 36 | pub fn gnu_date() -> Option<&'static str> { |
| 37 | static GNU: OnceLock<Option<String>> = OnceLock::new(); |
| 38 | GNU.get_or_init(|| { |
| 39 | for name in ["gnudate", "gdate", "date"] { |
| 40 | if let Ok(out) = Command::new(name).arg("--version").output() { |
| 41 | if String::from_utf8_lossy(&out.stdout).contains("GNU coreutils") { |
| 42 | return Some(name.to_string()); |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | None |
| 47 | }).as_deref() |
| 48 | } |
| 49 | |
| 50 | /// Says so and returns true when there is no GNU date to ask. |
| 51 | pub fn skip_without_oracle() -> bool { |
| 52 | if gnu_date().is_none() { |
| 53 | eprintln!("skipped: no GNU date on this machine"); |
| 54 | return true; |
| 55 | } |
| 56 | false |
| 57 | } |
| 58 | |
| 59 | fn scratch() -> PathBuf { |
| 60 | let dir = std::env::temp_dir().join(fmt!("datime-oracle-{}", std::process::id())); |
| 61 | let _ = fs::create_dir_all(&dir); |
| 62 | dir |
| 63 | } |
| 64 | |
| 65 | /// One answer per line, in order, from GNU date run with `tz` set and `tzdir` |
| 66 | /// as its zoneinfo tree if given. A line it refuses comes back None. |
| 67 | pub fn date_batch( |
| 68 | tz: &str, |
| 69 | tzdir: Option<&Path>, |
| 70 | lines: &[String], |
| 71 | format: &str, |
| 72 | ) |
| 73 | -> Outcome<Vec<Option<String>>> |
| 74 | { |
| 75 | date_batch_tz(Some(tz), tzdir, lines, format) |
| 76 | } |
| 77 | |
| 78 | /// As `date_batch`, but `TZ` is left out of the environment where `tz` is None, |
| 79 | /// which is not the same as setting it to nothing. |
| 80 | pub fn date_batch_tz( |
| 81 | tz: Option<&str>, |
| 82 | tzdir: Option<&Path>, |
| 83 | lines: &[String], |
| 84 | format: &str, |
| 85 | ) |
| 86 | -> Outcome<Vec<Option<String>>> |
| 87 | { |
| 88 | let gnu = res!(gnu_date().ok_or_else(|| err!("No GNU date."; System, Missing))); |
| 89 | // Tests run in parallel, so each call has a file of its own. |
| 90 | static CALLS: AtomicUsize = AtomicUsize::new(0); |
| 91 | let file = scratch().join(fmt!("in-{}.txt", CALLS.fetch_add(1, Ordering::SeqCst))); |
| 92 | { |
| 93 | let mut f = res!(fs::File::create(&file).map_err(|e| err!(e, "Could not write {:?}", file; IO, File))); |
| 94 | for line in lines { |
| 95 | res!(writeln!(f, "{}", line).map_err(|e| err!(e, "Could not write {:?}", file; IO, File))); |
| 96 | } |
| 97 | } |
| 98 | let mut cmd = Command::new(gnu); |
| 99 | cmd.env_remove("TZDIR"); |
| 100 | match tz { |
| 101 | Some(tz) => cmd.env("TZ", tz), |
| 102 | None => cmd.env_remove("TZ"), |
| 103 | }; |
| 104 | if let Some(dir) = tzdir { |
| 105 | cmd.env("TZDIR", dir); |
| 106 | } |
| 107 | let out = res!(cmd.arg("-f").arg(&file).arg(format) |
| 108 | .stdin(Stdio::null()).output().map_err(|e| err!(e, "Could not run {}", gnu; IO))); |
| 109 | let _ = fs::remove_file(&file); |
| 110 | let stdout = String::from_utf8_lossy(&out.stdout).to_string(); |
| 111 | let mut said = stdout.lines(); |
| 112 | // The lines it refuses are named on stderr, between curly quotes. |
| 113 | let mut refused: HashSet<String> = HashSet::new(); |
| 114 | for line in String::from_utf8_lossy(&out.stderr).lines() { |
| 115 | if let (Some(a), Some(b)) = (line.find('\u{2018}'), line.rfind('\u{2019}')) { |
| 116 | if line.contains("invalid date") && a < b { |
| 117 | refused.insert(line[a + '\u{2018}'.len_utf8()..b].to_string()); |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | let mut answers = Vec::with_capacity(lines.len()); |
| 122 | for line in lines { |
| 123 | if refused.contains(line) { |
| 124 | answers.push(None); |
| 125 | } else { |
| 126 | match said.next() { |
| 127 | Some(s) => answers.push(Some(s.to_string())), |
| 128 | None => return Err(err!( |
| 129 | "GNU date gave no answer for '{}' under TZ={:?} TZDIR={:?}: {}", |
| 130 | line, tz, tzdir, String::from_utf8_lossy(&out.stderr).lines().next().unwrap_or(""); |
| 131 | Invalid, Mismatch)), |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | if said.next().is_some() { |
| 136 | return Err(err!("GNU date answered more lines than it was given."; Invalid, Mismatch)); |
| 137 | } |
| 138 | Ok(answers) |
| 139 | } |
| 140 | |
| 141 | /// GNU date's `+%z` text as seconds east of UTC. |
| 142 | pub fn z_secs(z: &str) -> i64 { |
| 143 | let sign = if z.starts_with('-') { -1 } else { 1 }; |
| 144 | let n: i64 = z[1..3].parse().unwrap_or(0) ; |
| 145 | let m: i64 = z[3..5].parse().unwrap_or(0); |
| 146 | sign * (n * 3600 + m * 60) |
| 147 | } |
| 148 | |
| 149 | /// A zone as `here()` makes one, from the host's zoneinfo file; None when the |
| 150 | /// file is absent. Slim copies live in `dir`. |
| 151 | pub fn zone_from(dir: &str, name: &str) -> Outcome<Option<CalClockZone>> { |
| 152 | let path = Path::new(dir).join(name); |
| 153 | if !path.is_file() { |
| 154 | eprintln!("skipped {}: no file {:?}", name, path); |
| 155 | return Ok(None); |
| 156 | } |
| 157 | let mut parser = TZifParser::new(); |
| 158 | res!(parser.load_from_file(&path)); |
| 159 | let data = res!(parser.timezone_data().ok_or_else(|| err!("No data in {:?}", path; Invalid, Missing))); |
| 160 | Ok(Some(res!(CalClockZone::from_tzif_data(name, data.clone())))) |
| 161 | } |
| 162 | |
| 163 | /// The wall times of a list of local seconds, as GNU date writes them in UTC. |
| 164 | pub fn walls(locals: &[i64]) -> Outcome<Vec<String>> { |
| 165 | let lines: Vec<String> = locals.iter().map(|n| fmt!("@{}", n)).collect(); |
| 166 | let out = res!(date_batch("UTC", None, &lines, "+%F %T")); |
| 167 | let mut walls = Vec::with_capacity(out.len()); |
| 168 | for w in out { |
| 169 | walls.push(res!(w.ok_or_else(|| err!("GNU date refused an epoch second."; Invalid, Mismatch)))); |
| 170 | } |
| 171 | Ok(walls) |
| 172 | } |