1#[cfg(all(test, feature = "alloc"))]
11mod tests {
12 use alloc::{
13 string::{String, ToString},
14 vec,
15 };
16
17 use jcore::tz::tzif;
18
19 #[cfg(not(miri))]
20 use crate::tz::testdata::TZIF_TEST_FILES;
21
22 fn tzif_to_human_readable(tzif: &tzif::TimeZone) -> String {
32 use std::io::Write;
33
34 struct IndicatorDisplay(tzif::Indicator);
35
36 impl core::fmt::Display for IndicatorDisplay {
37 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
38 match self.0 {
39 tzif::Indicator::LocalWall => write!(f, "local/wall"),
40 tzif::Indicator::LocalStandard => write!(f, "local/std"),
41 tzif::Indicator::UTStandard => write!(f, "ut/std"),
42 }
43 }
44 }
45
46 fn datetime(dt: tzif::DateTime) -> crate::civil::DateTime {
47 crate::civil::DateTime::constant(
48 dt.year(),
49 dt.month(),
50 dt.day(),
51 dt.hour(),
52 dt.minute(),
53 dt.second(),
54 0,
55 )
56 }
57
58 let mut out = tabwriter::TabWriter::new(vec![])
59 .alignment(tabwriter::Alignment::Left);
60
61 writeln!(out, "TIME ZONE VERSION").unwrap();
62 writeln!(out, " {}", char::try_from(tzif.version).unwrap()).unwrap();
63
64 writeln!(out, "LOCAL TIME TYPES").unwrap();
65 for (i, typ) in tzif.types.iter().enumerate() {
66 writeln!(
67 out,
68 " {i:03}:\toffset={off}\t\
69 designation={desig}\t{dst}\tindicator={ind}",
70 off = jcore::tz::Offset::from_seconds(typ.offset.seconds())
71 .unwrap(),
72 desig = tzif.designations[usize::from(typ.designation)],
73 dst = if typ.dst.is_dst() { "dst" } else { "" },
74 ind = IndicatorDisplay(typ.indicator),
75 )
76 .unwrap();
77 }
78 if !tzif.transitions.timestamps.is_empty() {
79 writeln!(out, "TRANSITIONS").unwrap();
80 for i in 0..tzif.transitions.timestamps.len() {
81 let trans = &tzif.transitions;
82 let timestamp = trans.timestamps[i];
83 let dt = jcore::tz::Offset::UTC
84 .to_datetime(timestamp.to_standard_timestamp());
85 let typ = tzif.types[usize::from(trans.infos[i].type_index)];
86 let wall =
87 alloc::format!("{}", datetime(trans.civil_starts[i]));
88 let ambiguous = match trans.infos[i].kind {
89 tzif::TransitionKind::Unambiguous => {
90 "unambiguous".to_string()
91 }
92 tzif::TransitionKind::Gap => {
93 let end = datetime(trans.civil_ends[i]);
94 alloc::format!(" gap-until({end})")
95 }
96 tzif::TransitionKind::Fold => {
97 let end = datetime(trans.civil_ends[i]);
98 alloc::format!("fold-until({end})")
99 }
100 };
101
102 writeln!(
103 out,
104 " {i:04}:\t{dt:?}Z\tunix={ts}\twall={wall}\t\
105 {ambiguous}\t\
106 type={type_index}\t{off}\t\
107 {desig}\t{dst}",
108 ts = timestamp.as_second(),
109 type_index = trans.infos[i].type_index,
110 off =
111 jcore::tz::Offset::from_seconds(typ.offset.seconds())
112 .unwrap(),
113 desig = tzif.designations[usize::from(typ.designation)],
114 dst = if typ.dst.is_dst() { "dst" } else { "" },
115 )
116 .unwrap();
117 }
118 }
119 if let Some(ref posix_tz) = tzif.posix_tz {
120 writeln!(out, "POSIX TIME ZONE STRING").unwrap();
121 writeln!(
122 out,
123 " {}",
124 crate::tz::posix::TimeZoneFormatter(posix_tz)
125 )
126 .unwrap();
127 }
128 String::from_utf8(out.into_inner().unwrap()).unwrap()
129 }
130
131 #[cfg(feature = "std")]
138 #[test]
139 fn debug_tzif() -> anyhow::Result<()> {
140 use anyhow::Context;
141
142 let _ = crate::logging::Logger::init();
143
144 const ENV: &str = "JIFF_DEBUG_TZIF_PATH";
145 let Some(val) = std::env::var_os(ENV) else { return Ok(()) };
146 let Ok(val) = val.into_string() else {
147 anyhow::bail!("{ENV} has invalid UTF-8")
148 };
149 let bytes =
150 std::fs::read(&val).with_context(|| alloc::format!("{val:?}"))?;
151 let tzif = tzif::TimeZone::parse(&bytes)?;
152 std::eprint!("{}", tzif_to_human_readable(&tzif));
153 Ok(())
154 }
155
156 #[cfg(not(miri))]
157 #[test]
158 fn tzif_parse_v2plus() {
159 for tzif_test in TZIF_TEST_FILES {
160 insta::assert_snapshot!(
161 alloc::format!("{}_v2+", tzif_test.name),
162 tzif_to_human_readable(&tzif_test.parse())
163 );
164 }
165 }
166
167 #[cfg(not(miri))]
168 #[test]
169 fn tzif_parse_v1() {
170 for tzif_test in TZIF_TEST_FILES {
171 insta::assert_snapshot!(
172 alloc::format!("{}_v1", tzif_test.name),
173 tzif_to_human_readable(&tzif_test.parse_v1())
174 );
175 }
176 }
177
178 #[cfg(not(miri))]
184 #[cfg(feature = "tzdb-zoneinfo")]
185 #[cfg(target_os = "linux")]
186 #[test]
187 fn zoneinfo() {
188 const TZDIR: &str = "/usr/share/zoneinfo";
189
190 for result in walkdir::WalkDir::new(TZDIR) {
191 let Ok(dent) = result else { continue };
195 let Some(name) = dent.path().to_str() else { continue };
198 if name.contains("right/") || name.contains("posix/") {
199 continue;
200 }
201 let Ok(bytes) = std::fs::read(dent.path()) else { continue };
203 if !tzif::is_possibly_tzif(&bytes) {
204 continue;
205 }
206 if let Err(err) = tzif::TimeZone::parse(&bytes) {
209 panic!("failed to parse TZif file {:?}: {err}", dent.path());
210 }
211 }
212 }
213}