Caffe2 - C++ API
A deep learning, cross platform ML framework
test_assert.h
1 #pragma once
2 #include <stdexcept>
3 #include <stdarg.h>
4 
5 static inline void barf(const char *fmt, ...) {
6  char msg[2048];
7  va_list args;
8  va_start(args, fmt);
9  vsnprintf(msg, 2048, fmt, args);
10  va_end(args);
11  throw std::runtime_error(msg);
12 }
13 
14 #if defined(_MSC_VER) && _MSC_VER <= 1900
15 #define __func__ __FUNCTION__
16 #endif
17 
18 #if defined(__GNUC__) || defined(__ICL) || defined(__clang__)
19 #define AT_EXPECT(x, y) (__builtin_expect((x),(y)))
20 #else
21 #define AT_EXPECT(x, y) (x)
22 #endif
23 
24 #define ASSERT(cond) \
25  if (AT_EXPECT(!(cond), 0)) { \
26  barf("%s:%u: %s: Assertion `%s` failed.", __FILE__, __LINE__, __func__, #cond); \
27  }
28 
29 //note: msg must be a string literal
30 //node: In, ##__VA_ARGS '##' supresses the comma if __VA_ARGS__ is empty
31 #define ASSERTM(cond, msg, ...) \
32  if (AT_EXPECT(!(cond), 0)) { \
33  barf("%s:%u: %s: Assertion `%s` failed: " msg , __FILE__, __LINE__, __func__, #cond,##__VA_ARGS__); \
34  }
35 
36 #define TRY_CATCH_ELSE(fn, catc, els) \
37  { \
38  /* avoid mistakenly passing if els code throws exception*/ \
39  bool _passed = false; \
40  try { \
41  fn; \
42  _passed = true; \
43  els; \
44  } catch (const std::exception &e) { \
45  ASSERT(!_passed); \
46  catc; \
47  } \
48  }
49 
50 #define ASSERT_THROWSM(fn, message) \
51  TRY_CATCH_ELSE(fn, ASSERT(std::string(e.what()).find(message) != std::string::npos), ASSERT(false))
52 
53 #define ASSERT_THROWS(fn) \
54  ASSERT_THROWSM(fn, "");
55 
56 #define ASSERT_EQUAL(t1, t2) \
57  ASSERT(t1.equal(t2));
58 
59 // allclose broadcasts, so check same size before allclose.
60 #define ASSERT_ALLCLOSE(t1, t2) \
61  ASSERT(t1.is_same_size(t2)); \
62  ASSERT(t1.allclose(t2));
63 
64 // allclose broadcasts, so check same size before allclose.
65 #define ASSERT_ALLCLOSE_TOLERANCES(t1, t2, atol, rtol) \
66  ASSERT(t1.is_same_size(t2)); \
67  ASSERT(t1.allclose(t2, atol, rtol));