test.hpp 1.78 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <iostream>

Paul's avatar
Paul committed
7
8
#ifndef GUARD_TEST_TEST_HPP
#define GUARD_TEST_TEST_HPP
Paul's avatar
Paul committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

inline void failed(const char* msg, const char* file, int line)
{
    std::cout << "FAILED: " << msg << ": " << file << ": " << line << std::endl;
}

[[gnu::noreturn]] inline void failed_abort(const char* msg, const char* file, int line)
{
    failed(msg, file, line);
    std::abort();
}

template <class TLeft, class TRight>
inline void expect_equality(const TLeft& left,
                            const TRight& right,
                            const char* left_s,
                            const char* riglt_s,
                            const char* file,
                            int line)
{
    if(left == right)
        return;

    std::cout << "FAILED: " << left_s << "(" << left << ") == " << riglt_s << "(" << right
              << "): " << file << ':' << line << std::endl;
    std::abort();
}

#define CHECK(...)     \
    if(!(__VA_ARGS__)) \
    failed(#__VA_ARGS__, __FILE__, __LINE__)
#define EXPECT(...)    \
    if(!(__VA_ARGS__)) \
    failed_abort(#__VA_ARGS__, __FILE__, __LINE__)
#define EXPECT_EQUAL(LEFT, RIGHT) expect_equality(LEFT, RIGHT, #LEFT, #RIGHT, __FILE__, __LINE__)
#define STATUS(...) EXPECT((__VA_ARGS__) == 0)

#define FAIL(...) failed(__VA_ARGS__, __FILE__, __LINE__)

template <class F>
bool throws(F f)
{
    try
    {
        f();
        return false;
    }
    catch(...)
    {
        return true;
    }
}

template <class F, class Exception>
bool throws(F f, std::string msg = "")
{
    try
    {
        f();
        return false;
    }
    catch(const Exception& ex)
    {
        return std::string(ex.what()).find(msg) != std::string::npos;
    }
}

template <class T>
void run_test()
{
    T t = {};
    t.run();
}

#endif