tst-strftime.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5. static struct
  6. {
  7. const char *fmt;
  8. size_t min;
  9. size_t max;
  10. } tests[] =
  11. {
  12. { "%2000Y", 2000, 4000 },
  13. { "%02000Y", 2000, 4000 },
  14. { "%_2000Y", 2000, 4000 },
  15. { "%-2000Y", 2000, 4000 },
  16. };
  17. #define ntests (sizeof (tests) / sizeof (tests[0]))
  18. static int
  19. do_test (void)
  20. {
  21. size_t cnt;
  22. int result = 0;
  23. time_t tnow = time (NULL);
  24. struct tm *now = localtime (&tnow);
  25. for (cnt = 0; cnt < ntests; ++cnt)
  26. {
  27. size_t size = 0;
  28. int res;
  29. char *buf = NULL;
  30. do
  31. {
  32. size += 500;
  33. buf = (char *) realloc (buf, size);
  34. if (buf == NULL)
  35. {
  36. puts ("out of memory");
  37. exit (1);
  38. }
  39. res = strftime (buf, size, tests[cnt].fmt, now);
  40. if (res != 0)
  41. break;
  42. }
  43. while (size < tests[cnt].max);
  44. if (res == 0)
  45. {
  46. printf ("%Zu: %s: res == 0 despite size == %Zu\n",
  47. cnt, tests[cnt].fmt, size);
  48. result = 1;
  49. }
  50. else if (size < tests[cnt].min)
  51. {
  52. printf ("%Zu: %s: size == %Zu was enough\n",
  53. cnt, tests[cnt].fmt, size);
  54. result = 1;
  55. }
  56. else
  57. printf ("%Zu: %s: size == %Zu: OK\n", cnt, tests[cnt].fmt, size);
  58. free (buf);
  59. }
  60. struct tm ttm =
  61. {
  62. /* Initialize the fields which are needed in the tests. */
  63. .tm_mday = 1,
  64. .tm_hour = 2
  65. };
  66. const struct
  67. {
  68. const char *fmt;
  69. const char *exp;
  70. size_t n;
  71. } ftests[] =
  72. {
  73. { "%-e", "1", 1 },
  74. { "%-k", "2", 1 },
  75. { "%-l", "2", 1 },
  76. };
  77. #define nftests (sizeof (ftests) / sizeof (ftests[0]))
  78. for (cnt = 0; cnt < nftests; ++cnt)
  79. {
  80. char buf[100];
  81. size_t r = strftime (buf, sizeof (buf), ftests[cnt].fmt, &ttm);
  82. if (r != ftests[cnt].n)
  83. {
  84. printf ("strftime(\"%s\") returned %zu not %zu\n",
  85. ftests[cnt].fmt, r, ftests[cnt].n);
  86. result = 1;
  87. }
  88. if (strcmp (buf, ftests[cnt].exp) != 0)
  89. {
  90. printf ("strftime(\"%s\") produced \"%s\" not \"%s\"\n",
  91. ftests[cnt].fmt, buf, ftests[cnt].exp);
  92. result = 1;
  93. }
  94. }
  95. return result;
  96. }
  97. #define TEST_FUNCTION do_test ()
  98. #include "../test-skeleton.c"