normalize_path.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "api.h"
  2. #include "pal_debug.h"
  3. #include "pal_defs.h"
  4. #include "pal_error.h"
  5. static const char* get_norm_path_cases[][2] = {
  6. {"/", "/"},
  7. {"/a/b/c", "/a/b/c"},
  8. {"/a/../b", "/b"},
  9. {"/../a", "/a"},
  10. {"/../../../../../a", "/a"},
  11. {"/../a/../../b", "/b"},
  12. {"/../..a/b", "/..a/b"},
  13. {"/a/..", "/"},
  14. {"/a/.", "/a"},
  15. {"/.//a//./b", "/a/b"},
  16. {"///////.////////////./", "/"},
  17. {"/...././a/../././.../b/.....", "/..../.../b/....."},
  18. {"a/b/c", "a/b/c"},
  19. {"a/../b", "b"},
  20. {"../a", "../a"},
  21. {"../../../../../a", "../../../../../a"},
  22. {"../a/../../b", "../../b"},
  23. {"../..a/b", "../..a/b"},
  24. {"a/..", ""},
  25. {"a/.", "a"},
  26. };
  27. static const char* get_base_name_cases[][2] = {
  28. {"/", ""}, {"/a", "a"}, {"/a/b/c", "c"}, {"/..a/b", "b"},
  29. {"", ""}, {"../a", "a"}, {"../../../../../a", "a"}, {"..a/b", "b"},
  30. {"a/b/c", "c"},
  31. };
  32. #define print_err(name, i, ...) \
  33. do { \
  34. pal_printf("%s: case %lu (\"%s\") ", name, i, cases[i][0]); \
  35. pal_printf(__VA_ARGS__); \
  36. } while (0)
  37. static const char* (*cases)[2];
  38. static size_t cases_len;
  39. static int (*func_to_test)(const char*, char*, size_t*);
  40. static const char* func_name;
  41. static int run_test(void) {
  42. char buf[URI_MAX] = {0};
  43. for (size_t i = 0; i < cases_len; i++) {
  44. size_t size = sizeof(buf);
  45. int ret = func_to_test(cases[i][0], buf, &size);
  46. if (ret < 0) {
  47. print_err(func_name, i, "failed with error: %s\n", pal_strerror(ret));
  48. return 1;
  49. }
  50. if (strlen(buf) != size) {
  51. print_err(func_name, i, "returned wrong size: %zu\n", size);
  52. return 1;
  53. }
  54. if (strcmp(cases[i][1], buf) != 0) {
  55. print_err(func_name, i, "returned: \"%s\", instead of: \"%s\"\n", buf, cases[i][1]);
  56. return 1;
  57. }
  58. }
  59. return 0;
  60. }
  61. int main(void) {
  62. cases = get_norm_path_cases;
  63. cases_len = ARRAY_SIZE(get_norm_path_cases);
  64. func_to_test = get_norm_path;
  65. func_name = "get_norm_path";
  66. if (run_test()) {
  67. return 1;
  68. }
  69. cases = get_base_name_cases;
  70. cases_len = ARRAY_SIZE(get_base_name_cases);
  71. func_to_test = get_base_name;
  72. func_name = "get_base_name";
  73. if (run_test()) {
  74. return 1;
  75. }
  76. pal_printf("Success!\n");
  77. return 0;
  78. }