1 /* SPDX-License-Identifier: LGPL-2.1+ */
5 #include "alloc-util.h"
6 #include "string-util.h"
9 static void test_should_pass(const char *p
) {
11 char buf
[FORMAT_TIMESTAMP_MAX
], buf_relative
[FORMAT_TIMESTAMP_RELATIVE_MAX
];
13 log_info("Test: %s", p
);
14 assert_se(parse_timestamp(p
, &t
) >= 0);
15 assert_se(format_timestamp_us(buf
, sizeof(buf
), t
));
16 log_info("\"%s\" → \"%s\"", p
, buf
);
18 assert_se(parse_timestamp(buf
, &q
) >= 0);
20 char tmp
[FORMAT_TIMESTAMP_MAX
];
22 log_error("round-trip failed: \"%s\" → \"%s\"",
23 buf
, format_timestamp_us(tmp
, sizeof(tmp
), q
));
27 assert_se(format_timestamp_relative(buf_relative
, sizeof(buf_relative
), t
));
28 log_info("%s", strna(buf_relative
));
31 static void test_should_parse(const char *p
) {
34 log_info("Test: %s", p
);
35 assert_se(parse_timestamp(p
, &t
) >= 0);
36 log_info("\"%s\" → \"@%" PRI_USEC
"\"", p
, t
);
39 static void test_should_fail(const char *p
) {
43 log_info("Test: %s", p
);
44 r
= parse_timestamp(p
, &t
);
46 log_info("\"%s\" → \"@%" PRI_USEC
"\" (unexpected)", p
, t
);
48 log_info("parse_timestamp() returns %d (expected)", r
);
52 static void test_one(const char *p
) {
53 _cleanup_free_
char *with_utc
;
55 with_utc
= strjoin(p
, " UTC");
57 test_should_pass(with_utc
);
60 static void test_one_noutc(const char *p
) {
61 _cleanup_free_
char *with_utc
;
63 with_utc
= strjoin(p
, " UTC");
65 test_should_fail(with_utc
);
68 int main(int argc
, char *argv
[]) {
69 log_set_max_level(LOG_DEBUG
);
70 log_parse_environment();
75 test_one("18:42:44.0");
76 test_one("18:42:44.999999999999");
77 test_one("12-10-02 12:13:14");
78 test_one("12-10-2 12:13:14");
79 test_one("12-10-03 12:13");
80 test_one("2012-12-30 18:42");
81 test_one("2012-10-02");
82 test_one("Tue 2012-10-02");
83 test_one("yesterday");
86 test_one_noutc("16:20 UTC");
87 test_one_noutc("16:20 Asia/Seoul");
88 test_one_noutc("tomorrow Asia/Seoul");
89 test_one_noutc("2012-12-30 18:42 Asia/Seoul");
90 test_one_noutc("now");
91 test_one_noutc("+2d");
92 test_one_noutc("+2y 4d");
93 test_one_noutc("5months ago");
94 test_one_noutc("@1395716396");
95 test_should_parse("1970-1-1 UTC");
96 test_should_pass("1970-1-1 00:00:01 UTC");
97 test_should_fail("1969-12-31 UTC");
98 test_should_fail("-100y");
99 test_should_fail("today UTC UTC");
100 test_should_fail("now Asia/Seoul");
101 test_should_fail("+2d Asia/Seoul");
102 test_should_fail("@1395716396 Asia/Seoul");
103 #if SIZEOF_TIME_T == 8
104 test_should_pass("9999-12-30 23:59:59 UTC");
105 test_should_fail("9999-12-31 00:00:00 UTC");
106 test_should_fail("10000-01-01 00:00:00 UTC");
107 #elif SIZEOF_TIME_T == 4
108 test_should_pass("2038-01-19 03:14:07 UTC");
109 test_should_fail("2038-01-19 03:14:08 UTC");