Serenity Operating System
at master 121 lines 2.6 kB view raw
1/* 2 * Copyright (c) 2021, Brian Gianforcaro <bgianf@serenityos.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <AK/StringView.h> 8#include <LibTest/TestCase.h> 9#include <time.h> 10 11auto const expected_epoch = "Thu Jan 1 00:00:00 1970\n"sv; 12 13class TimeZoneGuard { 14public: 15 TimeZoneGuard() 16 : m_tz(getenv("TZ")) 17 { 18 } 19 20 explicit TimeZoneGuard(char const* tz) 21 : m_tz(getenv("TZ")) 22 { 23 setenv("TZ", tz, 1); 24 } 25 26 ~TimeZoneGuard() 27 { 28 if (m_tz) 29 setenv("TZ", m_tz, 1); 30 else 31 unsetenv("TZ"); 32 } 33 34private: 35 char const* m_tz { nullptr }; 36}; 37 38TEST_CASE(asctime) 39{ 40 TimeZoneGuard guard("UTC"); 41 42 time_t epoch = 0; 43 auto result = asctime(localtime(&epoch)); 44 EXPECT_EQ(expected_epoch, StringView(result, strlen(result))); 45} 46 47TEST_CASE(asctime_r) 48{ 49 TimeZoneGuard guard("UTC"); 50 51 char buffer[26] {}; 52 time_t epoch = 0; 53 auto result = asctime_r(localtime(&epoch), buffer); 54 EXPECT_EQ(expected_epoch, StringView(result, strlen(result))); 55} 56 57TEST_CASE(ctime) 58{ 59 TimeZoneGuard guard("UTC"); 60 61 time_t epoch = 0; 62 auto result = ctime(&epoch); 63 64 EXPECT_EQ(expected_epoch, StringView(result, strlen(result))); 65} 66 67TEST_CASE(ctime_r) 68{ 69 TimeZoneGuard guard("UTC"); 70 71 char buffer[26] {}; 72 time_t epoch = 0; 73 auto result = ctime_r(&epoch, buffer); 74 75 EXPECT_EQ(expected_epoch, StringView(result, strlen(result))); 76} 77 78TEST_CASE(tzset) 79{ 80 TimeZoneGuard guard; 81 82 auto set_tz = [](char const* tz) { 83 setenv("TZ", tz, 1); 84 tzset(); 85 }; 86 87 set_tz("UTC"); 88 EXPECT_EQ(timezone, 0); 89 EXPECT_EQ(altzone, 0); 90 EXPECT_EQ(daylight, 0); 91 EXPECT_EQ(tzname[0], "UTC"sv); 92 EXPECT_EQ(tzname[1], "UTC"sv); 93 94 set_tz("America/New_York"); 95 EXPECT_EQ(timezone, 5 * 60 * 60); 96 EXPECT_EQ(altzone, 4 * 60 * 60); 97 EXPECT_EQ(daylight, 1); 98 EXPECT_EQ(tzname[0], "EST"sv); 99 EXPECT_EQ(tzname[1], "EDT"sv); 100 101 set_tz("America/Phoenix"); 102 EXPECT_EQ(timezone, 7 * 60 * 60); 103 EXPECT_EQ(altzone, 7 * 60 * 60); 104 EXPECT_EQ(daylight, 0); 105 EXPECT_EQ(tzname[0], "MST"sv); 106 EXPECT_EQ(tzname[1], "MST"sv); 107 108 set_tz("America/Asuncion"); 109 EXPECT_EQ(timezone, 4 * 60 * 60); 110 EXPECT_EQ(altzone, 3 * 60 * 60); 111 EXPECT_EQ(daylight, 1); 112 EXPECT_EQ(tzname[0], "-04"sv); 113 EXPECT_EQ(tzname[1], "-03"sv); 114 115 set_tz("CET"); 116 EXPECT_EQ(timezone, -1 * 60 * 60); 117 EXPECT_EQ(altzone, -2 * 60 * 60); 118 EXPECT_EQ(daylight, 1); 119 EXPECT_EQ(tzname[0], "CET"sv); 120 EXPECT_EQ(tzname[1], "CEST"sv); 121}