-
Notifications
You must be signed in to change notification settings - Fork 0
/
MiniCppUnit.hpp
502 lines (442 loc) · 14 KB
/
MiniCppUnit.hpp
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/*
* Copyright (c) 2003-2004 Pau Arumí & David García
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef MiniCppUnit_hxx
#define MiniCppUnit_hxx
/**
* @mainpage
* miniCppUnit
* (C) 2003-2006 Pau Arumi & David Garcia
*
* @version 2.5 2006-03-14
* - MS Visual compatibility: SConstruct ccflags, usage example, #ifdefs
* @version 2.4 2006-03-14
* - exit test case after first failure
* - double and float comparison with fuzzy equals (using scalable epsilon)
* - have into account not a numbers
* - new ASSERT_EQUALS_EPSILON macro
* - more colors, and disabled when comiled in MS Visual
* - removed catalan location.
* - UsageExample.cxx now uses all macros and features
* @version 2.3 2006-02-13 added usage example and SConstruct
* @version 2.2 2004-11-28 code in english and tests suites
* @version 2.1 2004-11-04 char* especialization
* @version 2.0 2004-10-26 TestsFactory
* @version 1.0 2003-10-28 initial
*
* Example of use:
*
* @code
* #include "MiniCppUnit.hxx"
* class MyTests : public TestFixture<MyTests>
* {
* public:
* TEST_FIXTURE( MyTests )
* {
* CAS_DE_TEST( testAddition );
* // etc
* }
* void testAddition()
* {
* ASSERT_EQUALS( 4, 1+1+2 );
* }
* // etc
* };
*
* REGISTER_FIXTURE( MyTests );
* @endcode
* @code
* int main()
* {
* return TestFixtureFactory::theInstance().runTests() ? 0 : -1;
* }
* @endcode
* Good things:
*
* - it's a tiny framework made up of two or three src files.
* => no need to install as a library
* - object oriented and makes use of several GoF patterns
* - very simple usage. Just needs to learn very few C macros
* - string asserts are simpler to use than cppunit
* - string asserts are enhanced with coloured diffs
* - concrete test classes are totally decoupled via static factory
* => no src file have to include them all.
* - it have test suite hierarchies
* - compatible with non-standard compliant VisualC6
* (though not necessary good ;)
*/
#include <iostream>
#include <string>
#include <sstream>
#include <list>
#if _MSC_VER && _MSC_VER < 1300
/** necesary for Visual 6 which don't define std::min */
namespace std
{
template<typename T>
min(const T& a, const T& b) { return a < b ? a: b; }
}
#endif
/**
* A singleton class.
* Receives tests results and stores messages to the test log
* for later listing.
* It's a singleton for an easy global access from the 'Asserts'
* methods but it is probably asking for a refactoring in order to limit
* access only to TestFixtures
*/
class TestsListener
{
public:
/** accessor to the global (static) singleton instance */
static TestsListener& theInstance();
std::stringstream& errorsLog();
std::string logString();
void currentTestName( std::string& name);
static void testHasRun();
static void testHasFailed();
static void testHasThrown();
/** the human readable summary of run tests*/
std::string summary();
/** returns wheather all run tests have passed */
static bool allTestsPassed();
private:
static const char* errmsgTag_nameOfTest() { return "Test failed: "; }
/** constructor private: force the singleton to be wellbehaved ! */
TestsListener() : _currentTestName(0)
{
_executed=_failed=_exceptions=0;
}
std::string* _currentTestName;
std::stringstream _log;
unsigned _executed;
unsigned _failed;
unsigned _exceptions;
};
class TestFailedException
{
};
/**
* Abstract class with interface that allows run a test. That is runTest
* and name. It is implemented by TestFixture and TestCase
*
* It does the 'Component' role in the 'Composite' patten
**/
class Test
{
public:
virtual ~Test(){}
/** run the test: exercice the code and check results*/
virtual void runTest() = 0;
/** the test human-readable name */
virtual std::string name() const = 0;
};
/**
* This class is just a placeholder for all assert functions --as static methods.
* It is meant for being used just by the assert macros
*/
class Assert
{
static const char * errmsgTag_testFailedIn() { return "Test failed in "; }
static const char * errmsgTag_inLine() { return ", line: "; };
static const char * errmsgTag_failedExpression() { return "Failed expression: "; }
static const char * errmsgTag_expected() { return "Expected: "; }
static const char * errmsgTag_butWas() { return "But was: "; }
public:
//#ifdef _MSC_VER
static const char * blue() { return ""; }
static const char * green() { return ""; }
static const char * red() { return ""; }
static const char * normal() { return ""; }
static const char * bold() { return ""; }
static const char * yellow() { return ""; }
/*#else
static const char * blue() { return "\033[36;1m"; }
static const char * green() { return "\033[32;1m"; }
static const char * red() { return "\033[31;1m"; }
static const char * normal() { return "\033[0m"; }
static const char * bold() { return "\033[" "1m"; }
static const char * yellow() { return "\033[93;1m"; }
#endif*/
template<typename AType>
static void assertEquals( const AType& expected, const AType& result,
const char* file="", int line=0 )
{
if(expected != result)
{
TestsListener::theInstance().errorsLog()
<< file << ", line: " << line << "\n"
<< errmsgTag_expected() << " " << expected << " "
<< errmsgTag_butWas() << " " << result << "\n";
TestsListener::theInstance().testHasFailed();
}
}
static void assertTrue(const char* strExpression, bool expression,
const char* file="", int line=0);
static void assertTrueMessage(const char* strExpression, bool expression,
const char* missatge, const char* file="", int line =0);
static void assertEquals( const char * expected, const char * result,
const char* file="", int line =0 );
static void assertEquals( const bool& expected, const bool& result,
const char* file="", int line =0 );
static void assertEquals( const double& expected, const double& result,
const char* file="", int line =0 );
static void assertEquals( const float& expected, const float& result,
const char* file="", int line =0 );
static void assertEquals( const long double& expected, const long double& result,
const char* file="", int line =0 );
static void assertEqualsEpsilon( const double& expected, const double& result, const double& epsilon,
const char* file="", int line =0 );
static int notEqualIndex( const std::string & one, const std::string & other );
/**
* we overload the assert with string doing colored diffs
*
* MS Visual6 doesn't allow string by reference :-(
*/
static void assertEquals( const std::string expected, const std::string result,
const char* file="", int line =0 );
static void fail(const char* motiu, const char* file="", int line =0);
};
/**
* A TestFixture is a class that contain TestCases --which corresponds to
* ConcreteTestFixture methods-- common objects uder tests, and setUp and
* tearDown methods which are automatically executed before and after each
* test case.
*
* Is the base class of ConcreteFixtures implemented by the framework user
*
* It does the 'Composite' role in the 'Composite' GoF pattern.
* Its composite children are TestCases, which wrapps the test methods.
*
* It is a template class parametrized by ConcreteTestFixture so that it can
* instantiate TestCase objects templatized with this same parameter: it needs the
* concrete class type for calling its non-static methods.
*/
template <typename ConcreteTestFixture>
class TestFixture : public Test
{
protected:
typedef ConcreteTestFixture ConcreteFixture;
typedef void(ConcreteTestFixture::*TestCaseMethod)();
/**
* Wrapper for the test methods of concrete TestFixtures.
*
* Makes the 'Leave' role in the 'Composite' GoF pattern because can't be
* be a composition of other tests.
*
* It's also a case of 'Command' pattern because it encapsules in an object
* certain functionality whose execution depends on some deferred entity.
*/
class TestCase : public Test
{
public:
TestCase(ConcreteFixture* parent, TestCaseMethod method, const std::string & name) :
_parent(parent),
_testCaseMethod(method),
_name(name)
{
}
/** calls TestFixture method. setUp and tearDown methods are called by
* its parent TestFixture (in its runTest method).
* it is robust to unexpected exceptions (throw) */
void runTest()
{
TestsListener::theInstance().testHasRun();
TestsListener::theInstance().currentTestName(_name);
try
{
(_parent->*_testCaseMethod)();
}
catch( std::exception& error )
{
TestsListener::theInstance().testHasThrown();
TestsListener::theInstance().errorsLog()
<< "std::exception catched by MiniCppUnit: \n"
<< "what() : "
<< Assert::yellow() << error.what()
<< Assert::normal() << "\n";
}
catch ( TestFailedException& ) //just for skiping current test case
{
}
catch(...)
{
TestsListener::theInstance().testHasThrown();
TestsListener::theInstance().errorsLog()
<< "non standard exception catched by MiniCppUnit.\n";
}
}
/** the TestFixture method hame */
std::string name() const
{
return _name;
}
private:
ConcreteFixture* _parent;
TestCaseMethod _testCaseMethod;
std::string _name;
};
//------------- end of class TestCase ----------------------------
private:
typedef std::list<Test*> TestCases;
TestCases _testCases;
std::string _name;
void testsList() const
{
std::cout << "\n+ " << name() << "\n";
for( TestCases::const_iterator it=_testCases.begin();
it!=_testCases.end(); it++ )
std::cout << " - "<< (*it)->name() << "\n";
}
public:
virtual void setUp() {}
virtual void tearDown() {}
std::string name() const
{
return _name;
};
TestFixture(const std::string& name="A text fixture") : _name(name)
{
}
void afegeixCasDeTest(ConcreteFixture* parent, TestCaseMethod method, const char* name)
{
TestCase* casDeTest = new TestCase(parent, method, name);
_testCases.push_back( casDeTest );
}
/** calls each test after setUp and tearDown TestFixture methods */
void runTest()
{
testsList();
TestCases::iterator it;
for( it=_testCases.begin(); it!=_testCases.end(); it++)
{
setUp();
(*it)->runTest();
tearDown();
}
}
/** TestCase that wraps TestFixture methods are dynamically created and owned by
* the TestFixture. So here we clean it up*/
~TestFixture()
{
TestCases::iterator it;
for( it =_testCases.begin(); it!=_testCases.end(); it++)
delete (*it);
}
};
/**
* This class is aimed to hold a creator method for each concrete TestFixture
*/
class TestFixtureFactory
{
private:
/** Well behaved singleton:
* Don't allow instantiation apart from theInstance(), so private ctr.*/
TestFixtureFactory()
{
}
typedef Test* (*FixtureCreator)();
std::list<FixtureCreator> _creators;
public:
/** Accessor to the (static) singleton instance */
static TestFixtureFactory& theInstance()
{
static TestFixtureFactory theFactory;
return theFactory;
}
bool runTests()
{
std::list<FixtureCreator>::iterator it;
for(it=_creators.begin(); it!=_creators.end(); it++)
{
FixtureCreator creator = *it;
Test* test = creator();
test->runTest();
delete test;
}
std::string errors = TestsListener::theInstance().logString();
if (errors!="") std::cout << "\n\nError Details:\n" << errors;
std::cout << TestsListener::theInstance().summary();
return TestsListener::theInstance().allTestsPassed();
}
void addFixtureCreator(FixtureCreator creator)
{
_creators.push_back( creator );
}
};
/**
* Macro a usar després de cada classe de test
*/
#define REGISTER_FIXTURE( ConcreteTestFixture ) \
\
Test* Creador##ConcreteTestFixture() { return new ConcreteTestFixture; } \
\
class Registrador##ConcreteTestFixture \
{ \
public: \
Registrador##ConcreteTestFixture() \
{ \
TestFixtureFactory::theInstance().addFixtureCreator( \
Creador##ConcreteTestFixture); \
} \
}; \
static Registrador##ConcreteTestFixture estatic##ConcreteTestFixture;
/**
* Assert macros to use in test methods. An assert is a test condition
* we want to check.
*/
#define ASSERT_EQUALS( expected, result) \
Assert::assertEquals( expected, result, __FILE__, __LINE__ );
#define ASSERT_EQUALS_EPSILON( expected, result, epsilon) \
Assert::assertEqualsEpsilon( expected, result, epsilon, __FILE__, __LINE__ );
// #define ASSERT( exp ) \
// Assert::assertTrue(#exp, exp, __FILE__, __LINE__);
#define ASSERT_TEST_MESSAGE( exp, message ) \
Assert::assertTrueMessage(#exp, exp, message, __FILE__, __LINE__);
#define FAIL_TEST( why ) \
Assert::fail(#why, __FILE__, __LINE__);
/**
* Macros that allows to write the constructor of the concrete TestFixture.
* What the constructor does is agregate a wrapper for each test case (method)
* As easy to write as this:
*
* @code
* class MyTests : public TestFixture<MyTests>
* {
* public:
* TEST_FIXTURE( MyTests )
* {
* TEST_CASE( test );
* // etc
* }
* void test()
* {
* ASSERT_EQUALS( 4, 1+1+2 );
* }
* @endcode
*/
#define TEST_FIXTURE( ConcreteFixture ) \
ConcreteFixture() : TestFixture<ConcreteFixture>( #ConcreteFixture )
#define TEST_FIXTURE_DESCRIBE( ConcreteFixture, description ) \
ConcreteFixture() : TestFixture<ConcreteFixture>( description )
#define TEST_CASE( methodName ) \
afegeixCasDeTest( this, &ConcreteFixture::methodName, #methodName );
#define TEST_CASE_DESCRIBE( methodName, description ) \
afegeixCasDeTest( this, &ConcreteFixture::methodName, description );
#endif // MiniCppUnit_hxx