Advertisement
Guest User

Untitled

a guest
Jan 31st, 2015
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #include <string>
  2. #include <stdexcept>
  3. #include <cstdlib>
  4. #include <iomanip>
  5. #include <iostream>
  6.  
  7. #define TEST_CASE(x) #x, x
  8.  
  9. namespace test{
  10.  
  11. //function pointer to run as a test
  12. using test_function = void (*)(void);
  13.  
  14. struct suite {
  15. public:
  16. //initializes the test suite
  17. explicit suite(const std::string& test_suite_name): failed(0) {
  18. std::cout << "=== Testing " << test_suite_name << " ===" << std::endl;
  19. }
  20. //run the test
  21. void test(const std::string& test_name, test_function function) {
  22. std::cout << std::setw(32) << test_name << std::flush;
  23. try {
  24. //run the test
  25. function();
  26. //it didnt throw
  27. std::cout << " [PASS]" << std::endl;
  28. }//it threw so log the issue
  29. catch (const std::exception& e) {
  30. std::cout << " [FAIL: " << e.what() << "]" << std::endl;
  31. ++failed;
  32. }//it threw something that wasn't derived from std::exception?
  33. catch (...) {
  34. std::cerr << " [FAIL: Unexpected error]" << std::endl;
  35. throw;
  36. }
  37. }
  38. //returns EXIT_FAILURE if any tests failed otherwise returns EXIT_SUCCESS
  39. int tear_down() {
  40. std::cout << "=== Failed " << failed << " tests ===" << std::endl;
  41. if(failed > 0)
  42. return EXIT_FAILURE;
  43. else
  44. return EXIT_SUCCESS;
  45. }
  46.  
  47. private:
  48. //number of failed tests
  49. size_t failed;
  50. };
  51.  
  52. }
  53.  
  54. namespace {
  55.  
  56. void passing_test() {
  57. //we didn't throw an unhandled exception
  58. //therefore we pass
  59. }
  60.  
  61. void failing_test() {
  62. //this will bomb the test
  63. throw std::runtime_error("You've found a failing test");
  64. }
  65.  
  66. }
  67.  
  68. int main() {
  69. test::suite suite("sample_test_suite");
  70.  
  71. //run each test
  72. suite.test(TEST_CASE(passing_test));
  73. suite.test(TEST_CASE(failing_test));
  74.  
  75. return suite.tear_down();
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement