ts: test case list is printed after cmd line parsing, refactored
[platform/upstream/opencv.git] / modules / ts / src / ts.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of Intel Corporation may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42 #include "precomp.hpp"
43 #include "opencv2/core/core_c.h"
44
45 #include <ctype.h>
46 #include <stdarg.h>
47 #include <stdlib.h>
48 #include <fcntl.h>
49 #include <time.h>
50 #if defined _WIN32
51 #include <io.h>
52
53 #include <windows.h>
54 #undef small
55 #undef min
56 #undef max
57 #undef abs
58
59 #ifdef _MSC_VER
60 #include <eh.h>
61 #endif
62
63 #else
64 #include <unistd.h>
65 #include <signal.h>
66 #include <setjmp.h>
67 #endif
68
69 // isDirectory
70 #if defined _WIN32 || defined WINCE
71 # include <windows.h>
72 #else
73 # include <dirent.h>
74 # include <sys/stat.h>
75 #endif
76
77 #ifdef HAVE_OPENCL
78
79 #define DUMP_CONFIG_PROPERTY(propertyName, propertyValue) \
80     do { \
81         std::stringstream ssName, ssValue;\
82         ssName << propertyName;\
83         ssValue << (propertyValue); \
84         ::testing::Test::RecordProperty(ssName.str(), ssValue.str()); \
85     } while (false)
86
87 #define DUMP_MESSAGE_STDOUT(msg) \
88     do { \
89         std::cout << msg << std::endl; \
90     } while (false)
91
92 #include "opencv2/core/opencl/opencl_info.hpp"
93
94 #endif // HAVE_OPENCL
95
96 #include "opencv2/core/utility.hpp"
97 #include "opencv_tests_config.hpp"
98
99 namespace opencv_test {
100 bool required_opencv_test_namespace = false;  // compilation check for non-refactored tests
101 }
102
103 namespace cvtest
104 {
105
106 uint64 param_seed = 0x12345678; // real value is passed via parseCustomOptions function
107
108 static std::string path_join(const std::string& prefix, const std::string& subpath)
109 {
110     CV_Assert(subpath.empty() || subpath[0] != '/');
111     if (prefix.empty())
112         return subpath;
113     bool skipSlash = prefix.size() > 0 ? (prefix[prefix.size()-1] == '/' || prefix[prefix.size()-1] == '\\') : false;
114     std::string path = prefix + (skipSlash ? "" : "/") + subpath;
115     return path;
116 }
117
118
119
120 /*****************************************************************************************\
121 *                                Exception and memory handlers                            *
122 \*****************************************************************************************/
123
124 // a few platform-dependent declarations
125
126 #if defined _WIN32
127 #ifdef _MSC_VER
128 static void SEHTranslator( unsigned int /*u*/, EXCEPTION_POINTERS* pExp )
129 {
130     TS::FailureCode code = TS::FAIL_EXCEPTION;
131     switch( pExp->ExceptionRecord->ExceptionCode )
132     {
133     case EXCEPTION_ACCESS_VIOLATION:
134     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
135     case EXCEPTION_DATATYPE_MISALIGNMENT:
136     case EXCEPTION_FLT_STACK_CHECK:
137     case EXCEPTION_STACK_OVERFLOW:
138     case EXCEPTION_IN_PAGE_ERROR:
139         code = TS::FAIL_MEMORY_EXCEPTION;
140         break;
141     case EXCEPTION_FLT_DENORMAL_OPERAND:
142     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
143     case EXCEPTION_FLT_INEXACT_RESULT:
144     case EXCEPTION_FLT_INVALID_OPERATION:
145     case EXCEPTION_FLT_OVERFLOW:
146     case EXCEPTION_FLT_UNDERFLOW:
147     case EXCEPTION_INT_DIVIDE_BY_ZERO:
148     case EXCEPTION_INT_OVERFLOW:
149         code = TS::FAIL_ARITHM_EXCEPTION;
150         break;
151     case EXCEPTION_BREAKPOINT:
152     case EXCEPTION_ILLEGAL_INSTRUCTION:
153     case EXCEPTION_INVALID_DISPOSITION:
154     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
155     case EXCEPTION_PRIV_INSTRUCTION:
156     case EXCEPTION_SINGLE_STEP:
157         code = TS::FAIL_EXCEPTION;
158     }
159     throw code;
160 }
161 #endif
162
163 #else
164
165 static const int tsSigId[] = { SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT, -1 };
166
167 static jmp_buf tsJmpMark;
168
169 static void signalHandler( int sig_code )
170 {
171     TS::FailureCode code = TS::FAIL_EXCEPTION;
172     switch( sig_code )
173     {
174     case SIGFPE:
175         code = TS::FAIL_ARITHM_EXCEPTION;
176         break;
177     case SIGSEGV:
178     case SIGBUS:
179         code = TS::FAIL_ARITHM_EXCEPTION;
180         break;
181     case SIGILL:
182         code = TS::FAIL_EXCEPTION;
183     }
184
185     longjmp( tsJmpMark, (int)code );
186 }
187
188 #endif
189
190
191 // reads 16-digit hexadecimal number (i.e. 64-bit integer)
192 int64 readSeed( const char* str )
193 {
194     int64 val = 0;
195     if( str && strlen(str) == 16 )
196     {
197         for( int i = 0; str[i]; i++ )
198         {
199             int c = tolower(str[i]);
200             if( !isxdigit(c) )
201                 return 0;
202             val = val * 16 +
203             (str[i] < 'a' ? str[i] - '0' : str[i] - 'a' + 10);
204         }
205     }
206     return val;
207 }
208
209
210 /*****************************************************************************************\
211 *                                    Base Class for Tests                                 *
212 \*****************************************************************************************/
213
214 BaseTest::BaseTest()
215 {
216     ts = TS::ptr();
217     test_case_count = -1;
218 }
219
220 BaseTest::~BaseTest()
221 {
222     clear();
223 }
224
225 void BaseTest::clear()
226 {
227 }
228
229
230 const CvFileNode* BaseTest::find_param( CvFileStorage* fs, const char* param_name )
231 {
232     CvFileNode* node = cvGetFileNodeByName(fs, 0, get_name().c_str());
233     return node ? cvGetFileNodeByName( fs, node, param_name ) : 0;
234 }
235
236
237 int BaseTest::read_params( CvFileStorage* )
238 {
239     return 0;
240 }
241
242
243 bool BaseTest::can_do_fast_forward()
244 {
245     return true;
246 }
247
248
249 void BaseTest::safe_run( int start_from )
250 {
251     CV_TRACE_FUNCTION();
252     ts->update_context( 0, -1, true );
253     ts->update_context( this, -1, true );
254
255     if( !::testing::GTEST_FLAG(catch_exceptions) )
256         run( start_from );
257     else
258     {
259         try
260         {
261         #if !defined _WIN32
262         int _code = setjmp( tsJmpMark );
263         if( !_code )
264             run( start_from );
265         else
266             throw TS::FailureCode(_code);
267         #else
268             run( start_from );
269         #endif
270         }
271         catch (const cv::Exception& exc)
272         {
273             const char* errorStr = cvErrorStr(exc.code);
274             char buf[1 << 16];
275
276             const char* delim = exc.err.find('\n') == cv::String::npos ? "" : "\n";
277             sprintf( buf, "OpenCV Error:\n\t%s (%s%s) in %s, file %s, line %d",
278                     errorStr, delim, exc.err.c_str(), exc.func.size() > 0 ?
279                     exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line );
280             ts->printf(TS::LOG, "%s\n", buf);
281
282             ts->set_failed_test_info( TS::FAIL_ERROR_IN_CALLED_FUNC );
283         }
284         catch (const TS::FailureCode& fc)
285         {
286             std::string errorStr = TS::str_from_code(fc);
287             ts->printf(TS::LOG, "General failure:\n\t%s (%d)\n", errorStr.c_str(), fc);
288
289             ts->set_failed_test_info( fc );
290         }
291         catch (...)
292         {
293             ts->printf(TS::LOG, "Unknown failure\n");
294
295             ts->set_failed_test_info( TS::FAIL_EXCEPTION );
296         }
297     }
298
299     ts->set_gtest_status();
300 }
301
302
303 void BaseTest::run( int start_from )
304 {
305     int test_case_idx, count = get_test_case_count();
306     int64 t_start = cvGetTickCount();
307     double freq = cv::getTickFrequency();
308     bool ff = can_do_fast_forward();
309     int progress = 0, code;
310     int64 t1 = t_start;
311
312     for( test_case_idx = ff && start_from >= 0 ? start_from : 0;
313          count < 0 || test_case_idx < count; test_case_idx++ )
314     {
315         ts->update_context( this, test_case_idx, ff );
316         progress = update_progress( progress, test_case_idx, count, (double)(t1 - t_start)/(freq*1000) );
317
318         code = prepare_test_case( test_case_idx );
319         if( code < 0 || ts->get_err_code() < 0 )
320             return;
321
322         if( code == 0 )
323             continue;
324
325         run_func();
326
327         if( ts->get_err_code() < 0 )
328             return;
329
330         if( validate_test_results( test_case_idx ) < 0 || ts->get_err_code() < 0 )
331             return;
332     }
333 }
334
335
336 void BaseTest::run_func(void)
337 {
338     assert(0);
339 }
340
341
342 int BaseTest::get_test_case_count(void)
343 {
344     return test_case_count;
345 }
346
347
348 int BaseTest::prepare_test_case( int )
349 {
350     return 0;
351 }
352
353
354 int BaseTest::validate_test_results( int )
355 {
356     return 0;
357 }
358
359
360 int BaseTest::update_progress( int progress, int test_case_idx, int count, double dt )
361 {
362     int width = 60 - (int)get_name().size();
363     if( count > 0 )
364     {
365         int t = cvRound( ((double)test_case_idx * width)/count );
366         if( t > progress )
367         {
368             ts->printf( TS::CONSOLE, "." );
369             progress = t;
370         }
371     }
372     else if( cvRound(dt) > progress )
373     {
374         ts->printf( TS::CONSOLE, "." );
375         progress = cvRound(dt);
376     }
377
378     return progress;
379 }
380
381
382 BadArgTest::BadArgTest()
383 {
384     test_case_idx   = -1;
385     // oldErrorCbk     = 0;
386     // oldErrorCbkData = 0;
387 }
388
389 BadArgTest::~BadArgTest(void)
390 {
391 }
392
393 int BadArgTest::run_test_case( int expected_code, const string& _descr )
394 {
395     int errcount = 0;
396     bool thrown = false;
397     const char* descr = _descr.c_str() ? _descr.c_str() : "";
398
399     try
400     {
401         run_func();
402     }
403     catch(const cv::Exception& e)
404     {
405         thrown = true;
406         if (e.code != expected_code &&
407             e.code != cv::Error::StsError && e.code != cv::Error::StsAssert  // Exact error codes support will be dropped. Checks should provide proper text messages intead.
408         )
409         {
410             ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
411                        descr, test_case_idx, e.code, expected_code);
412             errcount = 1;
413         }
414     }
415     catch(...)
416     {
417         thrown = true;
418         ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
419                    descr, test_case_idx);
420         errcount = 1;
421     }
422
423     if(!thrown)
424     {
425         ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
426                    descr, test_case_idx);
427         errcount = 1;
428     }
429     test_case_idx++;
430
431     return errcount;
432 }
433
434 /*****************************************************************************************\
435 *                                 Base Class for Test System                              *
436 \*****************************************************************************************/
437
438 /******************************** Constructors/Destructors ******************************/
439
440 TSParams::TSParams()
441 {
442     rng_seed = (uint64)-1;
443     use_optimized = true;
444     test_case_count_scale = 1;
445 }
446
447
448 TestInfo::TestInfo()
449 {
450     test = 0;
451     code = 0;
452     rng_seed = rng_seed0 = 0;
453     test_case_idx = -1;
454 }
455
456
457 TS::TS()
458 {
459 } // ctor
460
461
462 TS::~TS()
463 {
464 } // dtor
465
466
467 string TS::str_from_code( const TS::FailureCode code )
468 {
469     switch( code )
470     {
471     case OK:                           return "Ok";
472     case FAIL_GENERIC:                 return "Generic/Unknown";
473     case FAIL_MISSING_TEST_DATA:       return "No test data";
474     case FAIL_INVALID_TEST_DATA:       return "Invalid test data";
475     case FAIL_ERROR_IN_CALLED_FUNC:    return "cvError invoked";
476     case FAIL_EXCEPTION:               return "Hardware/OS exception";
477     case FAIL_MEMORY_EXCEPTION:        return "Invalid memory access";
478     case FAIL_ARITHM_EXCEPTION:        return "Arithmetic exception";
479     case FAIL_MEMORY_CORRUPTION_BEGIN: return "Corrupted memblock (beginning)";
480     case FAIL_MEMORY_CORRUPTION_END:   return "Corrupted memblock (end)";
481     case FAIL_MEMORY_LEAK:             return "Memory leak";
482     case FAIL_INVALID_OUTPUT:          return "Invalid function output";
483     case FAIL_MISMATCH:                return "Unexpected output";
484     case FAIL_BAD_ACCURACY:            return "Bad accuracy";
485     case FAIL_HANG:                    return "Infinite loop(?)";
486     case FAIL_BAD_ARG_CHECK:           return "Incorrect handling of bad arguments";
487     default:
488             ;
489     }
490     return "Generic/Unknown";
491 }
492
493 static int tsErrorCallback( int status, const char* func_name, const char* err_msg, const char* file_name, int line, TS* ts )
494 {
495     const char* delim = std::string(err_msg).find('\n') == std::string::npos ? "" : "\n";
496     ts->printf(TS::LOG, "OpenCV Error:\n\t%s (%s%s) in %s, file %s, line %d\n", cvErrorStr(status), delim, err_msg, func_name[0] != 0 ? func_name : "unknown function", file_name, line);
497     return 0;
498 }
499
500 /************************************** Running tests **********************************/
501
502 void TS::init( const string& modulename )
503 {
504     data_search_subdir.push_back(modulename);
505 #ifndef WINRT
506     char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
507 #else
508     char* datapath_dir = OPENCV_TEST_DATA_PATH;
509 #endif
510
511     if( datapath_dir )
512     {
513         data_path = path_join(path_join(datapath_dir, modulename), "");
514     }
515
516     cv::redirectError((cv::ErrorCallback)tsErrorCallback, this);
517
518     if( ::testing::GTEST_FLAG(catch_exceptions) )
519     {
520 #if defined _WIN32
521 #ifdef _MSC_VER
522         _set_se_translator( SEHTranslator );
523 #endif
524 #else
525         for( int i = 0; tsSigId[i] >= 0; i++ )
526             signal( tsSigId[i], signalHandler );
527 #endif
528     }
529     else
530     {
531 #if defined _WIN32
532 #ifdef _MSC_VER
533         _set_se_translator( 0 );
534 #endif
535 #else
536         for( int i = 0; tsSigId[i] >= 0; i++ )
537             signal( tsSigId[i], SIG_DFL );
538 #endif
539     }
540
541     if( params.use_optimized == 0 )
542         cv::setUseOptimized(false);
543
544     rng = RNG(params.rng_seed);
545 }
546
547
548 void TS::set_gtest_status()
549 {
550     TS::FailureCode code = get_err_code();
551     if( code >= 0 )
552         return SUCCEED();
553
554     char seedstr[32];
555     sprintf(seedstr, "%08x%08x", (unsigned)(current_test_info.rng_seed>>32),
556                                 (unsigned)(current_test_info.rng_seed));
557
558     string logs = "";
559     if( !output_buf[SUMMARY_IDX].empty() )
560         logs += "\n-----------------------------------\n\tSUM: " + output_buf[SUMMARY_IDX];
561     if( !output_buf[LOG_IDX].empty() )
562         logs += "\n-----------------------------------\n\tLOG:\n" + output_buf[LOG_IDX];
563     if( !output_buf[CONSOLE_IDX].empty() )
564         logs += "\n-----------------------------------\n\tCONSOLE: " + output_buf[CONSOLE_IDX];
565     logs += "\n-----------------------------------\n";
566
567     FAIL() << "\n\tfailure reason: " << str_from_code(code) <<
568         "\n\ttest case #" << current_test_info.test_case_idx <<
569         "\n\tseed: " << seedstr << logs;
570 }
571
572
573 void TS::update_context( BaseTest* test, int test_case_idx, bool update_ts_context )
574 {
575     if( current_test_info.test != test )
576     {
577         for( int i = 0; i <= CONSOLE_IDX; i++ )
578             output_buf[i] = string();
579         rng = RNG(params.rng_seed);
580         current_test_info.rng_seed0 = current_test_info.rng_seed = rng.state;
581     }
582
583     current_test_info.test = test;
584     current_test_info.test_case_idx = test_case_idx;
585     current_test_info.code = 0;
586     cvSetErrStatus( CV_StsOk );
587     if( update_ts_context )
588         current_test_info.rng_seed = rng.state;
589 }
590
591
592 void TS::set_failed_test_info( int fail_code )
593 {
594     if( current_test_info.code >= 0 )
595         current_test_info.code = TS::FailureCode(fail_code);
596 }
597
598 #if defined _MSC_VER && _MSC_VER < 1400
599 #undef vsnprintf
600 #define vsnprintf _vsnprintf
601 #endif
602
603 void TS::vprintf( int streams, const char* fmt, va_list l )
604 {
605     char str[1 << 14];
606     vsnprintf( str, sizeof(str)-1, fmt, l );
607
608     for( int i = 0; i < MAX_IDX; i++ )
609         if( (streams & (1 << i)) )
610         {
611             output_buf[i] += std::string(str);
612             // in the new GTest-based framework we do not use
613             // any output files (except for the automatically generated xml report).
614             // if a test fails, all the buffers are printed, so we do not want to duplicate the information and
615             // thus only add the new information to a single buffer and return from the function.
616             break;
617         }
618 }
619
620
621 void TS::printf( int streams, const char* fmt, ... )
622 {
623     if( streams )
624     {
625         va_list l;
626         va_start( l, fmt );
627         vprintf( streams, fmt, l );
628         va_end( l );
629     }
630 }
631
632
633 TS* TS::ptr()
634 {
635     static TS ts;
636     return &ts;
637 }
638
639 void fillGradient(Mat& img, int delta)
640 {
641     const int ch = img.channels();
642     CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
643
644     int n = 255 / delta;
645     int r, c, i;
646     for(r=0; r<img.rows; r++)
647     {
648         int kR = r % (2*n);
649         int valR = (kR<=n) ? delta*kR : delta*(2*n-kR);
650         for(c=0; c<img.cols; c++)
651         {
652             int kC = c % (2*n);
653             int valC = (kC<=n) ? delta*kC : delta*(2*n-kC);
654             uchar vals[] = {uchar(valR), uchar(valC), uchar(200*r/img.rows), uchar(255)};
655             uchar *p = img.ptr(r, c);
656             for(i=0; i<ch; i++) p[i] = vals[i];
657         }
658     }
659 }
660
661 void smoothBorder(Mat& img, const Scalar& color, int delta)
662 {
663     const int ch = img.channels();
664     CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
665
666     Scalar s;
667     uchar *p = NULL;
668     int n = 100/delta;
669     int nR = std::min(n, (img.rows+1)/2), nC = std::min(n, (img.cols+1)/2);
670
671     int r, c, i;
672     for(r=0; r<nR; r++)
673     {
674         double k1 = r*delta/100., k2 = 1-k1;
675         for(c=0; c<img.cols; c++)
676         {
677             p = img.ptr(r, c);
678             for(i=0; i<ch; i++) s[i] = p[i];
679             s = s * k1 + color * k2;
680             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
681         }
682         for(c=0; c<img.cols; c++)
683         {
684             p = img.ptr(img.rows-r-1, c);
685             for(i=0; i<ch; i++) s[i] = p[i];
686             s = s * k1 + color * k2;
687             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
688         }
689     }
690
691     for(r=0; r<img.rows; r++)
692     {
693         for(c=0; c<nC; c++)
694         {
695             double k1 = c*delta/100., k2 = 1-k1;
696             p = img.ptr(r, c);
697             for(i=0; i<ch; i++) s[i] = p[i];
698             s = s * k1 + color * k2;
699             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
700         }
701         for(c=0; c<n; c++)
702         {
703             double k1 = c*delta/100., k2 = 1-k1;
704             p = img.ptr(r, img.cols-c-1);
705             for(i=0; i<ch; i++) s[i] = p[i];
706             s = s * k1 + color * k2;
707             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
708         }
709     }
710 }
711
712
713 bool test_ipp_check = false;
714
715 void checkIppStatus()
716 {
717     if (test_ipp_check)
718     {
719         int status = cv::ipp::getIppStatus();
720         EXPECT_LE(0, status) << cv::ipp::getIppErrorLocation().c_str();
721     }
722 }
723
724 bool skipUnstableTests = false;
725 bool runBigDataTests = false;
726 int testThreads = 0;
727
728 void parseCustomOptions(int argc, char **argv)
729 {
730     const char * const command_line_keys =
731         "{ ipp test_ipp_check |false    |check whether IPP works without failures }"
732         "{ test_seed          |809564   |seed for random numbers generator }"
733         "{ test_threads       |-1       |the number of worker threads, if parallel execution is enabled}"
734         "{ skip_unstable      |false    |skip unstable tests }"
735         "{ test_bigdata       |false    |run BigData tests (>=2Gb) }"
736         "{ h   help           |false    |print help info                          }";
737
738     cv::CommandLineParser parser(argc, argv, command_line_keys);
739     if (parser.get<bool>("help"))
740     {
741         std::cout << "\nAvailable options besides google test option: \n";
742         parser.printMessage();
743     }
744
745     test_ipp_check = parser.get<bool>("test_ipp_check");
746     if (!test_ipp_check)
747 #ifndef WINRT
748         test_ipp_check = getenv("OPENCV_IPP_CHECK") != NULL;
749 #else
750         test_ipp_check = false;
751 #endif
752
753     param_seed = parser.get<unsigned int>("test_seed");
754
755     testThreads = parser.get<int>("test_threads");
756
757     skipUnstableTests = parser.get<bool>("skip_unstable");
758     runBigDataTests = parser.get<bool>("test_bigdata");
759 }
760
761
762 static bool isDirectory(const std::string& path)
763 {
764 #if defined _WIN32 || defined WINCE
765     WIN32_FILE_ATTRIBUTE_DATA all_attrs;
766 #ifdef WINRT
767     wchar_t wpath[MAX_PATH];
768     size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
769     CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
770     BOOL status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs);
771 #else
772     BOOL status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
773 #endif
774     DWORD attributes = all_attrs.dwFileAttributes;
775     return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
776 #else
777     struct stat s;
778     if (0 != stat(path.c_str(), &s))
779         return false;
780     return S_ISDIR(s.st_mode);
781 #endif
782 }
783
784 void addDataSearchPath(const std::string& path)
785 {
786     if (isDirectory(path))
787         TS::ptr()->data_search_path.push_back(path);
788 }
789 void addDataSearchSubDirectory(const std::string& subdir)
790 {
791     TS::ptr()->data_search_subdir.push_back(subdir);
792 }
793
794 static std::string findData(const std::string& relative_path, bool required, bool findDirectory)
795 {
796 #define TEST_TRY_FILE_WITH_PREFIX(prefix) \
797 { \
798     std::string path = path_join(prefix, relative_path); \
799     /*printf("Trying %s\n", path.c_str());*/ \
800     if (findDirectory) \
801     { \
802         if (isDirectory(path)) \
803             return path; \
804     } \
805     else \
806     { \
807         FILE* f = fopen(path.c_str(), "rb"); \
808         if(f) { \
809             fclose(f); \
810             return path; \
811         } \
812     } \
813 }
814
815     const std::vector<std::string>& search_path = TS::ptr()->data_search_path;
816     for(size_t i = search_path.size(); i > 0; i--)
817     {
818         const std::string& prefix = search_path[i - 1];
819         TEST_TRY_FILE_WITH_PREFIX(prefix);
820     }
821
822     const std::vector<std::string>& search_subdir = TS::ptr()->data_search_subdir;
823
824 #ifndef WINRT
825     char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
826 #else
827     char* datapath_dir = OPENCV_TEST_DATA_PATH;
828 #endif
829
830     std::string datapath;
831     if (datapath_dir)
832     {
833         datapath = datapath_dir;
834         //CV_Assert(isDirectory(datapath) && "OPENCV_TEST_DATA_PATH is specified but it doesn't exist");
835         if (isDirectory(datapath))
836         {
837             for(size_t i = search_subdir.size(); i > 0; i--)
838             {
839                 const std::string& subdir = search_subdir[i - 1];
840                 std::string prefix = path_join(datapath, subdir);
841                 TEST_TRY_FILE_WITH_PREFIX(prefix);
842             }
843         }
844     }
845 #ifdef OPENCV_TEST_DATA_INSTALL_PATH
846     datapath = path_join("./", OPENCV_TEST_DATA_INSTALL_PATH);
847     if (isDirectory(datapath))
848     {
849         for(size_t i = search_subdir.size(); i > 0; i--)
850         {
851             const std::string& subdir = search_subdir[i - 1];
852             std::string prefix = path_join(datapath, subdir);
853             TEST_TRY_FILE_WITH_PREFIX(prefix);
854         }
855     }
856 #ifdef OPENCV_INSTALL_PREFIX
857     else
858     {
859         datapath = path_join(OPENCV_INSTALL_PREFIX, OPENCV_TEST_DATA_INSTALL_PATH);
860         if (isDirectory(datapath))
861         {
862             for(size_t i = search_subdir.size(); i > 0; i--)
863             {
864                 const std::string& subdir = search_subdir[i - 1];
865                 std::string prefix = path_join(datapath, subdir);
866                 TEST_TRY_FILE_WITH_PREFIX(prefix);
867             }
868         }
869     }
870 #endif
871 #endif
872     const char* type = findDirectory ? "directory" : "data file";
873     if (required)
874         CV_Error(cv::Error::StsError, cv::format("OpenCV tests: Can't find required %s: %s", type, relative_path.c_str()));
875     throw SkipTestException(cv::format("OpenCV tests: Can't find %s: %s", type, relative_path.c_str()));
876 }
877
878 std::string findDataFile(const std::string& relative_path, bool required)
879 {
880     return findData(relative_path, required, false);
881 }
882
883 std::string findDataDirectory(const std::string& relative_path, bool required)
884 {
885     return findData(relative_path, required, true);
886 }
887
888 inline static std::string getSnippetFromConfig(const std::string & start, const std::string & end)
889 {
890     const std::string buildInfo = cv::getBuildInformation();
891     size_t pos1 = buildInfo.find(start);
892     if (pos1 != std::string::npos)
893     {
894         pos1 += start.length();
895         pos1 = buildInfo.find_first_not_of(" \t\n\r", pos1);
896     }
897     size_t pos2 = buildInfo.find(end, pos1);
898     if (pos2 != std::string::npos)
899     {
900         pos2 = buildInfo.find_last_not_of(" \t\n\r", pos2);
901     }
902     if (pos1 != std::string::npos && pos2 != std::string::npos && pos1 < pos2)
903     {
904         return buildInfo.substr(pos1, pos2 - pos1 + 1);
905     }
906     return std::string();
907 }
908
909 inline static void recordPropertyVerbose(const std::string & property,
910                                          const std::string & msg,
911                                          const std::string & value,
912                                          const std::string & build_value = std::string())
913 {
914     ::testing::Test::RecordProperty(property, value);
915     std::cout << msg << ": " << (value.empty() ? std::string("N/A") : value) << std::endl;
916     if (!build_value.empty())
917     {
918         ::testing::Test::RecordProperty(property + "_build", build_value);
919         if (build_value != value)
920             std::cout << "WARNING: build value differs from runtime: " << build_value << endl;
921     }
922 }
923
924 #ifdef _DEBUG
925 #define CV_TEST_BUILD_CONFIG "Debug"
926 #else
927 #define CV_TEST_BUILD_CONFIG "Release"
928 #endif
929
930 void SystemInfoCollector::OnTestProgramStart(const testing::UnitTest&)
931 {
932     std::cout << "CTEST_FULL_OUTPUT" << std::endl; // Tell CTest not to discard any output
933     recordPropertyVerbose("cv_version", "OpenCV version", cv::getVersionString(), CV_VERSION);
934     recordPropertyVerbose("cv_vcs_version", "OpenCV VCS version", getSnippetFromConfig("Version control:", "\n"));
935     recordPropertyVerbose("cv_build_type", "Build type", getSnippetFromConfig("Configuration:", "\n"), CV_TEST_BUILD_CONFIG);
936     recordPropertyVerbose("cv_compiler", "Compiler", getSnippetFromConfig("C++ Compiler:", "\n"));
937     recordPropertyVerbose("cv_parallel_framework", "Parallel framework", cv::currentParallelFramework());
938     recordPropertyVerbose("cv_cpu_features", "CPU features", cv::getCPUFeaturesLine());
939 #ifdef HAVE_IPP
940     recordPropertyVerbose("cv_ipp_version", "Intel(R) IPP version", cv::ipp::useIPP() ? cv::ipp::getIppVersion() :  "disabled");
941 #endif
942 #ifdef HAVE_OPENCL
943     cv::dumpOpenCLInformation();
944 #endif
945 }
946
947 } //namespace cvtest
948
949 /* End of file. */