Advertisement
Argentum_02

test_runner.h

Apr 9th, 2019
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <sstream>
  4. #include <stdexcept>
  5. #include <string>
  6. #include <vector>
  7. #include <iostream>
  8. #include <set>
  9. #include <map>
  10.  
  11. using namespace std;
  12.  
  13. template <class T>
  14. ostream& operator << (ostream& os, const vector<T>& s) {
  15.   os << "{";
  16.   bool first = true;
  17.   for (const auto& x : s) {
  18.     if (!first) {
  19.       os << ", ";
  20.     }
  21.     first = false;
  22.     os << x;
  23.   }
  24.   return os << "}";
  25. }
  26.  
  27. template <class T>
  28. ostream& operator << (ostream& os, const set<T>& s) {
  29.   os << "{";
  30.   bool first = true;
  31.   for (const auto& x : s) {
  32.     if (!first) {
  33.       os << ", ";
  34.     }
  35.     first = false;
  36.     os << x;
  37.   }
  38.   return os << "}";
  39. }
  40.  
  41. template <class K, class V>
  42. ostream& operator << (ostream& os, const map<K, V>& m) {
  43.   os << "{";
  44.   bool first = true;
  45.   for (const auto& kv : m) {
  46.     if (!first) {
  47.       os << ", ";
  48.     }
  49.     first = false;
  50.     os << kv.first << ": " << kv.second;
  51.   }
  52.   return os << "}";
  53. }
  54.  
  55.  
  56.  
  57. template<class T, class U>
  58. void AssertEqual(const T& t, const U& u, const string& hint = {}) {
  59.   if (t != u) {
  60.     ostringstream os;
  61.     os << "Assertion failed: " << t << " != " << u;
  62.     if (!hint.empty()) {
  63.       os << " hint: " << hint;
  64.     }
  65.     throw runtime_error(os.str());
  66.   }
  67. }
  68.  
  69.  
  70.  
  71. class TestRunner {
  72. public:
  73.   template <class TestFunc>
  74.   void RunTest(TestFunc func, const string& test_name) {
  75.     try {
  76.       func();
  77.       cerr << test_name << " OK" << endl;
  78.     } catch (exception& e) {
  79.       ++fail_count;
  80.       cerr << test_name << " fail: " << e.what() << endl;
  81.     } catch (...) {
  82.       ++fail_count;
  83.       cerr << "Unknown exception caught" << endl;
  84.     }
  85.   }
  86.  
  87.   ~TestRunner() {
  88.     if (fail_count > 0) {
  89.       cerr << fail_count << " unit tests failed. Terminate" << endl;
  90.       exit(1);
  91.     }
  92.   }
  93.  
  94. private:
  95.   int fail_count = 0;
  96. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement