1#include <base/detect.h>
2#include <base/time.h>
3
4#include <gtest/gtest.h>
5
6#include <cstdlib>
7
8class TimestampTest : public testing::Test
9{
10protected:
11 void SetUp() override
12 {
13#if defined(CONF_FAMILY_WINDOWS)
14 _putenv_s("TZ", "UTC");
15 _tzset();
16#else
17 setenv(name: "TZ", value: "UTC", replace: 1);
18 tzset();
19#endif
20 }
21};
22
23TEST_F(TimestampTest, FromStr)
24{
25 time_t Timestamp;
26 EXPECT_TRUE(timestamp_from_str("2023-12-31_12-58-55", TimestampFormat::NOSPACE, &Timestamp));
27 EXPECT_EQ(Timestamp, 1704027535);
28
29 EXPECT_TRUE(timestamp_from_str("2012-02-29_13-00-00", TimestampFormat::NOSPACE, &Timestamp));
30 EXPECT_EQ(Timestamp, 1330520400);
31
32 EXPECT_TRUE(timestamp_from_str("2004-05-15 18:13:53", TimestampFormat::SPACE, &Timestamp));
33 EXPECT_EQ(Timestamp, 1084644833);
34}
35
36TEST_F(TimestampTest, FromStrFailing)
37{
38 time_t Timestamp;
39 // Invalid time string
40 EXPECT_FALSE(timestamp_from_str("123 2023-12-31_12-58-55", TimestampFormat::NOSPACE, &Timestamp));
41
42 // Invalid time string
43 EXPECT_FALSE(timestamp_from_str("555-02-29_13-12-7", TimestampFormat::NOSPACE, &Timestamp));
44
45 // Time string does not fit the format
46 EXPECT_FALSE(timestamp_from_str("2004-05-15 18-13-53", TimestampFormat::SPACE, &Timestamp));
47
48 // Invalid time string
49 EXPECT_FALSE(timestamp_from_str("2000-01-01 00:00:00:00", TimestampFormat::SPACE, &Timestamp));
50}
51
52TEST_F(TimestampTest, WithSpecifiedFormatAndTimestamp)
53{
54 char aTimestamp[20];
55 str_timestamp_ex(time: 1704027535, buffer: aTimestamp, buffer_size: sizeof(aTimestamp), format: TimestampFormat::NOSPACE);
56 EXPECT_STREQ(aTimestamp, "2023-12-31_12-58-55");
57
58 str_timestamp_ex(time: 1330520400, buffer: aTimestamp, buffer_size: sizeof(aTimestamp), format: TimestampFormat::NOSPACE);
59 EXPECT_STREQ(aTimestamp, "2012-02-29_13-00-00");
60
61 str_timestamp_ex(time: 1084644833, buffer: aTimestamp, buffer_size: sizeof(aTimestamp), format: TimestampFormat::SPACE);
62 EXPECT_STREQ(aTimestamp, "2004-05-15 18:13:53");
63}
64