Skip to content

Instantly share code, notes, and snippets.

@linuskmr
Last active September 20, 2022 17:26
Show Gist options
  • Save linuskmr/cdf36b4a97954464732a17b2213dbd3d to your computer and use it in GitHub Desktop.
Save linuskmr/cdf36b4a97954464732a17b2213dbd3d to your computer and use it in GitHub Desktop.
Simple Testrunner for C++
#include <iostream>
#include <cassert>
#include <vector>
#include <functional>
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
void test_ok() {
std::cout << "bla" << std::endl;
assert(1 == 1);
}
void test_fail() {
assert(1 == 2);
}
struct Test {
std::string name;
std::function<void()> function;
};
constexpr char const * const OK = "\033[32m[OK]\033[0m";
constexpr char const * const FAIL = "\033[31m[FAIL]\033[0m";
int main() {
std::vector<Test> tests = {
{.name = "test_ok", .function = test_ok},
{.name = "test_fail", .function = test_fail}
};
for (auto const & test : tests) {
std::cout << "\033[34mRunning test '" << test.name << "'\033[0m" << std::endl;
pid_t pid = fork();
if (pid == -1) {
std::cerr << "fork failed" << std::endl;
return 1;
} else if (pid == 0) {
// Child process
test.function();
return 0;
} else {
// Parent process
// Wait until child finishes
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
// Child exited normally
if (WEXITSTATUS(status) == 0) {
// Child exited with status 0
std::cout << OK << std::endl;
} else {
// Child exited with non-zero status
std::cout << FAIL << " exit_code = " << WEXITSTATUS(status) << std::endl;
}
} else {
// Child exited abnormally
if (WIFSIGNALED(status)) {
int const signal = WTERMSIG(status);
std::cout << FAIL << " signal = " << signal << " (" << strsignal(signal) << ")" << std::endl;
} else {
std::cout << FAIL << std::endl;
}
}
}
std::cout << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment