ctype.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "test.h"
  2. #include <stdio.h>
  3. #include <ctype.h>
  4. #include <limits.h>
  5. #define UPPER "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  6. #define LOWER "abcdefghijklmnopqrstuvwxyz"
  7. #define DIGIT "0123456789"
  8. #define HEX DIGIT "ABCDEFabcdef"
  9. #define CNTRL "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" \
  10. "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f"
  11. #define PUNCT "`~!@#$%^&*()_+-=[]\\{}|;':\",./<>?"
  12. #define GRAPH UPPER LOWER DIGIT PUNCT
  13. #define PRINT GRAPH " "
  14. #define SPACE " \f\n\r\t\v"
  15. #define test_ctype_function(fn, ex) test_ctype_function_imp(#fn, fn, ex, sizeof(ex))
  16. #define test_ctype_conversion(fn, from, to) test_ctype_conversion_imp(#fn, fn, from, to)
  17. static int is_expected(int n, const char *expected, size_t len)
  18. {
  19. size_t i;
  20. for (i = 0; i < len - 1; i++) {
  21. if (expected[i] == n) {
  22. return 1;
  23. }
  24. }
  25. return 0;
  26. }
  27. static void test_ctype_function_imp(const char *fnname, int (*fn)(int), const char *expected, size_t len)
  28. {
  29. char expression[64];
  30. int i;
  31. for (i = 0; i < UCHAR_MAX; i++) {
  32. sprintf(expression, "%s(%d)", fnname, i);
  33. test_bool_imp(expression, fn(i), is_expected(i, expected, len));
  34. }
  35. sprintf(expression, "%s(EOF)", fnname);
  36. test_bool_imp(expression, fn(EOF), 0);
  37. }
  38. static int convert(const char *from, const char *to, int n)
  39. {
  40. size_t i;
  41. for (i = 0; from[i] != '\0'; i++) {
  42. if (from[i] == n) {
  43. return to[i];
  44. }
  45. }
  46. return n;
  47. }
  48. static void test_ctype_conversion_imp(const char *fnname, int (*fn)(int), const char *from, const char *to)
  49. {
  50. char expression[64];
  51. int i;
  52. for (i = 0; i < UCHAR_MAX; i++) {
  53. int j = convert(from, to, i);
  54. sprintf(expression, "%s(%d)", fnname, i);
  55. test_int_equals_imp(expression, fn(i), j);
  56. }
  57. sprintf(expression, "%s(EOF)", fnname);
  58. test_int_equals_imp(expression, fn(EOF), EOF);
  59. }
  60. void test_ctype_h(void)
  61. {
  62. testing_header("ctype.h");
  63. test_ctype_function(isalnum, UPPER LOWER DIGIT);
  64. test_ctype_function(isalpha, UPPER LOWER);
  65. test_ctype_function(iscntrl, CNTRL);
  66. test_ctype_function(isdigit, DIGIT);
  67. test_ctype_function(isgraph, GRAPH);
  68. test_ctype_function(islower, LOWER);
  69. test_ctype_function(isprint, PRINT);
  70. test_ctype_function(ispunct, PUNCT);
  71. test_ctype_function(isspace, SPACE);
  72. test_ctype_function(isupper, UPPER);
  73. test_ctype_function(isxdigit, HEX);
  74. test_ctype_conversion(tolower, UPPER, LOWER);
  75. test_ctype_conversion(toupper, LOWER, UPPER);
  76. testing_end();
  77. }