GTestSuite.cpp
28.2 KB
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
/***************************************************************************
* GTestSuite.cpp - Abstract test suite base class *
* ----------------------------------------------------------------------- *
* copyright (C) 2012-2013 by Jean-Baptiste Cayrou *
* ----------------------------------------------------------------------- *
* *
* 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 3 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, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
/**
* @file GTestSuite.cpp
* @brief Abstract test suite base class implementation
* @author Jean-Baptiste Cayrou
*/
/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <typeinfo>
#include "GTestSuite.hpp"
#include "GTools.hpp"
#include "GLog.hpp"
/* __ OpenMP section _____________________________________________________ */
#ifdef _OPENMP
#include <omp.h>
#ifdef HAVE_OPENMP_DARWIN_KLUGE
#include <pthread.h>
pthread_attr_t gomp_thread_attr;
#endif
#endif
/* __ Method name definitions ____________________________________________ */
#define G_OP_ACCESS "GTestSuite::operator[](int&)"
#define G_TRY_SUCCESS "GTestSuite::test_try_success()"
#define G_TRY_FAILURE1 "GTestSuite::test_try_failure(std::string&,"\
" std::string&)"
#define G_TRY_FAILURE2 "GTestSuite::test_try_failure(std::exception&)"
/* __ Macros _____________________________________________________________ */
/* __ Coding definitions _________________________________________________ */
/* __ Debug definitions __________________________________________________ */
/*==========================================================================
= =
= Constructors/destructors =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Void constructor
***************************************************************************/
GTestSuite::GTestSuite(void)
{
// Initialise members
init_members();
//Return
return;
}
/***********************************************************************//**
* @brief Copy constructor
*
* @param[in] suite Test Suite.
***************************************************************************/
GTestSuite::GTestSuite(const GTestSuite& suite)
{
// Initialise members
init_members();
// Copy members
copy_members(suite);
//Return
return;
}
/***********************************************************************//**
* @brief Name constructor
*
* @param[in] name Test suite name.
***************************************************************************/
GTestSuite::GTestSuite(const std::string& name)
{
// Initialise members
init_members();
// Set name
m_name = name;
//Return
return;
}
/***********************************************************************//**
* @brief Destructor
***************************************************************************/
GTestSuite::~GTestSuite(void)
{
// Free members
free_members();
// Return
return;
}
/*==========================================================================
= =
= Operators =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Assignment operator
*
* @param[in] suite Test suite.
* @return Test suite.
***************************************************************************/
GTestSuite& GTestSuite::operator=(const GTestSuite& suite)
{
// Execute only if object is not identical
if (this != &suite) {
// Free members
free_members();
// Initialise members
init_members();
// Copy members
copy_members(suite);
} // endif: object was not identical
// Return
return *this;
}
/***********************************************************************//**
* @brief Returns reference to test case
*
* @param[in] index Test case index [0,...,size()-1].
*
* @exception GException::out_of_range
* Test case index is out of range.
***************************************************************************/
GTestCase& GTestSuite::operator[](const int& index)
{
// Compile option: raise exception if index is out of range
#if defined(G_RANGE_CHECK)
if (index < 0 || index >= size()) {
throw GException::out_of_range(G_OP_ACCESS, "Test case index", index, size());
}
#endif
// Return reference
return *(m_tests[index]);
}
/***********************************************************************//**
* @brief Returns reference to test case
*
* @param[in] index Test case index [0,...,size()-1].
*
* @exception GException::out_of_range
* Test case index is out of range.
***************************************************************************/
const GTestCase& GTestSuite::operator[](const int& index) const
{
// Compile option: raise exception if index is out of range
#if defined(G_RANGE_CHECK)
if (index < 0 || index >= size()) {
throw GException::out_of_range(G_OP_ACCESS, "Test case index", index, size());
}
#endif
// Return reference
return *(m_tests[index]);
}
/*==========================================================================
= =
= Public methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Clear test suite
***************************************************************************/
void GTestSuite::clear(void)
{
// Free members
free_members();
// Initialise members
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief Append test functions to test suite
*
* @param[in] function Test function pointer.
* @param[in] name Test name.
*
* This method adds test functions to the test suite. The test functions will
* be executed when the run method is called.
***************************************************************************/
void GTestSuite::append(const pfunction function, const std::string& name)
{
// Add test function pointer and name to suite
m_functions.push_back(function);
m_names.push_back(name);
// Return
return;
}
/***********************************************************************//**
* @brief Run all tests in test suite
*
* @return True is all tests were successful, false otherwise.
*
* Executes all test functions that have been appended to the test suite.
* For each test function a test case is added to the test suite.
***************************************************************************/
bool GTestSuite::run(void)
{
// Setup the test functions. This is a pure virtual function that needs
// to be implemented in the derived class. It sets the function
// pointers and function names for all test functions that should be
// executed.
set();
// Initialise success flag
bool success = true;
// Loop over all functions in suite
for (m_index = 0; m_index < m_functions.size(); ++m_index) {
// Continue only if function is valid
if (m_functions[m_index] != NULL) {
// Save the number of errors and failures before test
// execution. We use this after the test to see if
// any failures occured.
int old_errors = errors();
int old_failures = failures();
// Log the name of the test
std::cout << m_names[m_index] << ": ";
// Create a test of error type for function testing
GTestCase* test = new GTestCase(GTestCase::ERROR_TEST, m_names[m_index]);
// Set start time
#ifdef _OPENMP
double t_start = omp_get_wtime();
#else
clock_t t_start = clock();
#endif
// Execute test function
try {
(this->*(m_functions[m_index]))();
}
catch (std::exception& e) {
// Signal that test did not succeed
test->has_passed(false);
// Set test message to exception message
test->message(e.what());
// Set type as class name
test->type(typeid(e).name());
}
catch (...)
{
// For other exceptions
test->has_passed(false);
}
// Compute elapsed time
#ifdef _OPENMP
double t_elapse = omp_get_wtime()-t_start;
#else
double t_elapse = (double)(clock() - t_start) / (double)CLOCKS_PER_SEC;
#endif
// Set test duration
test->duration(t_elapse);
// Increment number of errors if the test did not pass
if (!test->has_passed()) {
m_errors++;
}
// Log the result (".","F" or, "E")
std::cout << test->print();
// Log if there are errors or failures
if ((m_errors == old_errors && m_failures == old_failures)) {
std::cout << " ok" << std::endl;
}
else {
std::cout << " NOK" << std::endl;
success = false;
}
// Add test case to test suite
m_tests.push_back(test);
} // endif: test case has a function pointer
} // endwhile: there were tests on the stack
// Reset index
m_index = 0;
// Return success flag
return success;
}
/***********************************************************************//**
* @brief Test an assert
*
* @param[in] assert Assert (true/false).
* @param[in] name Test case name (defaults to "").
* @param[in] message Test case name (defaults to "").
*
* Tests if a condition is true or false. This method adds a test case of
* type "failure" to the test suite.
*
* Examples:
* test_assert(x>3, "Test if x > 3");
* test_assert(x>3 && x<10, "Test if 3 < x < 10 ");
***************************************************************************/
void GTestSuite::test_assert(const bool& assert,
const std::string& name,
const std::string& message)
{
// Create a test case of failure type
GTestCase* testcase = new GTestCase(GTestCase::FAIL_TEST, format_name(name));
// If assert is false then signal that the test is not passed and
// increment the number of failures in this test suite
if (!assert) {
testcase->has_passed(false);
m_failures++;
}
// Set message
testcase->message(message);
// Log the result (".","F" or, "E")
std::cout << testcase->print();
// Add test case to test suite
m_tests.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Test a value
*
* @param[in] value Value to test.
* @param[in] expected Expected value.
* @param[in] name Test case name (defaults to "").
* @param[in] message Test case message (defaults to "").
*
* Test if the value is comprised in the interval
* [expected-eps, expected+eps].
***************************************************************************/
void GTestSuite::test_value(const int& value,
const int& expected,
const std::string& name,
const std::string& message)
{
// Set test case name. If no name is specify then build the name from
// the actual test parameters.
std::string formated_name;
if (name != "") {
formated_name = format_name(name);
}
else {
formated_name = format_name("Test if " + gammalib::str(value) + " is " +
gammalib::str(expected));
}
// Create a test case of failure type
GTestCase* testcase = new GTestCase(GTestCase::FAIL_TEST, formated_name);
// If value is not the expected one then signal test as failed and
// increment the number of failures
if (value != expected) {
testcase->has_passed(false);
m_failures++;
}
// If no message is specified then build message from test result
std::string formated_message;
if (message != "") {
formated_message = message;
}
else {
formated_message = "Value " + gammalib::str(value) + " equals not the " +
"expected value of " + gammalib::str(expected) + ".";
}
// Set message
testcase->message(formated_message);
// Log the result (".","F" or, "E")
std::cout << testcase->print();
// Add test case to test suite
m_tests.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Test a value
*
* @param[in] value Value to test.
* @param[in] expected Expected value.
* @param[in] eps Precision of the test (default 1e-30).
* @param[in] name Test case name (defaults to "").
* @param[in] message Test case message (defaults to "").
*
* Test if the value is comprised in the interval
* [expected-eps, expected+eps].
***************************************************************************/
void GTestSuite::test_value(const double& value,
const double& expected,
const double& eps,
const std::string& name,
const std::string& message)
{
// Set test case name. If no name is specify then build the name from
// the actual test parameters.
std::string formated_name;
if (name != "") {
formated_name = format_name(name);
}
else {
formated_name = format_name("Test if " + gammalib::str(value) + " is within " +
gammalib::str(expected) + " +/- " + gammalib::str(eps));
}
// Create a test case of failure type
GTestCase* testcase = new GTestCase(GTestCase::FAIL_TEST, formated_name);
// If value is not between in interval [expected-eps, expected+eps]
// then signal test as failed and increment the number of failures
if (value > expected + eps || value < expected - eps) {
testcase->has_passed(false);
m_failures++;
}
// If no message is specified then build message from test result
std::string formated_message;
if (message != "") {
formated_message = message;
}
else {
formated_message = "Value " + gammalib::str(value) + " not within " +
gammalib::str(expected) + " +/- " + gammalib::str(eps) +
" (value-expected = " + gammalib::str(value-expected) + ").";
}
// Set message
testcase->message(formated_message);
// Log the result (".","F" or, "E")
std::cout << testcase->print();
// Add test case to test suite
m_tests.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Test an try block
*
* @param[in] name Test case name (defaults to "").
*
* @see test_try_sucess()
* @see test_try_failure(const std::string& message,const std::string& type)
* @see test_try_failure(const std::exception& e)
*
* Call before testing a try/catch block.
*
* Example:
* test_try("Test a try block");
* try {
* ... //someting to test
* test_try_success();
* }
* catch(...) {
* test_try_failure();
* }
***************************************************************************/
void GTestSuite::test_try(const std::string& name)
{
// Create a test case of error type
GTestCase* testcase = new GTestCase(GTestCase::ERROR_TEST, format_name(name));
// Add test case to try stack of test suite
m_stack_try.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Notice when a try block succeeded
*
* @exception GException::test_nested_try_error
* Test case index is out of range.
*
* @see test_try(const std::string& name)
* @see test_try_failure(const std::string& message, const std::string& type)
* @see test_try_failure(const std::exception& e)
*
* Call this method at the last line of a try
*
* Example:
* test_try("Test a try block");
* try {
* ... //someting to test
* test_try_success();
* }
* catch(...) {
* test_try_failure();
* }
***************************************************************************/
void GTestSuite::test_try_success(void)
{
// If the stack is empty
if (m_stack_try.empty()) {
throw GException::test_nested_try_error(G_TRY_SUCCESS,
"Called \"G_TRY_SUCCESS\" without a previous call to test_try()");
}
// Add test case to test suite
m_tests.push_back(m_stack_try.back());
// Delete the test case from the try stack
m_stack_try.pop_back();
// Log the result (".","F" or, "E")
std::cout << m_tests.back()->print();
// Return
return;
}
/***********************************************************************//**
* @brief Notice when a try block failed
*
* @param[in] message Message to explain why test failed (defaults to "").
* @param[in] type Type of message (defaults to "").
*
* @exception GException::test_nested_try_error
* Test case index is out of range.
*
* @see test_try_sucess()
* @see test_try(const std::string& name)
* @see test_try_failure(const std::exception& e)
*
* Call this method in the catch block.
*
* Example:
* test_try("Test a try block");
* try {
* ... //someting to test
* test_try_success();
* }
* catch(...) {
* test_try_failure();
* }
***************************************************************************/
void GTestSuite::test_try_failure(const std::string& message,
const std::string& type)
{
// If the stack is empty then create an eception test case
if (m_stack_try.empty()) {
GTestCase* testcase = new GTestCase(GTestCase::ERROR_TEST, "Exception test");
m_stack_try.push_back(testcase);
}
// Signal that test is not ok
m_stack_try.back()->has_passed(false);
// Increment the number of errors
m_errors++;
// Set test type
m_stack_try.back()->kind(GTestCase::ERROR_TEST);
// Set message
m_stack_try.back()->message(message);
// Set type of message
m_stack_try.back()->type(type);
// Add test case to test suite
m_tests.push_back(m_stack_try.back());
// Delete the test case from the stack
m_stack_try.pop_back();
// Log the result ( ".","F" or, "E")
std::cout << m_tests.back()->print();
//Return
return;
}
/***********************************************************************//**
* @brief Notice when a try block failed
*
* @param[in] e Exception.
*
* @exception GException::test_nested_try_error
* Test case index is out of range.
*
* @see test_try_sucess()
* @see test_try(const std::string& name)
* @see test_try_failure(const std::string& message, const std::string& type)
*
* Call this method in a catch block.
*
* Example:
* test_try("Test a try block");
* try {
* ... //someting to test
* test_try_success();
* }
* catch(exception& e) {
* test_try_failure(e);
* }
***************************************************************************/
void GTestSuite::test_try_failure(const std::exception& e)
{
// Extract message of exception and class name
test_try_failure(e.what(), typeid(e).name());
// Return
return;
}
/***********************************************************************//**
* @brief Return a failure exception
*
* @param[in] message Message.
*
* @see test_try()
* @see test_error(const std::string& message)
*
* It can be use in a try test
*
* Example:
* test_try("Test a try block");
* try {
* throw exception_failure("a failure");
* test_try_success();
* }
* catch(exception& e) {
* test_try_failure(e);
* }
***************************************************************************/
GException::test_failure& GTestSuite::exception_failure(const std::string& message)
{
// Return exception
return *(new GException::test_failure(m_stack_try.back()->name(), message));
}
/***********************************************************************//**
* @brief Return an error exception
*
* @param[in] message Message.
*
* @see test_try()
* @see test_failure(const std::string& message)
*
* It can be use in a try test
*
* Example:
* test_try("Test a try block");
* try {
* throw exception_error("an error");
* test_try_success();
* }
* catch(exception& e) {
* test_try_failure(e);
* }
***************************************************************************/
GException::test_error& GTestSuite::exception_error(const std::string& message)
{
// Return exception
return *(new GException::test_error(m_stack_try.back()->name(),message));
}
/***********************************************************************//**
* @brief Return the number of successful tests
***************************************************************************/
int GTestSuite::success(void) const
{
// Return successes
return size()-(m_errors+m_failures);
}
/***********************************************************************//**
* @brief Return the total duration of all tests
*
* This method sums up all test durations and returns the result.
***************************************************************************/
double GTestSuite::duration(void) const
{
// Initialise duration
double duration = 0.0;
// Add up the durations of all tests
for (int i = 0; i < m_tests.size(); ++i) {
duration += m_tests[i]->duration();
}
// Return duration
return duration;
}
/***********************************************************************//**
* @brief Print test suite information
*
* @param[in] chatter Chattiness (defaults to NORMAL).
* @return String containing test suite information.
***************************************************************************/
std::string GTestSuite::print(const GChatter& chatter) const
{
// Initialise result string
std::string result;
// Continue only if chatter is not silent
if (chatter != SILENT) {
// Append header
result.append("=== GTestSuite ===");
// Append information
result.append("\n"+gammalib::parformat("Name")+m_name);
result.append("\n"+gammalib::parformat("Number of functions"));
result.append(gammalib::str(m_names.size()));
result.append("\n"+gammalib::parformat("Number of executed tests"));
result.append(gammalib::str(size()));
result.append("\n"+gammalib::parformat("Number of errors"));
result.append(gammalib::str(errors()));
result.append("\n"+gammalib::parformat("Number of failures"));
result.append(gammalib::str(failures()));
} // endif: chatter was not silent
// Return result
return result;
}
/*==========================================================================
= =
= Private methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Initialise class members
***************************************************************************/
void GTestSuite::init_members(void)
{
// Initialise members
m_name = "Unnamed Test Suite";
m_names.clear();
m_functions.clear();
m_tests.clear();
m_stack_try.clear();
m_index = 0;
m_failures = 0;
m_errors = 0;
m_log.clear();
m_timestamp = time(NULL);
// Set logger parameters
cout(true);
m_log.max_size(1);
// Return
return;
}
/***********************************************************************//**
* @brief Copy class members
*
* @param[in] suite Test suite.
*
* This method just clone the container not the test case.
***************************************************************************/
void GTestSuite::copy_members(const GTestSuite& suite)
{
// Copy members
m_name = suite.m_name;
m_names = suite.m_names;
m_functions = suite.m_functions;
m_index = suite.m_index;
m_failures = suite.m_failures;
m_errors = suite.m_errors;
m_log = suite.m_log;
m_timestamp = suite.m_timestamp;
// Clone test cases
for (int i = 0; i < suite.m_tests.size(); ++i) {
m_tests[i] = suite.m_tests[i]->clone();
}
// Clone try stack
for (int i = 0; i < suite.m_stack_try.size(); ++i) {
m_stack_try[i] = suite.m_stack_try[i]->clone();
}
// Return
return;
}
/***********************************************************************//**
* @brief Delete class members
***************************************************************************/
void GTestSuite::free_members(void)
{
// Delete test cases
for (int i = 0; i < m_tests.size(); ++i) {
delete m_tests[i];
m_tests[i] = NULL;
}
// Delete try stack
for (int i = 0; i < m_stack_try.size(); ++i) {
delete m_stack_try[i];
m_stack_try[i] = NULL;
}
// Close logger
m_log.close();
// Return
return;
}
/***********************************************************************//**
* @brief Format Name
*
* Return a string with the format
* "TestFunctionName:TestTryname1:TestTryName2: name"
***************************************************************************/
std::string GTestSuite::format_name(const std::string& name)
{
// Initialise format name
std::string format_name;
// Set name of the try blocks
if (!m_stack_try.empty()) {
format_name = m_stack_try.back()->name();
}
else {
// Set name of the test
format_name = m_names[m_index];
}
// Append test suite name
format_name += ": " + name;
// Return format
return format_name;
}