summaryrefslogtreecommitdiffstats
path: root/mmc_updater/src/tests/TestUtils.h
blob: 68d97da57b927036f24864a0564b02adb000bd95 (plain)
1
2
3
4
5
6
7
8
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#pragma once

#include <iostream>
#include <functional>
#include <string>
#include <vector>

template <class T>
class TestList
{
	public:
		void addTest(void (T::*test)())
		{
			m_tests.push_back(std::mem_fun(test));
		}

		int size() const
		{
			return m_tests.size();
		}

		void runTest(T* testInstance, int i)
		{
			m_tests.at(i)(testInstance);
		}

	private:
		std::vector<std::mem_fun_t<void,T> > m_tests;
};

class TestUtils
{
	public:
		template <class X, class Y>
		static void compare(const X& x, const Y& y, const char* xString, const char* yString)
		{
			if (x != y)
			{
				throw "Actual and expected values differ.  "
				      "Actual: " + toString(x,xString) +
				      " Expected: " + toString(y,yString);
			}
		}

		template <typename T>
		static std::string toString(T value, const char* context)
		{
			return "Unprintable: " + std::string(context);
		}

		template <class T>
		static int runTest(class TestList<T>& tests) throw ()
		{
			std::string errorText;
			try
			{
				T testInstance;
				for (int i=0; i < tests.size(); i++)
				{
					tests.runTest(&testInstance,i);
				}
			}
			catch (const std::exception& ex)
			{
				errorText = ex.what();
			}
			catch (const std::string& error)
			{
				errorText = error;
			}
			catch (...)
			{
				errorText = "Unknown exception";
			}

			if (errorText.empty())
			{
				std::cout << "Test passed" << std::endl;
				return 0;
			}
			else
			{
				std::cout << "Test failed: " << errorText << std::endl;
				return 1;
			}
		}
};

template <>
inline std::string TestUtils::toString(const std::string& value, const char*)
{
	return value;
}
template <>
inline std::string TestUtils::toString(std::string value, const char*)
{
	return value;
}
template <>
inline std::string TestUtils::toString(const char* value, const char*)
{
	return value;
}

#define TEST_COMPARE(x,y) \
	TestUtils::compare(x,y,#x,#y);