projects/linux·blob master · refs

102 lines · 2.2 KiB

1// SPDX-License-Identifier: LGPL-2.1+
2
3#include <kunit/test.h>
4#include <linux/time.h>
5
6/*
7 * Traditional implementation of leap year evaluation, but note that long
8 * is a signed type and the tests do cover negative year values. So this
9 * can't use the is_leap_year() helper from rtc.h.
10 */
11static bool is_leap(long year)
12{
13 return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
14}
15
16/*
17 * Gets the last day of a month.
18 */
19static int last_day_of_month(long year, int month)
20{
21 if (month == 2)
22 return 28 + is_leap(year);
23 if (month == 4 || month == 6 || month == 9 || month == 11)
24 return 30;
25 return 31;
26}
27
28/*
29 * Advances a date by one day.
30 */
31static void advance_date(long *year, int *month, int *mday, int *yday)
32{
33 if (*mday != last_day_of_month(*year, *month)) {
34 ++*mday;
35 ++*yday;
36 return;
37 }
38
39 *mday = 1;
40 if (*month != 12) {
41 ++*month;
42 ++*yday;
43 return;
44 }
45
46 *month = 1;
47 *yday = 0;
48 ++*year;
49}
50
51/*
52 * Checks every day in a 160000 years interval centered at 1970-01-01
53 * against the expected result.
54 */
55static void time64_to_tm_test_date_range(struct kunit *test)
56{
57 /*
58 * 80000 years = (80000 / 400) * 400 years
59 * = (80000 / 400) * 146097 days
60 * = (80000 / 400) * 146097 * 86400 seconds
61 */
62 time64_t total_secs = ((time64_t) 80000) / 400 * 146097 * 86400;
63 long year = 1970 - 80000;
64 int month = 1;
65 int mdday = 1;
66 int yday = 0;
67
68 struct tm result;
69 time64_t secs;
70 s64 days;
71
72 for (secs = -total_secs; secs <= total_secs; secs += 86400) {
73
74 time64_to_tm(secs, 0, &result);
75
76 days = div_s64(secs, 86400);
77
78 #define FAIL_MSG "%05ld/%02d/%02d (%2d) : %lld", \
79 year, month, mdday, yday, days
80
81 KUNIT_ASSERT_EQ_MSG(test, year - 1900, result.tm_year, FAIL_MSG);
82 KUNIT_ASSERT_EQ_MSG(test, month - 1, result.tm_mon, FAIL_MSG);
83 KUNIT_ASSERT_EQ_MSG(test, mdday, result.tm_mday, FAIL_MSG);
84 KUNIT_ASSERT_EQ_MSG(test, yday, result.tm_yday, FAIL_MSG);
85
86 advance_date(&year, &month, &mdday, &yday);
87 }
88}
89
90static struct kunit_case time_test_cases[] = {
91 KUNIT_CASE_SLOW(time64_to_tm_test_date_range),
92 {}
93};
94
95static struct kunit_suite time_test_suite = {
96 .name = "time_test_cases",
97 .test_cases = time_test_cases,
98};
99
100kunit_test_suite(time_test_suite);
101MODULE_DESCRIPTION("time unit test suite");
102MODULE_LICENSE("GPL");