Debian Codegraph @

debian/rust-vendor/chrono/src/naive/datetime/tests.rs

raw
1 use super::NaiveDateTime;
2 use crate::{Datelike, FixedOffset, MappedLocalTime, NaiveDate, TimeDelta, Utc};
3
4 #[test]
5 fn test_datetime_add() {
6 fn check(
7 (y, m, d, h, n, s): (i32, u32, u32, u32, u32, u32),
8 rhs: TimeDelta,
9 result: Option<(i32, u32, u32, u32, u32, u32)>,
10 ) {
11 let lhs = NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap();
12 let sum = result.map(|(y, m, d, h, n, s)| {
13 NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap()
14 });
15 assert_eq!(lhs.checked_add_signed(rhs), sum);
16 assert_eq!(lhs.checked_sub_signed(-rhs), sum);
17 }
18 let seconds = |s| TimeDelta::try_seconds(s).unwrap();
19
20 check((2014, 5, 6, 7, 8, 9), seconds(3600 + 60 + 1), Some((2014, 5, 6, 8, 9, 10)));
21 check((2014, 5, 6, 7, 8, 9), seconds(-(3600 + 60 + 1)), Some((2014, 5, 6, 6, 7, 8)));
22 check((2014, 5, 6, 7, 8, 9), seconds(86399), Some((2014, 5, 7, 7, 8, 8)));
23 check((2014, 5, 6, 7, 8, 9), seconds(86_400 * 10), Some((2014, 5, 16, 7, 8, 9)));
24 check((2014, 5, 6, 7, 8, 9), seconds(-86_400 * 10), Some((2014, 4, 26, 7, 8, 9)));
25 check((2014, 5, 6, 7, 8, 9), seconds(86_400 * 10), Some((2014, 5, 16, 7, 8, 9)));
26
27 // overflow check
28 // assumes that we have correct values for MAX/MIN_DAYS_FROM_YEAR_0 from `naive::date`.
29 // (they are private constants, but the equivalence is tested in that module.)
30 let max_days_from_year_0 =
31 NaiveDate::MAX.signed_duration_since(NaiveDate::from_ymd_opt(0, 1, 1).unwrap());
32 check((0, 1, 1, 0, 0, 0), max_days_from_year_0, Some((NaiveDate::MAX.year(), 12, 31, 0, 0, 0)));
33 check(
34 (0, 1, 1, 0, 0, 0),
35 max_days_from_year_0 + seconds(86399),
36 Some((NaiveDate::MAX.year(), 12, 31, 23, 59, 59)),
37 );
38 check((0, 1, 1, 0, 0, 0), max_days_from_year_0 + seconds(86_400), None);
39 check((0, 1, 1, 0, 0, 0), TimeDelta::MAX, None);
40
41 let min_days_from_year_0 =
42 NaiveDate::MIN.signed_duration_since(NaiveDate::from_ymd_opt(0, 1, 1).unwrap());
43 check((0, 1, 1, 0, 0, 0), min_days_from_year_0, Some((NaiveDate::MIN.year(), 1, 1, 0, 0, 0)));
44 check((0, 1, 1, 0, 0, 0), min_days_from_year_0 - seconds(1), None);
45 check((0, 1, 1, 0, 0, 0), TimeDelta::MIN, None);
46 }
47
48 #[test]
49 fn test_datetime_sub() {
50 let ymdhms =
51 |y, m, d, h, n, s| NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap();
52 let since = NaiveDateTime::signed_duration_since;
53 assert_eq!(since(ymdhms(2014, 5, 6, 7, 8, 9), ymdhms(2014, 5, 6, 7, 8, 9)), TimeDelta::zero());
54 assert_eq!(
55 since(ymdhms(2014, 5, 6, 7, 8, 10), ymdhms(2014, 5, 6, 7, 8, 9)),
56 TimeDelta::try_seconds(1).unwrap()
57 );
58 assert_eq!(
59 since(ymdhms(2014, 5, 6, 7, 8, 9), ymdhms(2014, 5, 6, 7, 8, 10)),
60 TimeDelta::try_seconds(-1).unwrap()
61 );
62 assert_eq!(
63 since(ymdhms(2014, 5, 7, 7, 8, 9), ymdhms(2014, 5, 6, 7, 8, 10)),
64 TimeDelta::try_seconds(86399).unwrap()
65 );
66 assert_eq!(
67 since(ymdhms(2001, 9, 9, 1, 46, 39), ymdhms(1970, 1, 1, 0, 0, 0)),
68 TimeDelta::try_seconds(999_999_999).unwrap()
69 );
70 }
71
72 #[test]
73 fn test_datetime_addassignment() {
74 let ymdhms =
75 |y, m, d, h, n, s| NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap();
76 let mut date = ymdhms(2016, 10, 1, 10, 10, 10);
77 date += TimeDelta::try_minutes(10_000_000).unwrap();
78 assert_eq!(date, ymdhms(2035, 10, 6, 20, 50, 10));
79 date += TimeDelta::try_days(10).unwrap();
80 assert_eq!(date, ymdhms(2035, 10, 16, 20, 50, 10));
81 }
82
83 #[test]
84 fn test_datetime_subassignment() {
85 let ymdhms =
86 |y, m, d, h, n, s| NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap();
87 let mut date = ymdhms(2016, 10, 1, 10, 10, 10);
88 date -= TimeDelta::try_minutes(10_000_000).unwrap();
89 assert_eq!(date, ymdhms(1997, 9, 26, 23, 30, 10));
90 date -= TimeDelta::try_days(10).unwrap();
91 assert_eq!(date, ymdhms(1997, 9, 16, 23, 30, 10));
92 }
93
94 #[test]
95 fn test_core_duration_ops() {
96 use core::time::Duration;
97
98 let mut dt = NaiveDate::from_ymd_opt(2023, 8, 29).unwrap().and_hms_opt(11, 34, 12).unwrap();
99 let same = dt + Duration::ZERO;
100 assert_eq!(dt, same);
101
102 dt += Duration::new(3600, 0);
103 assert_eq!(dt, NaiveDate::from_ymd_opt(2023, 8, 29).unwrap().and_hms_opt(12, 34, 12).unwrap());
104 }
105
106 #[test]
107 #[should_panic]
108 fn test_core_duration_max() {
109 use core::time::Duration;
110
111 let mut utc_dt = NaiveDate::from_ymd_opt(2023, 8, 29).unwrap().and_hms_opt(11, 34, 12).unwrap();
112 utc_dt += Duration::MAX;
113 }
114
115 #[test]
116 fn test_datetime_from_str() {
117 // valid cases
118 let valid = [
119 "2001-02-03T04:05:06",
120 "2012-12-12T12:12:12",
121 "2015-02-18T23:16:09.153",
122 "2015-2-18T23:16:09.153",
123 "-77-02-18T23:16:09",
124 "+82701-05-6T15:9:60.898989898989",
125 " +82701 - 05 - 6 T 15 : 9 : 60.898989898989 ",
126 ];
127 for &s in &valid {
128 eprintln!("test_parse_naivedatetime valid {s:?}");
129 let d = match s.parse::<NaiveDateTime>() {
130 Ok(d) => d,
131 Err(e) => panic!("parsing `{s}` has failed: {e}"),
132 };
133 let s_ = format!("{d:?}");
134 // `s` and `s_` may differ, but `s.parse()` and `s_.parse()` must be same
135 let d_ = match s_.parse::<NaiveDateTime>() {
136 Ok(d) => d,
137 Err(e) => {
138 panic!("`{s}` is parsed into `{d:?}`, but reparsing that has failed: {e}")
139 }
140 };
141 assert!(
142 d == d_,
143 "`{s}` is parsed into `{d:?}`, but reparsed result \
144 `{d_:?}` does not match"
145 );
146 }
147
148 // some invalid cases
149 // since `ParseErrorKind` is private, all we can do is to check if there was an error
150 let invalid = [
151 "", // empty
152 "x", // invalid / missing data
153 "15", // missing data
154 "15:8:9", // looks like a time (invalid date)
155 "15-8-9", // looks like a date (invalid)
156 "Fri, 09 Aug 2013 23:54:35 GMT", // valid date, wrong format
157 "Sat Jun 30 23:59:60 2012", // valid date, wrong format
158 "1441497364.649", // valid date, wrong format
159 "+1441497364.649", // valid date, wrong format
160 "+1441497364", // valid date, wrong format
161 "2014/02/03 04:05:06", // valid date, wrong format
162 "2015-15-15T15:15:15", // invalid date
163 "2012-12-12T12:12:12x", // bad timezone / trailing literal
164 "2012-12-12T12:12:12+00:00", // unexpected timezone / trailing literal
165 "2012-12-12T12:12:12 +00:00", // unexpected timezone / trailing literal
166 "2012-12-12T12:12:12 GMT", // unexpected timezone / trailing literal
167 "2012-123-12T12:12:12", // invalid month
168 "2012-12-12t12:12:12", // bad divider 't'
169 "2012-12-12 12:12:12", // missing divider 'T'
170 "2012-12-12T12:12:12Z", // trailing char 'Z'
171 "+ 82701-123-12T12:12:12", // strange year, invalid month
172 "+802701-123-12T12:12:12", // out-of-bound year, invalid month
173 ];
174 for &s in &invalid {
175 eprintln!("test_datetime_from_str invalid {s:?}");
176 assert!(s.parse::<NaiveDateTime>().is_err());
177 }
178 }
179
180 #[test]
181 fn test_datetime_parse_from_str() {
182 let ymdhms =
183 |y, m, d, h, n, s| NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_opt(h, n, s).unwrap();
184 let ymdhmsn = |y, m, d, h, n, s, nano| {
185 NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_nano_opt(h, n, s, nano).unwrap()
186 };
187 assert_eq!(
188 NaiveDateTime::parse_from_str("2014-5-7T12:34:56+09:30", "%Y-%m-%dT%H:%M:%S%z"),
189 Ok(ymdhms(2014, 5, 7, 12, 34, 56))
190 ); // ignore offset
191 assert_eq!(
192 NaiveDateTime::parse_from_str("2015-W06-1 000000", "%G-W%V-%u%H%M%S"),
193 Ok(ymdhms(2015, 2, 2, 0, 0, 0))
194 );
195 assert_eq!(
196 NaiveDateTime::parse_from_str("Fri, 09 Aug 2013 23:54:35 GMT", "%a, %d %b %Y %H:%M:%S GMT"),
197 Ok(ymdhms(2013, 8, 9, 23, 54, 35))
198 );
199 assert!(
200 NaiveDateTime::parse_from_str("Sat, 09 Aug 2013 23:54:35 GMT", "%a, %d %b %Y %H:%M:%S GMT")
201 .is_err()
202 );
203 assert!(NaiveDateTime::parse_from_str("2014-5-7 Q2 12:3456", "%Y-%m-%d Q%q %H:%M:%S").is_err());
204 assert!(NaiveDateTime::parse_from_str("12:34:56", "%H:%M:%S").is_err()); // insufficient
205 assert_eq!(
206 NaiveDateTime::parse_from_str("1441497364", "%s"),
207 Ok(ymdhms(2015, 9, 5, 23, 56, 4))
208 );
209 assert_eq!(
210 NaiveDateTime::parse_from_str("1283929614.1234", "%s.%f"),
211 Ok(ymdhmsn(2010, 9, 8, 7, 6, 54, 1234))
212 );
213 assert_eq!(
214 NaiveDateTime::parse_from_str("1441497364.649", "%s%.3f"),
215 Ok(ymdhmsn(2015, 9, 5, 23, 56, 4, 649000000))
216 );
217 assert_eq!(
218 NaiveDateTime::parse_from_str("1497854303.087654", "%s%.6f"),
219 Ok(ymdhmsn(2017, 6, 19, 6, 38, 23, 87654000))
220 );
221 assert_eq!(
222 NaiveDateTime::parse_from_str("1437742189.918273645", "%s%.9f"),
223 Ok(ymdhmsn(2015, 7, 24, 12, 49, 49, 918273645))
224 );
225 }
226
227 #[test]
228 fn test_datetime_parse_from_str_with_spaces() {
229 let parse_from_str = NaiveDateTime::parse_from_str;
230 let dt = NaiveDate::from_ymd_opt(2013, 8, 9).unwrap().and_hms_opt(23, 54, 35).unwrap();
231 // with varying spaces - should succeed
232 assert_eq!(parse_from_str(" Aug 09 2013 23:54:35", " %b %d %Y %H:%M:%S"), Ok(dt));
233 assert_eq!(parse_from_str("Aug 09 2013 23:54:35 ", "%b %d %Y %H:%M:%S "), Ok(dt));
234 assert_eq!(parse_from_str(" Aug 09 2013 23:54:35 ", " %b %d %Y %H:%M:%S "), Ok(dt));
235 assert_eq!(parse_from_str(" Aug 09 2013 23:54:35", " %b %d %Y %H:%M:%S"), Ok(dt));
236 assert_eq!(parse_from_str(" Aug 09 2013 23:54:35", " %b %d %Y %H:%M:%S"), Ok(dt));
237 assert_eq!(parse_from_str("\n\tAug 09 2013 23:54:35 ", "\n\t%b %d %Y %H:%M:%S "), Ok(dt));
238 assert_eq!(parse_from_str("\tAug 09 2013 23:54:35\t", "\t%b %d %Y %H:%M:%S\t"), Ok(dt));
239 assert_eq!(parse_from_str("Aug 09 2013 23:54:35", "%b %d %Y %H:%M:%S"), Ok(dt));
240 assert_eq!(parse_from_str("Aug 09 2013 23:54:35", "%b %d %Y %H:%M:%S"), Ok(dt));
241 assert_eq!(parse_from_str("Aug 09 2013\t23:54:35", "%b %d %Y\t%H:%M:%S"), Ok(dt));
242 assert_eq!(parse_from_str("Aug 09 2013\t\t23:54:35", "%b %d %Y\t\t%H:%M:%S"), Ok(dt));
243 assert_eq!(parse_from_str("Aug 09 2013 23:54:35 ", "%b %d %Y %H:%M:%S\n"), Ok(dt));
244 assert_eq!(parse_from_str("Aug 09 2013 23:54:35", "%b %d %Y\t%H:%M:%S"), Ok(dt));
245 assert_eq!(parse_from_str("Aug 09 2013 23:54:35", "%b %d %Y %H:%M:%S "), Ok(dt));
246 assert_eq!(parse_from_str("Aug 09 2013 23:54:35", " %b %d %Y %H:%M:%S"), Ok(dt));
247 assert_eq!(parse_from_str("Aug 09 2013 23:54:35", "%b %d %Y %H:%M:%S\n"), Ok(dt));
248 // with varying spaces - should fail
249 // leading space in data
250 assert!(parse_from_str(" Aug 09 2013 23:54:35", "%b %d %Y %H:%M:%S").is_err());
251 // trailing space in data
252 assert!(parse_from_str("Aug 09 2013 23:54:35 ", "%b %d %Y %H:%M:%S").is_err());
253 // trailing tab in data
254 assert!(parse_from_str("Aug 09 2013 23:54:35\t", "%b %d %Y %H:%M:%S").is_err());
255 // mismatched newlines
256 assert!(parse_from_str("\nAug 09 2013 23:54:35", "%b %d %Y %H:%M:%S\n").is_err());
257 // trailing literal in data
258 assert!(parse_from_str("Aug 09 2013 23:54:35 !!!", "%b %d %Y %H:%M:%S ").is_err());
259 }
260
261 #[test]
262 fn test_datetime_add_sub_invariant() {
263 // issue #37
264 let base = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap().and_hms_opt(0, 0, 0).unwrap();
265 let t = -946684799990000;
266 let time = base + TimeDelta::microseconds(t);
267 assert_eq!(t, time.signed_duration_since(base).num_microseconds().unwrap());
268 }
269
270 #[test]
271 fn test_and_local_timezone() {
272 let ndt = NaiveDate::from_ymd_opt(2022, 6, 15).unwrap().and_hms_opt(18, 59, 36).unwrap();
273 let dt_utc = ndt.and_utc();
274 assert_eq!(dt_utc.naive_local(), ndt);
275 assert_eq!(dt_utc.timezone(), Utc);
276
277 let offset_tz = FixedOffset::west_opt(4 * 3600).unwrap();
278 let dt_offset = ndt.and_local_timezone(offset_tz).unwrap();
279 assert_eq!(dt_offset.naive_local(), ndt);
280 assert_eq!(dt_offset.timezone(), offset_tz);
281 }
282
283 #[test]
284 fn test_and_utc() {
285 let ndt = NaiveDate::from_ymd_opt(2023, 1, 30).unwrap().and_hms_opt(19, 32, 33).unwrap();
286 let dt_utc = ndt.and_utc();
287 assert_eq!(dt_utc.naive_local(), ndt);
288 assert_eq!(dt_utc.timezone(), Utc);
289 }
290
291 #[test]
292 fn test_checked_add_offset() {
293 let ymdhmsm = |y, m, d, h, mn, s, mi| {
294 NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_milli_opt(h, mn, s, mi)
295 };
296
297 let positive_offset = FixedOffset::east_opt(2 * 60 * 60).unwrap();
298 // regular date
299 let dt = ymdhmsm(2023, 5, 5, 20, 10, 0, 0).unwrap();
300 assert_eq!(dt.checked_add_offset(positive_offset), ymdhmsm(2023, 5, 5, 22, 10, 0, 0));
301 // leap second is preserved
302 let dt = ymdhmsm(2023, 6, 30, 23, 59, 59, 1_000).unwrap();
303 assert_eq!(dt.checked_add_offset(positive_offset), ymdhmsm(2023, 7, 1, 1, 59, 59, 1_000));
304 // out of range
305 assert!(NaiveDateTime::MAX.checked_add_offset(positive_offset).is_none());
306
307 let negative_offset = FixedOffset::west_opt(2 * 60 * 60).unwrap();
308 // regular date
309 let dt = ymdhmsm(2023, 5, 5, 20, 10, 0, 0).unwrap();
310 assert_eq!(dt.checked_add_offset(negative_offset), ymdhmsm(2023, 5, 5, 18, 10, 0, 0));
311 // leap second is preserved
312 let dt = ymdhmsm(2023, 6, 30, 23, 59, 59, 1_000).unwrap();
313 assert_eq!(dt.checked_add_offset(negative_offset), ymdhmsm(2023, 6, 30, 21, 59, 59, 1_000));
314 // out of range
315 assert!(NaiveDateTime::MIN.checked_add_offset(negative_offset).is_none());
316 }
317
318 #[test]
319 fn test_checked_sub_offset() {
320 let ymdhmsm = |y, m, d, h, mn, s, mi| {
321 NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_milli_opt(h, mn, s, mi)
322 };
323
324 let positive_offset = FixedOffset::east_opt(2 * 60 * 60).unwrap();
325 // regular date
326 let dt = ymdhmsm(2023, 5, 5, 20, 10, 0, 0).unwrap();
327 assert_eq!(dt.checked_sub_offset(positive_offset), ymdhmsm(2023, 5, 5, 18, 10, 0, 0));
328 // leap second is preserved
329 let dt = ymdhmsm(2023, 6, 30, 23, 59, 59, 1_000).unwrap();
330 assert_eq!(dt.checked_sub_offset(positive_offset), ymdhmsm(2023, 6, 30, 21, 59, 59, 1_000));
331 // out of range
332 assert!(NaiveDateTime::MIN.checked_sub_offset(positive_offset).is_none());
333
334 let negative_offset = FixedOffset::west_opt(2 * 60 * 60).unwrap();
335 // regular date
336 let dt = ymdhmsm(2023, 5, 5, 20, 10, 0, 0).unwrap();
337 assert_eq!(dt.checked_sub_offset(negative_offset), ymdhmsm(2023, 5, 5, 22, 10, 0, 0));
338 // leap second is preserved
339 let dt = ymdhmsm(2023, 6, 30, 23, 59, 59, 1_000).unwrap();
340 assert_eq!(dt.checked_sub_offset(negative_offset), ymdhmsm(2023, 7, 1, 1, 59, 59, 1_000));
341 // out of range
342 assert!(NaiveDateTime::MAX.checked_sub_offset(negative_offset).is_none());
343
344 assert_eq!(dt.checked_add_offset(positive_offset), Some(dt + positive_offset));
345 assert_eq!(dt.checked_sub_offset(positive_offset), Some(dt - positive_offset));
346 }
347
348 #[test]
349 fn test_overflowing_add_offset() {
350 let ymdhmsm = |y, m, d, h, mn, s, mi| {
351 NaiveDate::from_ymd_opt(y, m, d).unwrap().and_hms_milli_opt(h, mn, s, mi).unwrap()
352 };
353 let positive_offset = FixedOffset::east_opt(2 * 60 * 60).unwrap();
354 // regular date
355 let dt = ymdhmsm(2023, 5, 5, 20, 10, 0, 0);
356 assert_eq!(dt.overflowing_add_offset(positive_offset), ymdhmsm(2023, 5, 5, 22, 10, 0, 0));
357 // leap second is preserved
358 let dt = ymdhmsm(2023, 6, 30, 23, 59, 59, 1_000);
359 assert_eq!(dt.overflowing_add_offset(positive_offset), ymdhmsm(2023, 7, 1, 1, 59, 59, 1_000));
360 // out of range
361 assert!(NaiveDateTime::MAX.overflowing_add_offset(positive_offset) > NaiveDateTime::MAX);
362
363 let negative_offset = FixedOffset::west_opt(2 * 60 * 60).unwrap();
364 // regular date
365 let dt = ymdhmsm(2023, 5, 5, 20, 10, 0, 0);
366 assert_eq!(dt.overflowing_add_offset(negative_offset), ymdhmsm(2023, 5, 5, 18, 10, 0, 0));
367 // leap second is preserved
368 let dt = ymdhmsm(2023, 6, 30, 23, 59, 59, 1_000);
369 assert_eq!(dt.overflowing_add_offset(negative_offset), ymdhmsm(2023, 6, 30, 21, 59, 59, 1_000));
370 // out of range
371 assert!(NaiveDateTime::MIN.overflowing_add_offset(negative_offset) < NaiveDateTime::MIN);
372 }
373
374 #[test]
375 fn test_and_timezone_min_max_dates() {
376 for offset_hour in -23..=23 {
377 dbg!(offset_hour);
378 let offset = FixedOffset::east_opt(offset_hour * 60 * 60).unwrap();
379
380 let local_max = NaiveDateTime::MAX.and_local_timezone(offset);
381 if offset_hour >= 0 {
382 assert_eq!(local_max.unwrap().naive_local(), NaiveDateTime::MAX);
383 } else {
384 assert_eq!(local_max, MappedLocalTime::None);
385 }
386 let local_min = NaiveDateTime::MIN.and_local_timezone(offset);
387 if offset_hour <= 0 {
388 assert_eq!(local_min.unwrap().naive_local(), NaiveDateTime::MIN);
389 } else {
390 assert_eq!(local_min, MappedLocalTime::None);
391 }
392 }
393 }
394
395 #[test]
396 #[cfg(feature = "rkyv-validation")]
397 fn test_rkyv_validation() {
398 let dt_min = NaiveDateTime::MIN;
399 let bytes = rkyv::to_bytes::<_, 12>(&dt_min).unwrap();
400 assert_eq!(rkyv::from_bytes::<NaiveDateTime>(&bytes).unwrap(), dt_min);
401
402 let dt_max = NaiveDateTime::MAX;
403 let bytes = rkyv::to_bytes::<_, 12>(&dt_max).unwrap();
404 assert_eq!(rkyv::from_bytes::<NaiveDateTime>(&bytes).unwrap(), dt_max);
405 }