Advertisement
chzchz

Untitled

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