Project 2 - Fixed-Point Number Class
test.hpp
1 #ifndef TEST_HPP_
2 #define TEST_HPP_
3 
4 #include <exception>
5 #include <iostream>
6 #include <ostream>
7 
8 // For internal use by the test() macro.
9 // Turn the macro argument into a character string literal
10 #define TEST_STRINGIFY(x) #x
11 
12 // For internal use by the test() macro.
13 // Report a test failure.
14 inline void test_failed(char const* expr, char const* file, int line)
15 {
16  std::cerr << file << ", line " << line << ": test failed: " << expr << '\n';
17 }
18 
19 // For internal use by the test() macro
20 // Run a test. Report a failure if the condition is false or
21 inline void test_run(bool condition, char const* expr, char const* file, int line)
22 {
23  if (not condition)
24  test_failed(expr, file, line);
25 }
26 
27 // For internal use by the test() macro.
28 // Report an exception.
29 inline void test_exception(std::exception const& ex, char const* expr, char const* file, int line)
30 {
31  std::string msg{ expr };
32  msg += " threw an exception: ";
33  msg += ex.what();
34  test_failed(msg.c_str(), file, line);
35 }
36 
45 #define TEST(x) \
46 try {\
47  test_run(x, TEST_STRINGIFY(x), __FILE__, __LINE__);\
48 }\
49 catch(std::exception const& ex)\
50 {\
51  test_exception(ex, TEST_STRINGIFY(x), __FILE__, __LINE__);\
52 }
53 
54 #endif