#define _POSIX_C_SOURCE 1 #include #include #include #include #include #include #include "../src/Colors.h" static bool endsWith(const char* s, const char* end) { size_t a = strlen(s); size_t b = strlen(end); if(a < b) { return false; } return strcmp(s + (a - b), end) == 0; } static void printTests() { const char* path = "./test"; DIR* d = opendir(path); if(d == nullptr) { return; } while(true) { struct dirent* file = readdir(d); if(file == nullptr) { break; } if(endsWith(file->d_name, ".basic")) { printf("%s/%s\n", path, file->d_name); } } closedir(d); } static void printUntilNewline(const char* s) { while(*s != '\n' && *s != '\0') { putchar(*(s++)); } } static void compareStreams(FILE* file, FILE* result) { bool diff = false; int line = 0; while(true) { line++; char bufferA[256] = {}; char bufferB[256] = {}; char* r1 = fgets(bufferA, sizeof(bufferA), file); char* r2 = fgets(bufferB, sizeof(bufferB), result); if(r1 == nullptr && r2 == nullptr) { break; } if(strcmp(bufferA, bufferB) != 0) { printf(TC_RED "Line %d differs '", line); printUntilNewline(bufferA); printf("' vs '"); printUntilNewline(bufferB); puts("'" TC_RESET); diff = true; } } if(!diff) { puts(TC_GREEN "Success" TC_RESET); } } int main(int argCount, const char** args) { if(argCount < 2) { return 0; } else if(strcmp(args[1], "help") == 0) { printTests(); return 0; } int fd[2]; if(pipe(fd) == -1) { puts("pipe failed"); return 1; } pid_t f = fork(); if(f == 0) { // child close(fd[0]); dup2(fd[1], STDOUT_FILENO); close(fd[1]); #ifdef NDEBUG const char* path = "./build_release/basic"; #else const char* path = "./build_debug/basic"; #endif execlp(path, path, args[1], (char*)nullptr); puts("execlp failed"); exit(1); } else if(f == -1) { // failure puts("fork failed"); exit(1); } close(fd[1]); char resultPath[256]; snprintf(resultPath, sizeof(resultPath), "%s_result", args[1]); FILE* file = fopen(resultPath, "r"); if(file == nullptr) { printf(TC_RED "'%s' does not exist" TC_RESET "\n", resultPath); return 1; } FILE* result = fdopen(fd[0], "r"); if(result == nullptr) { puts("Cannot map file descriptor"); } else { compareStreams(file, result); fclose(result); } fclose(file); return 1; }