Ignored warnings from gtest with precompiled headers enabled
[profile/ivi/opencv.git] / modules / ts / include / opencv2 / ts / ts.hpp
1 #ifndef __OPENCV_GTESTCV_HPP__
2 #define __OPENCV_GTESTCV_HPP__
3
4 #if HAVE_CVCONFIG_H
5 #include "cvconfig.h"
6 #endif
7 #ifndef GTEST_CREATE_SHARED_LIBRARY
8 #ifdef BUILD_SHARED_LIBS
9 #define GTEST_LINKED_AS_SHARED_LIBRARY 1
10 #endif
11 #endif
12
13 #ifdef ANDROID
14 # include <android/api-level.h>
15 # define GTEST_HAS_CLONE (__ANDROID_API__ > 7 && __arm__)
16 # define GTEST_HAS_POSIX_RE (__ANDROID_API__ > 7)
17 # define GTEST_HAS_STD_WSTRING _GLIBCXX_USE_WCHAR_T
18 #endif
19
20 #include <stdarg.h> // for va_list
21
22 #if defined _MSC_VER && _MSC_VER >= 1200
23 #pragma warning( disable: 4251 4275 4355 4127 )
24 #endif
25
26 #define GTEST_DONT_DEFINE_FAIL      0
27 #define GTEST_DONT_DEFINE_SUCCEED   0
28 #define GTEST_DONT_DEFINE_ASSERT_EQ 0
29 #define GTEST_DONT_DEFINE_ASSERT_NE 0
30 #define GTEST_DONT_DEFINE_ASSERT_LE 0
31 #define GTEST_DONT_DEFINE_ASSERT_LT 0
32 #define GTEST_DONT_DEFINE_ASSERT_GE 0
33 #define GTEST_DONT_DEFINE_ASSERT_GT 0
34 #define GTEST_DONT_DEFINE_TEST      0
35
36 #include "opencv2/ts/ts_gtest.h"
37
38 #ifndef GTEST_USES_SIMPLE_RE
39 #  define GTEST_USES_SIMPLE_RE 0
40 #endif
41 #ifndef GTEST_USES_POSIX_RE
42 #  define GTEST_USES_POSIX_RE 0
43 #endif
44 // #ifdef __GNUC__
45 // #  pragma GCC diagnostic ignored "-Wmissing-declarations"
46 // #endif
47
48 #include "opencv2/core/core.hpp"
49
50 namespace cvtest
51 {
52
53 using std::vector;
54 using std::string;
55 using cv::RNG;
56 using cv::Mat;
57 using cv::Scalar;
58 using cv::Size;
59 using cv::Point;
60 using cv::Rect;
61
62 class CV_EXPORTS TS;
63
64 CV_EXPORTS int64 readSeed(const char* str);
65
66 CV_EXPORTS void randUni( RNG& rng, Mat& a, const Scalar& param1, const Scalar& param2 );
67
68 inline unsigned randInt( RNG& rng )
69 {
70     return (unsigned)rng;
71 }
72
73 inline  double randReal( RNG& rng )
74 {
75     return (double)rng;
76 }
77
78
79 CV_EXPORTS const char* getTypeName( int type );
80 CV_EXPORTS int typeByName( const char* type_name );
81
82 CV_EXPORTS string vec2str(const string& sep, const int* v, size_t nelems);
83
84 inline int clipInt( int val, int min_val, int max_val )
85 {
86     if( val < min_val )
87         val = min_val;
88     if( val > max_val )
89         val = max_val;
90     return val;
91 }
92
93 CV_EXPORTS double getMinVal(int depth);
94 CV_EXPORTS double getMaxVal(int depth);
95
96 CV_EXPORTS Size randomSize(RNG& rng, double maxSizeLog);
97 CV_EXPORTS void randomSize(RNG& rng, int minDims, int maxDims, double maxSizeLog, vector<int>& sz);
98 CV_EXPORTS int randomType(RNG& rng, int typeMask, int minChannels, int maxChannels);
99 CV_EXPORTS Mat randomMat(RNG& rng, Size size, int type, double minVal, double maxVal, bool useRoi);
100 CV_EXPORTS Mat randomMat(RNG& rng, const vector<int>& size, int type, double minVal, double maxVal, bool useRoi);
101 CV_EXPORTS void add(const Mat& a, double alpha, const Mat& b, double beta,
102                       Scalar gamma, Mat& c, int ctype, bool calcAbs=false);
103 CV_EXPORTS void multiply(const Mat& a, const Mat& b, Mat& c, double alpha=1);
104 CV_EXPORTS void divide(const Mat& a, const Mat& b, Mat& c, double alpha=1);
105
106 CV_EXPORTS void convert(const Mat& src, Mat& dst, int dtype, double alpha=1, double beta=0);
107 CV_EXPORTS void copy(const Mat& src, Mat& dst, const Mat& mask=Mat(), bool invertMask=false);
108 CV_EXPORTS void set(Mat& dst, const Scalar& gamma, const Mat& mask=Mat());
109
110 // working with multi-channel arrays
111 CV_EXPORTS void extract( const Mat& a, Mat& plane, int coi );
112 CV_EXPORTS void insert( const Mat& plane, Mat& a, int coi );
113
114 // checks that the array does not have NaNs and/or Infs and all the elements are
115 // within [min_val,max_val). idx is the index of the first "bad" element.
116 CV_EXPORTS int check( const Mat& data, double min_val, double max_val, vector<int>* idx );
117
118 // modifies values that are close to zero
119 CV_EXPORTS void  patchZeros( Mat& mat, double level );
120
121 CV_EXPORTS void transpose(const Mat& src, Mat& dst);
122 CV_EXPORTS void erode(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
123                       int borderType=IPL_BORDER_CONSTANT, const Scalar& borderValue=Scalar());
124 CV_EXPORTS void dilate(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
125                        int borderType=IPL_BORDER_CONSTANT, const Scalar& borderValue=Scalar());
126 CV_EXPORTS void filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel,
127                          Point anchor, double delta, int borderType,
128                          const Scalar& borderValue=Scalar());
129 CV_EXPORTS void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right,
130                                int borderType, const Scalar& borderValue=Scalar());
131 CV_EXPORTS Mat calcSobelKernel2D( int dx, int dy, int apertureSize, int origin=0 );
132 CV_EXPORTS Mat calcLaplaceKernel2D( int aperture_size );
133
134 CV_EXPORTS void initUndistortMap( const Mat& a, const Mat& k, Size sz, Mat& mapx, Mat& mapy );
135
136 CV_EXPORTS void minMaxLoc(const Mat& src, double* minval, double* maxval,
137                           vector<int>* minloc, vector<int>* maxloc, const Mat& mask=Mat());
138 CV_EXPORTS double norm(const Mat& src, int normType, const Mat& mask=Mat());
139 CV_EXPORTS double norm(const Mat& src1, const Mat& src2, int normType, const Mat& mask=Mat());
140 CV_EXPORTS Scalar mean(const Mat& src, const Mat& mask=Mat());
141
142 CV_EXPORTS bool cmpUlps(const Mat& data, const Mat& refdata, int expMaxDiff, double* realMaxDiff, vector<int>* idx);
143
144 // compares two arrays. max_diff is the maximum actual difference,
145 // success_err_level is maximum allowed difference, idx is the index of the first
146 // element for which difference is >success_err_level
147 // (or index of element with the maximum difference)
148 CV_EXPORTS int cmpEps( const Mat& data, const Mat& refdata, double* max_diff,
149                        double success_err_level, vector<int>* idx,
150                        bool element_wise_relative_error );
151
152 // a wrapper for the previous function. in case of error prints the message to log file.
153 CV_EXPORTS int cmpEps2( TS* ts, const Mat& data, const Mat& refdata, double success_err_level,
154                         bool element_wise_relative_error, const char* desc );
155
156 CV_EXPORTS int cmpEps2_64f( TS* ts, const double* val, const double* refval, int len,
157                         double eps, const char* param_name );
158
159 CV_EXPORTS void logicOp(const Mat& src1, const Mat& src2, Mat& dst, char c);
160 CV_EXPORTS void logicOp(const Mat& src, const Scalar& s, Mat& dst, char c);
161 CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
162 CV_EXPORTS void min(const Mat& src, double s, Mat& dst);
163 CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
164 CV_EXPORTS void max(const Mat& src, double s, Mat& dst);
165
166 CV_EXPORTS void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop);
167 CV_EXPORTS void compare(const Mat& src, double s, Mat& dst, int cmpop);
168 CV_EXPORTS void gemm(const Mat& src1, const Mat& src2, double alpha,
169                      const Mat& src3, double beta, Mat& dst, int flags);
170     CV_EXPORTS void transform( const Mat& src, Mat& dst, const Mat& transmat, const Mat& shift );
171 CV_EXPORTS double crossCorr(const Mat& src1, const Mat& src2);
172
173 struct CV_EXPORTS MatInfo
174 {
175     MatInfo(const Mat& _m) : m(&_m) {}
176     const Mat* m;
177 };
178
179 CV_EXPORTS std::ostream& operator << (std::ostream& out, const MatInfo& m);
180
181 struct CV_EXPORTS MatComparator
182 {
183 public:
184     MatComparator(double maxdiff, int context);
185
186     ::testing::AssertionResult operator()(const char* expr1, const char* expr2,
187                                           const Mat& m1, const Mat& m2);
188
189     double maxdiff;
190     double realmaxdiff;
191     vector<int> loc0;
192     int context;
193 };
194
195
196
197 class BaseTest;
198 class TS;
199
200 class CV_EXPORTS BaseTest
201 {
202 public:
203     // constructor(s) and destructor
204     BaseTest();
205     virtual ~BaseTest();
206
207     // the main procedure of the test
208     virtual void run( int start_from );
209
210     // the wrapper for run that cares of exceptions
211     virtual void safe_run( int start_from=0 );
212
213     const string& get_name() const { return name; }
214
215     // returns true if and only if the different test cases do not depend on each other
216     // (so that test system could get right to a problematic test case)
217     virtual bool can_do_fast_forward();
218
219     // deallocates all the memory.
220     // called by init() (before initialization) and by the destructor
221     virtual void clear();
222
223 protected:
224     int test_case_count; // the total number of test cases
225
226     // read test params
227     virtual int read_params( CvFileStorage* fs );
228
229     // returns the number of tests or -1 if it is unknown a-priori
230     virtual int get_test_case_count();
231
232     // prepares data for the next test case. rng seed is updated by the function
233     virtual int prepare_test_case( int test_case_idx );
234
235     // checks if the test output is valid and accurate
236     virtual int validate_test_results( int test_case_idx );
237
238     // calls the tested function. the method is called from run_test_case()
239     virtual void run_func(); // runs tested func(s)
240
241     // updates progress bar
242     virtual int update_progress( int progress, int test_case_idx, int count, double dt );
243
244     // finds test parameter
245     const CvFileNode* find_param( CvFileStorage* fs, const char* param_name );
246
247     // name of the test (it is possible to locate a test by its name)
248     string name;
249
250     // pointer to the system that includes the test
251     TS* ts;
252 };
253
254
255 /*****************************************************************************************\
256 *                               Information about a failed test                           *
257 \*****************************************************************************************/
258
259 struct TestInfo
260 {
261     TestInfo();
262
263     // pointer to the test
264     BaseTest* test;
265
266     // failure code (CV_FAIL*)
267     int code;
268
269     // seed value right before the data for the failed test case is prepared.
270     uint64 rng_seed;
271
272     // seed value right before running the test
273     uint64 rng_seed0;
274
275     // index of test case, can be then passed to BaseTest::proceed_to_test_case()
276     int test_case_idx;
277 };
278
279 /*****************************************************************************************\
280 *                                 Base Class for test system                              *
281 \*****************************************************************************************/
282
283 // common parameters:
284 struct CV_EXPORTS TSParams
285 {
286     TSParams();
287
288     // RNG seed, passed to and updated by every test executed.
289     uint64 rng_seed;
290
291     // whether to use IPP, MKL etc. or not
292     bool use_optimized;
293
294     // extensivity of the tests, scale factor for test_case_count
295     double test_case_count_scale;
296 };
297
298
299 class CV_EXPORTS TS
300 {
301 public:
302     // constructor(s) and destructor
303     TS();
304     virtual ~TS();
305
306     enum
307     {
308         NUL=0,
309         SUMMARY_IDX=0,
310         SUMMARY=1 << SUMMARY_IDX,
311         LOG_IDX=1,
312         LOG=1 << LOG_IDX,
313         CSV_IDX=2,
314         CSV=1 << CSV_IDX,
315         CONSOLE_IDX=3,
316         CONSOLE=1 << CONSOLE_IDX,
317         MAX_IDX=4
318     };
319
320     static TS* ptr();
321
322     // initialize test system before running the first test
323     virtual void init( const string& modulename );
324
325     // low-level printing functions that are used by individual tests and by the system itself
326     virtual void printf( int streams, const char* fmt, ... );
327     virtual void vprintf( int streams, const char* fmt, va_list arglist );
328
329     // updates the context: current test, test case, rng state
330     virtual void update_context( BaseTest* test, int test_case_idx, bool update_ts_context );
331
332     const TestInfo* get_current_test_info() { return &current_test_info; }
333
334     // sets information about a failed test
335     virtual void set_failed_test_info( int fail_code );
336
337     virtual void set_gtest_status();
338
339     // test error codes
340     enum
341     {
342         // everything is Ok
343         OK=0,
344
345         // generic error: stub value to be used
346         // temporarily if the error's cause is unknown
347         FAIL_GENERIC=-1,
348
349         // the test is missing some essential data to proceed further
350         FAIL_MISSING_TEST_DATA=-2,
351
352         // the tested function raised an error via cxcore error handler
353         FAIL_ERROR_IN_CALLED_FUNC=-3,
354
355         // an exception has been raised;
356         // for memory and arithmetic exception
357         // there are two specialized codes (see below...)
358         FAIL_EXCEPTION=-4,
359
360         // a memory exception
361         // (access violation, access to missed page, stack overflow etc.)
362         FAIL_MEMORY_EXCEPTION=-5,
363
364         // arithmetic exception (overflow, division by zero etc.)
365         FAIL_ARITHM_EXCEPTION=-6,
366
367         // the tested function corrupted memory (no exception have been raised)
368         FAIL_MEMORY_CORRUPTION_BEGIN=-7,
369         FAIL_MEMORY_CORRUPTION_END=-8,
370
371         // the tested function (or test ifself) do not deallocate some memory
372         FAIL_MEMORY_LEAK=-9,
373
374         // the tested function returned invalid object, e.g. matrix, containing NaNs,
375         // structure with NULL or out-of-range fields (while it should not)
376         FAIL_INVALID_OUTPUT=-10,
377
378         // the tested function returned valid object, but it does not match to
379         // the original (or produced by the test) object
380         FAIL_MISMATCH=-11,
381
382         // the tested function returned valid object (a single number or numerical array),
383         // but it differs too much from the original (or produced by the test) object
384         FAIL_BAD_ACCURACY=-12,
385
386         // the tested function hung. Sometimes, can be determined by unexpectedly long
387         // processing time (in this case there should be possibility to interrupt such a function
388         FAIL_HANG=-13,
389
390         // unexpected responce on passing bad arguments to the tested function
391         // (the function crashed, proceed succesfully (while it should not), or returned
392         // error code that is different from what is expected)
393         FAIL_BAD_ARG_CHECK=-14,
394
395         // the test data (in whole or for the particular test case) is invalid
396         FAIL_INVALID_TEST_DATA=-15,
397
398         // the test has been skipped because it is not in the selected subset of the tests to run,
399         // because it has been run already within the same run with the same parameters, or because
400         // of some other reason and this is not considered as an error.
401         // Normally TS::run() (or overrided method in the derived class) takes care of what
402         // needs to be run, so this code should not occur.
403         SKIPPED=1
404     };
405
406     // get file storage
407     CvFileStorage* get_file_storage();
408
409     // get RNG to generate random input data for a test
410     RNG& get_rng() { return rng; }
411
412     // returns the current error code
413     int get_err_code() { return current_test_info.code; }
414
415     // returns the test extensivity scale
416     double get_test_case_count_scale() { return params.test_case_count_scale; }
417
418     const string& get_data_path() const { return data_path; }
419
420     // returns textual description of failure code
421     static string str_from_code( int code );
422
423 protected:
424
425     // these are allocated within a test to try keep them valid in case of stack corruption
426     RNG rng;
427
428     // information about the current test
429     TestInfo current_test_info;
430
431     // the path to data files used by tests
432     string data_path;
433
434     TSParams params;
435     std::string output_buf[MAX_IDX];
436 };
437
438
439 /*****************************************************************************************\
440 *            Subclass of BaseTest for testing functions that process dense arrays           *
441 \*****************************************************************************************/
442
443 class CV_EXPORTS ArrayTest : public BaseTest
444 {
445 public:
446     // constructor(s) and destructor
447     ArrayTest();
448     virtual ~ArrayTest();
449
450     virtual void clear();
451
452 protected:
453
454     virtual int read_params( CvFileStorage* fs );
455     virtual int prepare_test_case( int test_case_idx );
456     virtual int validate_test_results( int test_case_idx );
457
458     virtual void prepare_to_validation( int test_case_idx );
459     virtual void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types );
460     virtual void fill_array( int test_case_idx, int i, int j, Mat& arr );
461     virtual void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high );
462     virtual double get_success_error_level( int test_case_idx, int i, int j );
463
464     bool cvmat_allowed;
465     bool iplimage_allowed;
466     bool optional_mask;
467     bool element_wise_relative_error;
468
469     int min_log_array_size;
470     int max_log_array_size;
471
472     enum { INPUT, INPUT_OUTPUT, OUTPUT, REF_INPUT_OUTPUT, REF_OUTPUT, TEMP, MASK, MAX_ARR };
473
474     vector<vector<void*> > test_array;
475     vector<vector<Mat> > test_mat;
476     float buf[4];
477 };
478
479
480 class CV_EXPORTS BadArgTest : public BaseTest
481 {
482 public:
483     // constructor(s) and destructor
484     BadArgTest();
485     virtual ~BadArgTest();
486
487 protected:
488     virtual int run_test_case( int expected_code, const string& descr );
489     virtual void run_func(void) = 0;
490     int test_case_idx;
491     int progress;
492     double t, freq;
493
494     template<class F>
495     int run_test_case( int expected_code, const string& _descr, F f)
496     {
497         double new_t = (double)cv::getTickCount(), dt;
498         if( test_case_idx < 0 )
499         {
500             test_case_idx = 0;
501             progress = 0;
502             dt = 0;
503         }
504         else
505         {
506             dt = (new_t - t)/(freq*1000);
507             t = new_t;
508         }
509         progress = update_progress(progress, test_case_idx, 0, dt);
510
511         int errcount = 0;
512         bool thrown = false;
513         const char* descr = _descr.c_str() ? _descr.c_str() : "";
514
515         try
516         {
517             f();
518         }
519         catch(const cv::Exception& e)
520         {
521             thrown = true;
522             if( e.code != expected_code )
523             {
524                 ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
525                     descr, test_case_idx, e.code, expected_code);
526                 errcount = 1;
527             }
528         }
529         catch(...)
530         {
531             thrown = true;
532             ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
533                        descr, test_case_idx);
534             errcount = 1;
535         }
536         if(!thrown)
537         {
538             ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
539                        descr, test_case_idx);
540             errcount = 1;
541         }
542         test_case_idx++;
543
544         return errcount;
545     }
546 };
547
548 struct CV_EXPORTS DefaultRngAuto
549 {
550     const uint64 old_state;
551
552     DefaultRngAuto() : old_state(cv::theRNG().state) { cv::theRNG().state = (uint64)-1; }
553     ~DefaultRngAuto() { cv::theRNG().state = old_state; }
554
555     DefaultRngAuto& operator=(const DefaultRngAuto&);
556 };
557
558 }
559
560 // fills c with zeros
561 CV_EXPORTS void cvTsZero( CvMat* c, const CvMat* mask=0 );
562
563 // copies a to b (whole matrix or only the selected region)
564 CV_EXPORTS void cvTsCopy( const CvMat* a, CvMat* b, const CvMat* mask=0 );
565
566 // converts one array to another
567 CV_EXPORTS void  cvTsConvert( const CvMat* src, CvMat* dst );
568
569 CV_EXPORTS void cvTsGEMM( const CvMat* a, const CvMat* b, double alpha,
570                          const CvMat* c, double beta, CvMat* d, int flags );
571
572 #define CV_TEST_MAIN(resourcesubdir) \
573 int main(int argc, char **argv) \
574 { \
575     cvtest::TS::ptr()->init(resourcesubdir); \
576     ::testing::InitGoogleTest(&argc, argv); \
577     return RUN_ALL_TESTS(); \
578 }
579
580 #endif
581
582 #include "ts_perf.hpp"