lib_test.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // SPDX-License-Identifier: LGPL-2.1+
  2. #include <kunit/test.h>
  3. #include <linux/rtc.h>
  4. /*
  5. * Advance a date by one day.
  6. */
  7. static void advance_date(int *year, int *month, int *mday, int *yday)
  8. {
  9. if (*mday != rtc_month_days(*month - 1, *year)) {
  10. ++*mday;
  11. ++*yday;
  12. return;
  13. }
  14. *mday = 1;
  15. if (*month != 12) {
  16. ++*month;
  17. ++*yday;
  18. return;
  19. }
  20. *month = 1;
  21. *yday = 1;
  22. ++*year;
  23. }
  24. /*
  25. * Check every day in specified number of years interval starting on 1970-01-01
  26. * against the expected result.
  27. */
  28. static void rtc_time64_to_tm_test_date_range(struct kunit *test, int years)
  29. {
  30. /*
  31. * years = (years / 400) * 400 years
  32. * = (years / 400) * 146097 days
  33. * = (years / 400) * 146097 * 86400 seconds
  34. */
  35. time64_t total_secs = ((time64_t)years) / 400 * 146097 * 86400;
  36. int year = 1970;
  37. int month = 1;
  38. int mday = 1;
  39. int yday = 1;
  40. struct rtc_time result;
  41. time64_t secs;
  42. s64 days;
  43. for (secs = 0; secs <= total_secs; secs += 86400) {
  44. rtc_time64_to_tm(secs, &result);
  45. days = div_s64(secs, 86400);
  46. #define FAIL_MSG "%d/%02d/%02d (%2d) : %lld", \
  47. year, month, mday, yday, days
  48. KUNIT_ASSERT_EQ_MSG(test, year - 1900, result.tm_year, FAIL_MSG);
  49. KUNIT_ASSERT_EQ_MSG(test, month - 1, result.tm_mon, FAIL_MSG);
  50. KUNIT_ASSERT_EQ_MSG(test, mday, result.tm_mday, FAIL_MSG);
  51. KUNIT_ASSERT_EQ_MSG(test, yday, result.tm_yday, FAIL_MSG);
  52. advance_date(&year, &month, &mday, &yday);
  53. }
  54. }
  55. /*
  56. * Checks every day in a 160000 years interval starting on 1970-01-01
  57. * against the expected result.
  58. */
  59. static void rtc_time64_to_tm_test_date_range_160000(struct kunit *test)
  60. {
  61. rtc_time64_to_tm_test_date_range(test, 160000);
  62. }
  63. /*
  64. * Checks every day in a 1000 years interval starting on 1970-01-01
  65. * against the expected result.
  66. */
  67. static void rtc_time64_to_tm_test_date_range_1000(struct kunit *test)
  68. {
  69. rtc_time64_to_tm_test_date_range(test, 1000);
  70. }
  71. static struct kunit_case rtc_lib_test_cases[] = {
  72. KUNIT_CASE(rtc_time64_to_tm_test_date_range_1000),
  73. KUNIT_CASE_SLOW(rtc_time64_to_tm_test_date_range_160000),
  74. {}
  75. };
  76. static struct kunit_suite rtc_lib_test_suite = {
  77. .name = "rtc_lib_test_cases",
  78. .test_cases = rtc_lib_test_cases,
  79. };
  80. kunit_test_suite(rtc_lib_test_suite);
  81. MODULE_DESCRIPTION("KUnit test for RTC lib functions");
  82. MODULE_LICENSE("GPL");