test.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #ifndef _TEST_H_
  2. #define _TEST_H_
  3. #include <string>
  4. #include <vector>
  5. #include <map>
  6. #include <functional>
  7. #include <cstdlib>
  8. #include <iostream>
  9. struct test {
  10. std::string name;
  11. std::function<void()> f;
  12. };
  13. std::vector<test> tests;
  14. struct test_holder {
  15. test_holder(const test& t) {
  16. tests.push_back(t);
  17. }
  18. };
  19. #define TEST(f) \
  20. void test_##f(); \
  21. test test_item##f = {#f, test_##f}; \
  22. test_holder test_holder##f(test_item##f); \
  23. void test_##f() \
  24. #ifdef _MSC_VER
  25. # define TEST_NORETURN __declspec(noreturn)
  26. #elif defined __GNUC__
  27. # define TEST_NORETURN __attribute__ ((noreturn))
  28. #else
  29. # define TEST_NORETURN
  30. #endif
  31. TEST_NORETURN void error(std::string message) {
  32. std::cout << "ERROR: " << message << std::endl;
  33. exit(1);
  34. }
  35. void ensure_exit(int exit_code, std::function<void()> f) {
  36. try {
  37. f();
  38. } catch (exit_exception& e) {
  39. if (e.getExitCode() != exit_code) {
  40. error("Expected exit code " + std::to_string(exit_code) + " but found " + std::to_string(e.getExitCode()));
  41. } else
  42. return;
  43. } catch (...) {
  44. error("Expected exit_exception, but got other exception");
  45. }
  46. error("Expected exit_exception, but not exception got");
  47. }
  48. void run_tests() {
  49. for (const auto& t: tests) {
  50. std::string title = "Running test '" + t.name + "'";
  51. while (title.length() < 100)
  52. title += ' ';
  53. std::cout << title;
  54. try {
  55. t.f();
  56. } catch (exit_exception& e) {
  57. error("Teslib exited with code " + std::to_string(e.getExitCode()));
  58. } catch (...) {
  59. error("Unexpected exception");
  60. std::exit(1);
  61. }
  62. std::cout << "OK" << std::endl;
  63. }
  64. std::cout << std::endl << "SUCCESS " << tests.size() << " tests passed." << std::endl;
  65. }
  66. #endif