Test.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include <cstring>
  2. #include <fstream>
  3. #include <iostream>
  4. #include <dirent.h>
  5. #include "test/Test.h"
  6. #include "tokenizer/TokenStream.h"
  7. #include "tokenizer/Tokenizer.h"
  8. #include "utils/String.h"
  9. static unsigned int done = 0;
  10. static unsigned int tests = 0;
  11. static bool checkPath(const String& path, const char* ending, bool (*f)(const String&, const String&)) {
  12. DIR* dir = opendir(path);
  13. if(dir == nullptr) {
  14. std::cout << "cannot open '" << path << "': " << strerror(errno) << "\n";
  15. return true;
  16. }
  17. while(true) {
  18. struct dirent* entry = readdir(dir);
  19. if(entry == nullptr) {
  20. break;
  21. } else if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
  22. continue;
  23. } else if(entry->d_type == DT_DIR) {
  24. checkPath(path + "/" + entry->d_name, ending, f);
  25. } else if(entry->d_type == DT_REG && strchr(entry->d_name, '.') == nullptr) {
  26. if(f(path + "/" + entry->d_name, path + "/" + entry->d_name + ending)) {
  27. return true;
  28. }
  29. }
  30. }
  31. if(closedir(dir)) {
  32. std::cout << "cannot close '" << path << "': " << strerror(errno) << "\n";
  33. return true;
  34. }
  35. return false;
  36. }
  37. static String readLine(std::ifstream& f) {
  38. String s;
  39. while(true) {
  40. char c = f.get();
  41. if(!f.good() || c == '\n') {
  42. break;
  43. }
  44. s += c;
  45. }
  46. return s;
  47. }
  48. static bool testTokenizer(const String& input, const String& output) {
  49. tests++;
  50. std::ifstream oStream;
  51. oStream.open(output);
  52. if(!oStream.good()) {
  53. std::cout << "cannot open file '" << output << "'\n";
  54. return true;
  55. }
  56. TokenStream tokenStream;
  57. if(Tokenizer::tokenize(tokenStream, input)) {
  58. return true;
  59. }
  60. while(true) {
  61. String expected = readLine(oStream);
  62. if(expected.getLength() == 0) {
  63. break;
  64. } else if(!tokenStream.hasToken()) {
  65. std::cout << "error in '" << input << "\n'out of tokens\n";
  66. return false;
  67. }
  68. String buffer = tokenStream.nextTokenString();
  69. if(strchr(buffer, '\n') != nullptr) {
  70. expected += '\n';
  71. expected += readLine(oStream);
  72. }
  73. if(strcmp(buffer, expected) != 0) {
  74. std::cout << "error in '" << input << "\n'" << buffer << "' should be '" << expected << "'\n";
  75. return false;
  76. }
  77. }
  78. done++;
  79. return false;
  80. }
  81. static void startTokenizerTests(const char* path) {
  82. done = 0;
  83. tests = 0;
  84. checkPath(path, ".tout", testTokenizer);
  85. std::cout << done << " / " << tests << " tokenizer tests succeeded\n";
  86. }
  87. void Test::start(const char* path) {
  88. startTokenizerTests(path);
  89. }