dnn(test): replace SkipTestException with tags
[platform/upstream/opencv.git] / modules / ts / include / opencv2 / ts.hpp
1 #ifndef OPENCV_TS_HPP
2 #define OPENCV_TS_HPP
3
4 #ifndef __OPENCV_TESTS
5 #define __OPENCV_TESTS 1
6 #endif
7
8 #include "opencv2/opencv_modules.hpp"
9
10 #include "opencv2/core.hpp"
11 #include "opencv2/imgproc.hpp"
12 #include "opencv2/imgcodecs.hpp"
13 #include "opencv2/videoio.hpp"
14 #include "opencv2/highgui.hpp"
15
16 #include "opencv2/core/utility.hpp"
17
18 #include "opencv2/core/utils/trace.hpp"
19
20 #include "opencv2/core/hal/hal.hpp"
21
22 #include <stdarg.h> // for va_list
23
24 #include "cvconfig.h"
25
26 #include <cmath>
27 #include <vector>
28 #include <list>
29 #include <map>
30 #include <queue>
31 #include <string>
32 #include <iostream>
33 #include <fstream>
34 #include <iomanip>
35 #include <sstream>
36 #include <cstdio>
37 #include <iterator>
38 #include <limits>
39 #include <algorithm>
40
41
42 #ifndef OPENCV_32BIT_CONFIGURATION
43 # if defined(INTPTR_MAX) && defined(INT32_MAX) && INTPTR_MAX == INT32_MAX
44 #   define OPENCV_32BIT_CONFIGURATION 1
45 # elif defined(_WIN32) && !defined(_WIN64)
46 #   define OPENCV_32BIT_CONFIGURATION 1
47 # endif
48 #else
49 # if OPENCV_32BIT_CONFIGURATION == 0
50 #   undef OPENCV_32BIT_CONFIGURATION
51 # endif
52 #endif
53
54
55
56 // most part of OpenCV tests are fit into 200Mb limit, but some tests are not:
57 // Note: due memory fragmentation real limits are usually lower on 20-25% (400Mb memory usage goes into mem_1Gb class)
58 #define CV_TEST_TAG_MEMORY_512MB "mem_512mb"     // used memory: 200..512Mb - enabled by default
59 #define CV_TEST_TAG_MEMORY_1GB "mem_1gb"         // used memory: 512Mb..1Gb - enabled by default
60 #define CV_TEST_TAG_MEMORY_2GB "mem_2gb"         // used memory: 1..2Gb - enabled by default on 64-bit configuration (32-bit - disabled)
61 #define CV_TEST_TAG_MEMORY_6GB "mem_6gb"         // used memory: 2..6Gb - disabled by default
62 #define CV_TEST_TAG_MEMORY_14GB "mem_14gb"       // used memory: 6..14Gb - disabled by default
63
64 // Large / huge video streams or complex workloads
65 #define CV_TEST_TAG_LONG "long"                  // 5+ seconds on modern desktop machine (single thread)
66 #define CV_TEST_TAG_VERYLONG "verylong"          // 20+ seconds on modern desktop machine (single thread)
67
68 // Large / huge video streams or complex workloads for debug builds
69 #define CV_TEST_TAG_DEBUG_LONG "debug_long"           // 10+ seconds on modern desktop machine (single thread)
70 #define CV_TEST_TAG_DEBUG_VERYLONG "debug_verylong"   // 40+ seconds on modern desktop machine (single thread)
71
72 // Lets skip processing of high resolution images via instrumentation tools (valgrind/coverage/sanitizers).
73 // It is enough to run lower resolution (VGA: 640x480) tests.
74 #define CV_TEST_TAG_SIZE_HD "size_hd"            // 720p+, enabled
75 #define CV_TEST_TAG_SIZE_FULLHD "size_fullhd"    // 1080p+, enabled (disable these tests for valgrind/coverage run)
76 #define CV_TEST_TAG_SIZE_4K "size_4k"            // 2160p+, enabled (disable these tests for valgrind/coverage run)
77
78 // Other misc test tags
79 #define CV_TEST_TAG_TYPE_64F "type_64f"          // CV_64F, enabled (disable these tests on low power embedded devices)
80
81 // Kernel-based image processing
82 #define CV_TEST_TAG_FILTER_SMALL "filter_small"       // Filtering with kernels <= 3x3
83 #define CV_TEST_TAG_FILTER_MEDIUM "filter_medium"     // Filtering with kernels: 3x3 < kernel <= 5x5
84 #define CV_TEST_TAG_FILTER_LARGE "filter_large"       // Filtering with kernels: 5x5 < kernel <= 9x9
85 #define CV_TEST_TAG_FILTER_HUGE "filter_huge"         // Filtering with kernels: > 9x9
86
87 // Other tests categories
88 #define CV_TEST_TAG_OPENCL "opencl"              // Tests with OpenCL
89
90
91
92 #ifdef WINRT
93     #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
94 #endif
95
96 #ifdef _MSC_VER
97 #pragma warning( disable: 4503 ) // decorated name length exceeded, name was truncated
98 #endif
99
100 #define GTEST_DONT_DEFINE_FAIL      0
101 #define GTEST_DONT_DEFINE_SUCCEED   0
102 #define GTEST_DONT_DEFINE_ASSERT_EQ 0
103 #define GTEST_DONT_DEFINE_ASSERT_NE 0
104 #define GTEST_DONT_DEFINE_ASSERT_LE 0
105 #define GTEST_DONT_DEFINE_ASSERT_LT 0
106 #define GTEST_DONT_DEFINE_ASSERT_GE 0
107 #define GTEST_DONT_DEFINE_ASSERT_GT 0
108 #define GTEST_DONT_DEFINE_TEST      0
109
110 #ifndef GTEST_LANG_CXX11
111 #if __cplusplus >= 201103L || (defined(_MSVC_LANG) && !(_MSVC_LANG < 201103))
112 #  define GTEST_LANG_CXX11 1
113 #  define GTEST_HAS_TR1_TUPLE 0
114 #  define GTEST_HAS_COMBINE 1
115 # endif
116 #endif
117
118 #if defined(__OPENCV_BUILD) && defined(__clang__)
119 #pragma clang diagnostic ignored "-Winconsistent-missing-override"
120 #endif
121 #if defined(__OPENCV_BUILD) && defined(__GNUC__) && __GNUC__ >= 5
122 //#pragma GCC diagnostic push
123 #pragma GCC diagnostic ignored "-Wsuggest-override"
124 #endif
125 #include "opencv2/ts/ts_gtest.h"
126 #if defined(__OPENCV_BUILD) && defined(__GNUC__) && __GNUC__ >= 5
127 //#pragma GCC diagnostic pop
128 #endif
129 #include "opencv2/ts/ts_ext.hpp"
130
131 #ifndef GTEST_USES_SIMPLE_RE
132 #  define GTEST_USES_SIMPLE_RE 0
133 #endif
134 #ifndef GTEST_USES_POSIX_RE
135 #  define GTEST_USES_POSIX_RE 0
136 #endif
137
138 #define PARAM_TEST_CASE(name, ...) struct name : testing::TestWithParam< testing::tuple< __VA_ARGS__ > >
139 #define GET_PARAM(k) testing::get< k >(GetParam())
140
141 namespace cvtest
142 {
143
144 using std::vector;
145 using std::map;
146 using std::string;
147 using std::stringstream;
148 using std::cout;
149 using std::cerr;
150 using std::endl;
151 using std::min;
152 using std::max;
153 using std::numeric_limits;
154 using std::pair;
155 using std::make_pair;
156 using testing::TestWithParam;
157 using testing::Values;
158 using testing::ValuesIn;
159 using testing::Combine;
160
161 using cv::Mat;
162 using cv::Mat_;
163 using cv::UMat;
164 using cv::InputArray;
165 using cv::OutputArray;
166 using cv::noArray;
167
168 using cv::Range;
169 using cv::Point;
170 using cv::Rect;
171 using cv::Size;
172 using cv::Scalar;
173 using cv::RNG;
174
175 // Tuple stuff from Google Tests
176 using testing::get;
177 using testing::make_tuple;
178 using testing::tuple;
179 using testing::tuple_size;
180 using testing::tuple_element;
181
182
183 class SkipTestException: public cv::Exception
184 {
185 public:
186     int dummy; // workaround for MacOSX Xcode 7.3 bug (don't make class "empty")
187     SkipTestException() : dummy(0) {}
188     SkipTestException(const cv::String& message) : dummy(0) { this->msg = message; }
189 };
190
191 /** Apply tag to the current test
192
193 Automatically apply corresponding additional tags (for example, 4K => FHD => HD => VGA).
194
195 If tag is in skip list, then SkipTestException is thrown
196 */
197 void applyTestTag(const std::string& tag);
198
199 /** Run postponed checks of applied test tags
200
201 If tag is in skip list, then SkipTestException is thrown
202 */
203 void checkTestTags();
204
205 void applyTestTag_(const std::string& tag);
206
207 static inline void applyTestTag(const std::string& tag1, const std::string& tag2)
208 { applyTestTag_(tag1); applyTestTag_(tag2); checkTestTags(); }
209 static inline void applyTestTag(const std::string& tag1, const std::string& tag2, const std::string& tag3)
210 { applyTestTag_(tag1); applyTestTag_(tag2); applyTestTag_(tag3); checkTestTags(); }
211 static inline void applyTestTag(const std::string& tag1, const std::string& tag2, const std::string& tag3, const std::string& tag4)
212 { applyTestTag_(tag1); applyTestTag_(tag2); applyTestTag_(tag3); applyTestTag_(tag4); checkTestTags(); }
213
214
215 /** Append global skip test tags
216 */
217 void registerGlobalSkipTag(const std::string& skipTag);
218 static inline void registerGlobalSkipTag(const std::string& tag1, const std::string& tag2)
219 { registerGlobalSkipTag(tag1); registerGlobalSkipTag(tag2); }
220 static inline void registerGlobalSkipTag(const std::string& tag1, const std::string& tag2, const std::string& tag3)
221 { registerGlobalSkipTag(tag1); registerGlobalSkipTag(tag2); registerGlobalSkipTag(tag3); }
222 static inline void registerGlobalSkipTag(const std::string& tag1, const std::string& tag2, const std::string& tag3, const std::string& tag4)
223 { registerGlobalSkipTag(tag1); registerGlobalSkipTag(tag2); registerGlobalSkipTag(tag3); registerGlobalSkipTag(tag4); }
224 static inline void registerGlobalSkipTag(const std::string& tag1, const std::string& tag2, const std::string& tag3, const std::string& tag4,
225     const std::string& tag5)
226 {
227     registerGlobalSkipTag(tag1); registerGlobalSkipTag(tag2); registerGlobalSkipTag(tag3); registerGlobalSkipTag(tag4);
228     registerGlobalSkipTag(tag5);
229 }
230 static inline void registerGlobalSkipTag(const std::string& tag1, const std::string& tag2, const std::string& tag3, const std::string& tag4,
231     const std::string& tag5, const std::string& tag6)
232 {
233     registerGlobalSkipTag(tag1); registerGlobalSkipTag(tag2); registerGlobalSkipTag(tag3); registerGlobalSkipTag(tag4);
234     registerGlobalSkipTag(tag5); registerGlobalSkipTag(tag6);
235 }
236 static inline void registerGlobalSkipTag(const std::string& tag1, const std::string& tag2, const std::string& tag3, const std::string& tag4,
237     const std::string& tag5, const std::string& tag6, const std::string& tag7)
238 {
239     registerGlobalSkipTag(tag1); registerGlobalSkipTag(tag2); registerGlobalSkipTag(tag3); registerGlobalSkipTag(tag4);
240     registerGlobalSkipTag(tag5); registerGlobalSkipTag(tag6); registerGlobalSkipTag(tag7);
241 }
242
243
244
245 class TS;
246
247 int64 readSeed(const char* str);
248
249 void randUni( RNG& rng, Mat& a, const Scalar& param1, const Scalar& param2 );
250
251 inline unsigned randInt( RNG& rng )
252 {
253     return (unsigned)rng;
254 }
255
256 inline  double randReal( RNG& rng )
257 {
258     return (double)rng;
259 }
260
261
262 const char* getTypeName( int type );
263 int typeByName( const char* type_name );
264
265 string vec2str(const string& sep, const int* v, size_t nelems);
266
267 inline int clipInt( int val, int min_val, int max_val )
268 {
269     if( val < min_val )
270         val = min_val;
271     if( val > max_val )
272         val = max_val;
273     return val;
274 }
275
276 double getMinVal(int depth);
277 double getMaxVal(int depth);
278
279 Size randomSize(RNG& rng, double maxSizeLog);
280 void randomSize(RNG& rng, int minDims, int maxDims, double maxSizeLog, vector<int>& sz);
281 int randomType(RNG& rng, int typeMask, int minChannels, int maxChannels);
282 Mat randomMat(RNG& rng, Size size, int type, double minVal, double maxVal, bool useRoi);
283 Mat randomMat(RNG& rng, const vector<int>& size, int type, double minVal, double maxVal, bool useRoi);
284 void add(const Mat& a, double alpha, const Mat& b, double beta,
285                       Scalar gamma, Mat& c, int ctype, bool calcAbs=false);
286 void multiply(const Mat& a, const Mat& b, Mat& c, double alpha=1);
287 void divide(const Mat& a, const Mat& b, Mat& c, double alpha=1);
288
289 void convert(const Mat& src, cv::OutputArray dst, int dtype, double alpha=1, double beta=0);
290 void copy(const Mat& src, Mat& dst, const Mat& mask=Mat(), bool invertMask=false);
291 void set(Mat& dst, const Scalar& gamma, const Mat& mask=Mat());
292
293 // working with multi-channel arrays
294 void extract( const Mat& a, Mat& plane, int coi );
295 void insert( const Mat& plane, Mat& a, int coi );
296
297 // checks that the array does not have NaNs and/or Infs and all the elements are
298 // within [min_val,max_val). idx is the index of the first "bad" element.
299 int check( const Mat& data, double min_val, double max_val, vector<int>* idx );
300
301 // modifies values that are close to zero
302 void  patchZeros( Mat& mat, double level );
303
304 void transpose(const Mat& src, Mat& dst);
305 void erode(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
306                       int borderType=0, const Scalar& borderValue=Scalar());
307 void dilate(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
308                        int borderType=0, const Scalar& borderValue=Scalar());
309 void filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel,
310                          Point anchor, double delta, int borderType,
311                          const Scalar& borderValue=Scalar());
312 void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right,
313                                int borderType, const Scalar& borderValue=Scalar());
314 Mat calcSobelKernel2D( int dx, int dy, int apertureSize, int origin=0 );
315 Mat calcLaplaceKernel2D( int aperture_size );
316
317 void initUndistortMap( const Mat& a, const Mat& k, Size sz, Mat& mapx, Mat& mapy );
318
319 void minMaxLoc(const Mat& src, double* minval, double* maxval,
320                           vector<int>* minloc, vector<int>* maxloc, const Mat& mask=Mat());
321 double norm(InputArray src, int normType, InputArray mask=noArray());
322 double norm(InputArray src1, InputArray src2, int normType, InputArray mask=noArray());
323 Scalar mean(const Mat& src, const Mat& mask=Mat());
324 double PSNR(InputArray src1, InputArray src2);
325
326 bool cmpUlps(const Mat& data, const Mat& refdata, int expMaxDiff, double* realMaxDiff, vector<int>* idx);
327
328 // compares two arrays. max_diff is the maximum actual difference,
329 // success_err_level is maximum allowed difference, idx is the index of the first
330 // element for which difference is >success_err_level
331 // (or index of element with the maximum difference)
332 int cmpEps( const Mat& data, const Mat& refdata, double* max_diff,
333                        double success_err_level, vector<int>* idx,
334                        bool element_wise_relative_error );
335
336 // a wrapper for the previous function. in case of error prints the message to log file.
337 int cmpEps2( TS* ts, const Mat& data, const Mat& refdata, double success_err_level,
338                         bool element_wise_relative_error, const char* desc );
339
340 int cmpEps2_64f( TS* ts, const double* val, const double* refval, int len,
341                         double eps, const char* param_name );
342
343 void logicOp(const Mat& src1, const Mat& src2, Mat& dst, char c);
344 void logicOp(const Mat& src, const Scalar& s, Mat& dst, char c);
345 void min(const Mat& src1, const Mat& src2, Mat& dst);
346 void min(const Mat& src, double s, Mat& dst);
347 void max(const Mat& src1, const Mat& src2, Mat& dst);
348 void max(const Mat& src, double s, Mat& dst);
349
350 void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop);
351 void compare(const Mat& src, double s, Mat& dst, int cmpop);
352 void gemm(const Mat& src1, const Mat& src2, double alpha,
353                      const Mat& src3, double beta, Mat& dst, int flags);
354 void transform( const Mat& src, Mat& dst, const Mat& transmat, const Mat& shift );
355 double crossCorr(const Mat& src1, const Mat& src2);
356 void threshold( const Mat& src, Mat& dst, double thresh, double maxval, int thresh_type );
357 void minMaxIdx( InputArray _img, double* minVal, double* maxVal,
358                     Point* minLoc, Point* maxLoc, InputArray _mask );
359
360 struct MatInfo
361 {
362     MatInfo(const Mat& _m) : m(&_m) {}
363     const Mat* m;
364 };
365
366 std::ostream& operator << (std::ostream& out, const MatInfo& m);
367
368 struct MatComparator
369 {
370 public:
371     MatComparator(double maxdiff, int context);
372
373     ::testing::AssertionResult operator()(const char* expr1, const char* expr2,
374                                           const Mat& m1, const Mat& m2);
375
376     double maxdiff;
377     double realmaxdiff;
378     vector<int> loc0;
379     int context;
380 };
381
382
383
384 class BaseTest;
385 class TS;
386
387 class BaseTest
388 {
389 public:
390     // constructor(s) and destructor
391     BaseTest();
392     virtual ~BaseTest();
393
394     // the main procedure of the test
395     virtual void run( int start_from );
396
397     // the wrapper for run that cares of exceptions
398     virtual void safe_run( int start_from=0 );
399
400     const string& get_name() const { return name; }
401
402     // returns true if and only if the different test cases do not depend on each other
403     // (so that test system could get right to a problematic test case)
404     virtual bool can_do_fast_forward();
405
406     // deallocates all the memory.
407     // called by init() (before initialization) and by the destructor
408     virtual void clear();
409
410 protected:
411     int test_case_count; // the total number of test cases
412
413     // read test params
414     virtual int read_params( CvFileStorage* fs );
415
416     // returns the number of tests or -1 if it is unknown a-priori
417     virtual int get_test_case_count();
418
419     // prepares data for the next test case. rng seed is updated by the function
420     virtual int prepare_test_case( int test_case_idx );
421
422     // checks if the test output is valid and accurate
423     virtual int validate_test_results( int test_case_idx );
424
425     // calls the tested function. the method is called from run_test_case()
426     virtual void run_func(); // runs tested func(s)
427
428     // updates progress bar
429     virtual int update_progress( int progress, int test_case_idx, int count, double dt );
430
431     // finds test parameter
432     const CvFileNode* find_param( CvFileStorage* fs, const char* param_name );
433
434     // name of the test (it is possible to locate a test by its name)
435     string name;
436
437     // pointer to the system that includes the test
438     TS* ts;
439 };
440
441
442 /*****************************************************************************************\
443 *                               Information about a failed test                           *
444 \*****************************************************************************************/
445
446 struct TestInfo
447 {
448     TestInfo();
449
450     // pointer to the test
451     BaseTest* test;
452
453     // failure code (TS::FAIL_*)
454     int code;
455
456     // seed value right before the data for the failed test case is prepared.
457     uint64 rng_seed;
458
459     // seed value right before running the test
460     uint64 rng_seed0;
461
462     // index of test case, can be then passed to BaseTest::proceed_to_test_case()
463     int test_case_idx;
464 };
465
466 /*****************************************************************************************\
467 *                                 Base Class for test system                              *
468 \*****************************************************************************************/
469
470 // common parameters:
471 struct TSParams
472 {
473     TSParams();
474
475     // RNG seed, passed to and updated by every test executed.
476     uint64 rng_seed;
477
478     // whether to use IPP, MKL etc. or not
479     bool use_optimized;
480
481     // extensivity of the tests, scale factor for test_case_count
482     double test_case_count_scale;
483 };
484
485
486 class TS
487 {
488     TS();
489     virtual ~TS();
490 public:
491
492     enum
493     {
494         NUL=0,
495         SUMMARY_IDX=0,
496         SUMMARY=1 << SUMMARY_IDX,
497         LOG_IDX=1,
498         LOG=1 << LOG_IDX,
499         CSV_IDX=2,
500         CSV=1 << CSV_IDX,
501         CONSOLE_IDX=3,
502         CONSOLE=1 << CONSOLE_IDX,
503         MAX_IDX=4
504     };
505
506     static TS* ptr();
507
508     // initialize test system before running the first test
509     virtual void init( const string& modulename );
510
511     // low-level printing functions that are used by individual tests and by the system itself
512     virtual void printf( int streams, const char* fmt, ... );
513     virtual void vprintf( int streams, const char* fmt, va_list arglist );
514
515     // updates the context: current test, test case, rng state
516     virtual void update_context( BaseTest* test, int test_case_idx, bool update_ts_context );
517
518     const TestInfo* get_current_test_info() { return &current_test_info; }
519
520     // sets information about a failed test
521     virtual void set_failed_test_info( int fail_code );
522
523     virtual void set_gtest_status();
524
525     // test error codes
526     enum FailureCode
527     {
528         // everything is Ok
529         OK=0,
530
531         // generic error: stub value to be used
532         // temporarily if the error's cause is unknown
533         FAIL_GENERIC=-1,
534
535         // the test is missing some essential data to proceed further
536         FAIL_MISSING_TEST_DATA=-2,
537
538         // the tested function raised an error via cxcore error handler
539         FAIL_ERROR_IN_CALLED_FUNC=-3,
540
541         // an exception has been raised;
542         // for memory and arithmetic exception
543         // there are two specialized codes (see below...)
544         FAIL_EXCEPTION=-4,
545
546         // a memory exception
547         // (access violation, access to missed page, stack overflow etc.)
548         FAIL_MEMORY_EXCEPTION=-5,
549
550         // arithmetic exception (overflow, division by zero etc.)
551         FAIL_ARITHM_EXCEPTION=-6,
552
553         // the tested function corrupted memory (no exception have been raised)
554         FAIL_MEMORY_CORRUPTION_BEGIN=-7,
555         FAIL_MEMORY_CORRUPTION_END=-8,
556
557         // the tested function (or test itself) do not deallocate some memory
558         FAIL_MEMORY_LEAK=-9,
559
560         // the tested function returned invalid object, e.g. matrix, containing NaNs,
561         // structure with NULL or out-of-range fields (while it should not)
562         FAIL_INVALID_OUTPUT=-10,
563
564         // the tested function returned valid object, but it does not match
565         // the original (or produced by the test) object
566         FAIL_MISMATCH=-11,
567
568         // the tested function returned valid object (a single number or numerical array),
569         // but it differs too much from the original (or produced by the test) object
570         FAIL_BAD_ACCURACY=-12,
571
572         // the tested function hung. Sometimes, it can be determined by unexpectedly long
573         // processing time (in this case there should be possibility to interrupt such a function
574         FAIL_HANG=-13,
575
576         // unexpected response on passing bad arguments to the tested function
577         // (the function crashed, proceed successfully (while it should not), or returned
578         // error code that is different from what is expected)
579         FAIL_BAD_ARG_CHECK=-14,
580
581         // the test data (in whole or for the particular test case) is invalid
582         FAIL_INVALID_TEST_DATA=-15,
583
584         // the test has been skipped because it is not in the selected subset of the tests to run,
585         // because it has been run already within the same run with the same parameters, or because
586         // of some other reason and this is not considered as an error.
587         // Normally TS::run() (or overridden method in the derived class) takes care of what
588         // needs to be run, so this code should not occur.
589         SKIPPED=1
590     };
591
592     // get RNG to generate random input data for a test
593     RNG& get_rng() { return rng; }
594
595     // returns the current error code
596     TS::FailureCode get_err_code() { return TS::FailureCode(current_test_info.code); }
597
598     // returns the test extensivity scale
599     double get_test_case_count_scale() { return params.test_case_count_scale; }
600
601     const string& get_data_path() const { return data_path; }
602
603     // returns textual description of failure code
604     static string str_from_code( const TS::FailureCode code );
605
606     std::vector<std::string> data_search_path;
607     std::vector<std::string> data_search_subdir;
608 protected:
609
610     // these are allocated within a test to try to keep them valid in case of stack corruption
611     RNG rng;
612
613     // information about the current test
614     TestInfo current_test_info;
615
616     // the path to data files used by tests
617     string data_path;
618
619     TSParams params;
620     std::string output_buf[MAX_IDX];
621 };
622
623
624 /*****************************************************************************************\
625 *            Subclass of BaseTest for testing functions that process dense arrays           *
626 \*****************************************************************************************/
627
628 class ArrayTest : public BaseTest
629 {
630 public:
631     // constructor(s) and destructor
632     ArrayTest();
633     virtual ~ArrayTest();
634
635     virtual void clear() CV_OVERRIDE;
636
637 protected:
638
639     virtual int read_params( CvFileStorage* fs ) CV_OVERRIDE;
640     virtual int prepare_test_case( int test_case_idx ) CV_OVERRIDE;
641     virtual int validate_test_results( int test_case_idx ) CV_OVERRIDE;
642
643     virtual void prepare_to_validation( int test_case_idx );
644     virtual void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types );
645     virtual void fill_array( int test_case_idx, int i, int j, Mat& arr );
646     virtual void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high );
647     virtual double get_success_error_level( int test_case_idx, int i, int j );
648
649     bool cvmat_allowed;
650     bool iplimage_allowed;
651     bool optional_mask;
652     bool element_wise_relative_error;
653
654     int min_log_array_size;
655     int max_log_array_size;
656
657     enum { INPUT, INPUT_OUTPUT, OUTPUT, REF_INPUT_OUTPUT, REF_OUTPUT, TEMP, MASK, MAX_ARR };
658
659     vector<vector<void*> > test_array;
660     vector<vector<Mat> > test_mat;
661     float buf[4];
662 };
663
664
665 class BadArgTest : public BaseTest
666 {
667 public:
668     // constructor(s) and destructor
669     BadArgTest();
670     virtual ~BadArgTest();
671
672 protected:
673     virtual int run_test_case( int expected_code, const string& descr );
674     virtual void run_func(void) CV_OVERRIDE = 0;
675     int test_case_idx;
676
677     template<class F>
678     int run_test_case( int expected_code, const string& _descr, F f)
679     {
680         int errcount = 0;
681         bool thrown = false;
682         const char* descr = _descr.c_str() ? _descr.c_str() : "";
683
684         try
685         {
686             f();
687         }
688         catch(const cv::Exception& e)
689         {
690             thrown = true;
691             if( e.code != expected_code )
692             {
693                 ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
694                     descr, test_case_idx, e.code, expected_code);
695                 errcount = 1;
696             }
697         }
698         catch(...)
699         {
700             thrown = true;
701             ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
702                        descr, test_case_idx);
703             errcount = 1;
704         }
705         if(!thrown)
706         {
707             ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
708                        descr, test_case_idx);
709             errcount = 1;
710         }
711         test_case_idx++;
712
713         return errcount;
714     }
715 };
716
717 extern uint64 param_seed;
718
719 struct DefaultRngAuto
720 {
721     const uint64 old_state;
722
723     DefaultRngAuto() : old_state(cv::theRNG().state) { cv::theRNG().state = cvtest::param_seed; }
724     ~DefaultRngAuto() { cv::theRNG().state = old_state; }
725
726     DefaultRngAuto& operator=(const DefaultRngAuto&);
727 };
728
729
730 // test images generation functions
731 void fillGradient(Mat& img, int delta = 5);
732 void smoothBorder(Mat& img, const Scalar& color, int delta = 3);
733
734 // Utility functions
735
736 void addDataSearchPath(const std::string& path);
737 void addDataSearchSubDirectory(const std::string& subdir);
738
739 /*! @brief Try to find requested data file
740
741   Search directories:
742
743   0. TS::data_search_path (search sub-directories are not used)
744   1. OPENCV_TEST_DATA_PATH environment variable
745   2. One of these:
746      a. OpenCV testdata based on build location: "./" + "share/OpenCV/testdata"
747      b. OpenCV testdata at install location: CMAKE_INSTALL_PREFIX + "share/OpenCV/testdata"
748
749   Search sub-directories:
750
751   - addDataSearchSubDirectory()
752   - modulename from TS::init()
753
754  */
755 std::string findDataFile(const std::string& relative_path, bool required = true);
756
757 /*! @brief Try to find requested data directory
758 @sa findDataFile
759  */
760 std::string findDataDirectory(const std::string& relative_path, bool required = true);
761
762 // Test definitions
763
764 class SystemInfoCollector : public testing::EmptyTestEventListener
765 {
766 private:
767     virtual void OnTestProgramStart(const testing::UnitTest&);
768 };
769
770 #ifndef __CV_TEST_EXEC_ARGS
771 #if defined(_MSC_VER) && (_MSC_VER <= 1400)
772 #define __CV_TEST_EXEC_ARGS(...)    \
773     while (++argc >= (--argc,-1)) {__VA_ARGS__; break;} /*this ugly construction is needed for VS 2005*/
774 #else
775 #define __CV_TEST_EXEC_ARGS(...)    \
776     __VA_ARGS__;
777 #endif
778 #endif
779
780 void parseCustomOptions(int argc, char **argv);
781
782 #define CV_TEST_INIT0_NOOP (void)0
783
784 #define CV_TEST_MAIN(resourcesubdir, ...) CV_TEST_MAIN_EX(resourcesubdir, NOOP, __VA_ARGS__)
785
786 #define CV_TEST_MAIN_EX(resourcesubdir, INIT0, ...) \
787 int main(int argc, char **argv) \
788 { \
789     CV_TRACE_FUNCTION(); \
790     { CV_TRACE_REGION("INIT"); \
791     using namespace cvtest; using namespace opencv_test; \
792     TS* ts = TS::ptr(); \
793     ts->init(resourcesubdir); \
794     __CV_TEST_EXEC_ARGS(CV_TEST_INIT0_ ## INIT0) \
795     ::testing::InitGoogleTest(&argc, argv); \
796     ::testing::UnitTest::GetInstance()->listeners().Append(new SystemInfoCollector); \
797     __CV_TEST_EXEC_ARGS(__VA_ARGS__) \
798     parseCustomOptions(argc, argv); \
799     } \
800     return RUN_ALL_TESTS(); \
801 }
802
803 // This usually only makes sense in perf tests with several implementations,
804 // some of which are not available.
805 #define CV_TEST_FAIL_NO_IMPL() do { \
806     ::testing::Test::RecordProperty("custom_status", "noimpl"); \
807     FAIL() << "No equivalent implementation."; \
808 } while (0)
809
810 } //namespace cvtest
811
812 #include "opencv2/ts/ts_perf.hpp"
813
814 namespace cvtest {
815 using perf::MatDepth;
816 using perf::MatType;
817 }
818
819 #ifdef WINRT
820 #ifndef __FSTREAM_EMULATED__
821 #define __FSTREAM_EMULATED__
822 #include <stdlib.h>
823 #include <fstream>
824 #include <sstream>
825
826 #undef ifstream
827 #undef ofstream
828 #define ifstream ifstream_emulated
829 #define ofstream ofstream_emulated
830
831 namespace std {
832
833 class ifstream : public stringstream
834 {
835     FILE* f;
836 public:
837     ifstream(const char* filename, ios_base::openmode mode = ios_base::in)
838         : f(NULL)
839     {
840         string modeStr("r");
841         printf("Open file (read): %s\n", filename);
842         if (mode & ios_base::binary)
843             modeStr += "b";
844         f = fopen(filename, modeStr.c_str());
845
846         if (f == NULL)
847         {
848             printf("Can't open file: %s\n", filename);
849             return;
850         }
851         fseek(f, 0, SEEK_END);
852         size_t sz = ftell(f);
853         if (sz > 0)
854         {
855             char* buf = (char*) malloc(sz);
856             fseek(f, 0, SEEK_SET);
857             if (fread(buf, 1, sz, f) == sz)
858             {
859                 this->str(std::string(buf, sz));
860             }
861             free(buf);
862         }
863     }
864
865     ~ifstream() { close(); }
866     bool is_open() const { return f != NULL; }
867     void close()
868     {
869         if (f)
870             fclose(f);
871         f = NULL;
872         this->str("");
873     }
874 };
875
876 class ofstream : public stringstream
877 {
878     FILE* f;
879 public:
880     ofstream(const char* filename, ios_base::openmode mode = ios_base::out)
881     : f(NULL)
882     {
883         open(filename, mode);
884     }
885     ~ofstream() { close(); }
886     void open(const char* filename, ios_base::openmode mode = ios_base::out)
887     {
888         string modeStr("w+");
889         if (mode & ios_base::trunc)
890             modeStr = "w";
891         if (mode & ios_base::binary)
892             modeStr += "b";
893         f = fopen(filename, modeStr.c_str());
894         printf("Open file (write): %s\n", filename);
895         if (f == NULL)
896         {
897             printf("Can't open file (write): %s\n", filename);
898             return;
899         }
900     }
901     bool is_open() const { return f != NULL; }
902     void close()
903     {
904         if (f)
905         {
906             fwrite(reinterpret_cast<const char *>(this->str().c_str()), this->str().size(), 1, f);
907             fclose(f);
908         }
909         f = NULL;
910         this->str("");
911     }
912 };
913
914 } // namespace std
915 #endif // __FSTREAM_EMULATED__
916 #endif // WINRT
917
918
919 namespace opencv_test {
920 using namespace cvtest;
921 using namespace cv;
922
923 #ifdef CV_CXX11
924 #define CVTEST_GUARD_SYMBOL(name) \
925     class required_namespace_specificatin_here_for_symbol_ ## name {}; \
926     using name = required_namespace_specificatin_here_for_symbol_ ## name;
927 #else
928 #define CVTEST_GUARD_SYMBOL(name) /* nothing */
929 #endif
930
931 CVTEST_GUARD_SYMBOL(norm)
932 CVTEST_GUARD_SYMBOL(add)
933 CVTEST_GUARD_SYMBOL(multiply)
934 CVTEST_GUARD_SYMBOL(divide)
935 CVTEST_GUARD_SYMBOL(transpose)
936 CVTEST_GUARD_SYMBOL(copyMakeBorder)
937 CVTEST_GUARD_SYMBOL(filter2D)
938 CVTEST_GUARD_SYMBOL(compare)
939 CVTEST_GUARD_SYMBOL(minMaxIdx)
940 CVTEST_GUARD_SYMBOL(threshold)
941
942 extern bool required_opencv_test_namespace;  // compilation check for non-refactored tests
943 }
944
945 #endif // OPENCV_TS_HPP