time_test.cpp revision f04935c85e0b466f0d30d2cd4c0fa2fff62e7d6d
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <sys/cdefs.h>
18#include <features.h>
19#include <gtest/gtest.h>
20
21#include <time.h>
22
23#if defined(__BIONIC__) // mktime_tz is a bionic extension.
24#include <libc/private/bionic_time.h>
25#endif // __BIONIC__
26
27TEST(time, mktime_tz) {
28#if defined(__BIONIC__)
29  struct tm epoch;
30  memset(&epoch, 0, sizeof(tm));
31  epoch.tm_year = 1970 - 1900;
32  epoch.tm_mon = 1;
33  epoch.tm_mday = 1;
34
35  // Alphabetically first. Coincidentally equivalent to UTC.
36  ASSERT_EQ(2678400, mktime_tz(&epoch, "Africa/Abidjan"));
37
38  // Alphabetically last. Coincidentally equivalent to UTC.
39  ASSERT_EQ(2678400, mktime_tz(&epoch, "Zulu"));
40
41  // Somewhere in the middle, not UTC.
42  ASSERT_EQ(2707200, mktime_tz(&epoch, "America/Los_Angeles"));
43
44  // Missing. Falls back to UTC.
45  ASSERT_EQ(2678400, mktime_tz(&epoch, "PST"));
46#else // __BIONIC__
47  GTEST_LOG_(INFO) << "This test does nothing.\n";
48#endif // __BIONIC__
49}
50
51TEST(time, gmtime) {
52  time_t t = 0;
53  tm* broken_down = gmtime(&t);
54  ASSERT_TRUE(broken_down != NULL);
55  ASSERT_EQ(0, broken_down->tm_sec);
56  ASSERT_EQ(0, broken_down->tm_min);
57  ASSERT_EQ(0, broken_down->tm_hour);
58  ASSERT_EQ(1, broken_down->tm_mday);
59  ASSERT_EQ(0, broken_down->tm_mon);
60  ASSERT_EQ(1970, broken_down->tm_year + 1900);
61}
62
63TEST(time, mktime_10310929) {
64  struct tm t;
65  memset(&t, 0, sizeof(tm));
66  t.tm_year = 200;
67  t.tm_mon = 2;
68  t.tm_mday = 10;
69
70#if !defined(__LP64__)
71  // 32-bit bionic stupidly had a signed 32-bit time_t.
72  ASSERT_EQ(-1, mktime(&t));
73#if defined(__BIONIC__)
74  ASSERT_EQ(-1, mktime_tz(&t, "UTC"));
75#endif
76#else
77  // Everyone else should be using a signed 64-bit time_t.
78  ASSERT_GE(sizeof(time_t) * 8, 64U);
79
80  setenv("TZ", "America/Los_Angeles", 1);
81  tzset();
82  ASSERT_EQ(static_cast<time_t>(4108348800U), mktime(&t));
83#if defined(__BIONIC__)
84  ASSERT_EQ(static_cast<time_t>(4108320000U), mktime_tz(&t, "UTC"));
85#endif
86
87  setenv("TZ", "UTC", 1);
88  tzset();
89  ASSERT_EQ(static_cast<time_t>(4108320000U), mktime(&t));
90#if defined(__BIONIC__)
91  ASSERT_EQ(static_cast<time_t>(4108348800U), mktime_tz(&t, "America/Los_Angeles"));
92#endif
93#endif
94}
95