Merge remote-tracking branch 'upstream/3.4' into merge-3.4
[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 #include "opencv2/core/utils/allocator_stats.hpp"
95 namespace cv { namespace ocl {
96 cv::utils::AllocatorStatisticsInterface& getOpenCLAllocatorStatistics();
97 }}
98 #endif // HAVE_OPENCL
99
100 #include "opencv2/core/utils/allocator_stats.hpp"
101 namespace cv {
102 CV_EXPORTS cv::utils::AllocatorStatisticsInterface& getAllocatorStatistics();
103 }
104
105 #include "opencv_tests_config.hpp"
106
107 #include "ts_tags.hpp"
108
109 #if defined(__GNUC__) && defined(__linux__)
110 extern "C" {
111 size_t malloc_peak(void) __attribute__((weak));
112 void malloc_reset_peak(void) __attribute__((weak));
113 } // extern "C"
114 #else // stubs
115 static size_t (*malloc_peak)(void) = 0;
116 static void (*malloc_reset_peak)(void) = 0;
117 #endif
118
119 namespace opencv_test {
120 bool required_opencv_test_namespace = false;  // compilation check for non-refactored tests
121 }
122
123 namespace cvtest
124 {
125
126 uint64 param_seed = 0x12345678; // real value is passed via parseCustomOptions function
127
128 static std::string path_join(const std::string& prefix, const std::string& subpath)
129 {
130     CV_Assert(subpath.empty() || subpath[0] != '/');
131     if (prefix.empty())
132         return subpath;
133     bool skipSlash = prefix.size() > 0 ? (prefix[prefix.size()-1] == '/' || prefix[prefix.size()-1] == '\\') : false;
134     std::string path = prefix + (skipSlash ? "" : "/") + subpath;
135     return path;
136 }
137
138
139
140 /*****************************************************************************************\
141 *                                Exception and memory handlers                            *
142 \*****************************************************************************************/
143
144 // a few platform-dependent declarations
145
146 #if defined _WIN32
147 #ifdef _MSC_VER
148 static void SEHTranslator( unsigned int /*u*/, EXCEPTION_POINTERS* pExp )
149 {
150     TS::FailureCode code = TS::FAIL_EXCEPTION;
151     switch( pExp->ExceptionRecord->ExceptionCode )
152     {
153     case EXCEPTION_ACCESS_VIOLATION:
154     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
155     case EXCEPTION_DATATYPE_MISALIGNMENT:
156     case EXCEPTION_FLT_STACK_CHECK:
157     case EXCEPTION_STACK_OVERFLOW:
158     case EXCEPTION_IN_PAGE_ERROR:
159         code = TS::FAIL_MEMORY_EXCEPTION;
160         break;
161     case EXCEPTION_FLT_DENORMAL_OPERAND:
162     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
163     case EXCEPTION_FLT_INEXACT_RESULT:
164     case EXCEPTION_FLT_INVALID_OPERATION:
165     case EXCEPTION_FLT_OVERFLOW:
166     case EXCEPTION_FLT_UNDERFLOW:
167     case EXCEPTION_INT_DIVIDE_BY_ZERO:
168     case EXCEPTION_INT_OVERFLOW:
169         code = TS::FAIL_ARITHM_EXCEPTION;
170         break;
171     case EXCEPTION_BREAKPOINT:
172     case EXCEPTION_ILLEGAL_INSTRUCTION:
173     case EXCEPTION_INVALID_DISPOSITION:
174     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
175     case EXCEPTION_PRIV_INSTRUCTION:
176     case EXCEPTION_SINGLE_STEP:
177         code = TS::FAIL_EXCEPTION;
178     }
179     throw code;
180 }
181 #endif
182
183 #else
184
185 static const int tsSigId[] = { SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT, -1 };
186
187 static jmp_buf tsJmpMark;
188
189 static void signalHandler( int sig_code )
190 {
191     TS::FailureCode code = TS::FAIL_EXCEPTION;
192     switch( sig_code )
193     {
194     case SIGFPE:
195         code = TS::FAIL_ARITHM_EXCEPTION;
196         break;
197     case SIGSEGV:
198     case SIGBUS:
199         code = TS::FAIL_ARITHM_EXCEPTION;
200         break;
201     case SIGILL:
202         code = TS::FAIL_EXCEPTION;
203     }
204
205     longjmp( tsJmpMark, (int)code );
206 }
207
208 #endif
209
210
211 // reads 16-digit hexadecimal number (i.e. 64-bit integer)
212 int64 readSeed( const char* str )
213 {
214     int64 val = 0;
215     if( str && strlen(str) == 16 )
216     {
217         for( int i = 0; str[i]; i++ )
218         {
219             int c = tolower(str[i]);
220             if( !isxdigit(c) )
221                 return 0;
222             val = val * 16 +
223             (str[i] < 'a' ? str[i] - '0' : str[i] - 'a' + 10);
224         }
225     }
226     return val;
227 }
228
229
230 /*****************************************************************************************\
231 *                                    Base Class for Tests                                 *
232 \*****************************************************************************************/
233
234 BaseTest::BaseTest()
235 {
236     ts = TS::ptr();
237     test_case_count = -1;
238 }
239
240 BaseTest::~BaseTest()
241 {
242     clear();
243 }
244
245 void BaseTest::clear()
246 {
247 }
248
249
250 cv::FileNode BaseTest::find_param( const cv::FileStorage& fs, const char* param_name )
251 {
252     cv::FileNode node = fs[get_name()];
253     return node[param_name];
254 }
255
256
257 int BaseTest::read_params( const cv::FileStorage& )
258 {
259     return 0;
260 }
261
262
263 bool BaseTest::can_do_fast_forward()
264 {
265     return true;
266 }
267
268
269 void BaseTest::safe_run( int start_from )
270 {
271     CV_TRACE_FUNCTION();
272     ts->update_context( 0, -1, true );
273     ts->update_context( this, -1, true );
274
275     if( !::testing::GTEST_FLAG(catch_exceptions) )
276         run( start_from );
277     else
278     {
279         try
280         {
281         #if !defined _WIN32
282         int _code = setjmp( tsJmpMark );
283         if( !_code )
284             run( start_from );
285         else
286             throw TS::FailureCode(_code);
287         #else
288             run( start_from );
289         #endif
290         }
291         catch (const cv::Exception& exc)
292         {
293             const char* errorStr = cvErrorStr(exc.code);
294             char buf[1 << 16];
295
296             const char* delim = exc.err.find('\n') == cv::String::npos ? "" : "\n";
297             sprintf( buf, "OpenCV Error:\n\t%s (%s%s) in %s, file %s, line %d",
298                     errorStr, delim, exc.err.c_str(), exc.func.size() > 0 ?
299                     exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line );
300             ts->printf(TS::LOG, "%s\n", buf);
301
302             ts->set_failed_test_info( TS::FAIL_ERROR_IN_CALLED_FUNC );
303         }
304         catch (const TS::FailureCode& fc)
305         {
306             std::string errorStr = TS::str_from_code(fc);
307             ts->printf(TS::LOG, "General failure:\n\t%s (%d)\n", errorStr.c_str(), fc);
308
309             ts->set_failed_test_info( fc );
310         }
311         catch (...)
312         {
313             ts->printf(TS::LOG, "Unknown failure\n");
314
315             ts->set_failed_test_info( TS::FAIL_EXCEPTION );
316         }
317     }
318
319     ts->set_gtest_status();
320 }
321
322
323 void BaseTest::run( int start_from )
324 {
325     int test_case_idx, count = get_test_case_count();
326     int64 t_start = cvGetTickCount();
327     double freq = cv::getTickFrequency();
328     bool ff = can_do_fast_forward();
329     int progress = 0, code;
330     int64 t1 = t_start;
331
332     for( test_case_idx = ff && start_from >= 0 ? start_from : 0;
333          count < 0 || test_case_idx < count; test_case_idx++ )
334     {
335         ts->update_context( this, test_case_idx, ff );
336         progress = update_progress( progress, test_case_idx, count, (double)(t1 - t_start)/(freq*1000) );
337
338         code = prepare_test_case( test_case_idx );
339         if( code < 0 || ts->get_err_code() < 0 )
340             return;
341
342         if( code == 0 )
343             continue;
344
345         run_func();
346
347         if( ts->get_err_code() < 0 )
348             return;
349
350         if( validate_test_results( test_case_idx ) < 0 || ts->get_err_code() < 0 )
351             return;
352     }
353 }
354
355
356 void BaseTest::run_func(void)
357 {
358     assert(0);
359 }
360
361
362 int BaseTest::get_test_case_count(void)
363 {
364     return test_case_count;
365 }
366
367
368 int BaseTest::prepare_test_case( int )
369 {
370     return 0;
371 }
372
373
374 int BaseTest::validate_test_results( int )
375 {
376     return 0;
377 }
378
379
380 int BaseTest::update_progress( int progress, int test_case_idx, int count, double dt )
381 {
382     int width = 60 - (int)get_name().size();
383     if( count > 0 )
384     {
385         int t = cvRound( ((double)test_case_idx * width)/count );
386         if( t > progress )
387         {
388             ts->printf( TS::CONSOLE, "." );
389             progress = t;
390         }
391     }
392     else if( cvRound(dt) > progress )
393     {
394         ts->printf( TS::CONSOLE, "." );
395         progress = cvRound(dt);
396     }
397
398     return progress;
399 }
400
401
402 BadArgTest::BadArgTest()
403 {
404     test_case_idx   = -1;
405     // oldErrorCbk     = 0;
406     // oldErrorCbkData = 0;
407 }
408
409 BadArgTest::~BadArgTest(void)
410 {
411 }
412
413 int BadArgTest::run_test_case( int expected_code, const string& _descr )
414 {
415     int errcount = 0;
416     bool thrown = false;
417     const char* descr = _descr.c_str() ? _descr.c_str() : "";
418
419     try
420     {
421         run_func();
422     }
423     catch(const cv::Exception& e)
424     {
425         thrown = true;
426         if (e.code != expected_code &&
427             e.code != cv::Error::StsError && e.code != cv::Error::StsAssert  // Exact error codes support will be dropped. Checks should provide proper text messages intead.
428         )
429         {
430             ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
431                        descr, test_case_idx, e.code, expected_code);
432             errcount = 1;
433         }
434     }
435     catch(...)
436     {
437         thrown = true;
438         ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
439                    descr, test_case_idx);
440         errcount = 1;
441     }
442
443     if(!thrown)
444     {
445         ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
446                    descr, test_case_idx);
447         errcount = 1;
448     }
449     test_case_idx++;
450
451     return errcount;
452 }
453
454 /*****************************************************************************************\
455 *                                 Base Class for Test System                              *
456 \*****************************************************************************************/
457
458 /******************************** Constructors/Destructors ******************************/
459
460 TSParams::TSParams()
461 {
462     rng_seed = (uint64)-1;
463     use_optimized = true;
464     test_case_count_scale = 1;
465 }
466
467
468 TestInfo::TestInfo()
469 {
470     test = 0;
471     code = 0;
472     rng_seed = rng_seed0 = 0;
473     test_case_idx = -1;
474 }
475
476
477 TS::TS()
478 {
479 } // ctor
480
481
482 TS::~TS()
483 {
484 } // dtor
485
486
487 string TS::str_from_code( const TS::FailureCode code )
488 {
489     switch( code )
490     {
491     case OK:                           return "Ok";
492     case FAIL_GENERIC:                 return "Generic/Unknown";
493     case FAIL_MISSING_TEST_DATA:       return "No test data";
494     case FAIL_INVALID_TEST_DATA:       return "Invalid test data";
495     case FAIL_ERROR_IN_CALLED_FUNC:    return "cvError invoked";
496     case FAIL_EXCEPTION:               return "Hardware/OS exception";
497     case FAIL_MEMORY_EXCEPTION:        return "Invalid memory access";
498     case FAIL_ARITHM_EXCEPTION:        return "Arithmetic exception";
499     case FAIL_MEMORY_CORRUPTION_BEGIN: return "Corrupted memblock (beginning)";
500     case FAIL_MEMORY_CORRUPTION_END:   return "Corrupted memblock (end)";
501     case FAIL_MEMORY_LEAK:             return "Memory leak";
502     case FAIL_INVALID_OUTPUT:          return "Invalid function output";
503     case FAIL_MISMATCH:                return "Unexpected output";
504     case FAIL_BAD_ACCURACY:            return "Bad accuracy";
505     case FAIL_HANG:                    return "Infinite loop(?)";
506     case FAIL_BAD_ARG_CHECK:           return "Incorrect handling of bad arguments";
507     default:
508             ;
509     }
510     return "Generic/Unknown";
511 }
512
513 static int tsErrorCallback( int status, const char* func_name, const char* err_msg, const char* file_name, int line, TS* ts )
514 {
515     const char* delim = std::string(err_msg).find('\n') == std::string::npos ? "" : "\n";
516     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);
517     return 0;
518 }
519
520 /************************************** Running tests **********************************/
521
522 void TS::init( const string& modulename )
523 {
524     data_search_subdir.push_back(modulename);
525 #ifndef WINRT
526     char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
527 #else
528     char* datapath_dir = OPENCV_TEST_DATA_PATH;
529 #endif
530
531     if( datapath_dir )
532     {
533         data_path = path_join(path_join(datapath_dir, modulename), "");
534     }
535
536     cv::redirectError((cv::ErrorCallback)tsErrorCallback, this);
537
538     if( ::testing::GTEST_FLAG(catch_exceptions) )
539     {
540 #if defined _WIN32
541 #ifdef _MSC_VER
542         _set_se_translator( SEHTranslator );
543 #endif
544 #else
545         for( int i = 0; tsSigId[i] >= 0; i++ )
546             signal( tsSigId[i], signalHandler );
547 #endif
548     }
549     else
550     {
551 #if defined _WIN32
552 #ifdef _MSC_VER
553         _set_se_translator( 0 );
554 #endif
555 #else
556         for( int i = 0; tsSigId[i] >= 0; i++ )
557             signal( tsSigId[i], SIG_DFL );
558 #endif
559     }
560
561     if( params.use_optimized == 0 )
562         cv::setUseOptimized(false);
563
564     rng = RNG(params.rng_seed);
565 }
566
567
568 void TS::set_gtest_status()
569 {
570     TS::FailureCode code = get_err_code();
571     if( code >= 0 )
572         return SUCCEED();
573
574     char seedstr[32];
575     sprintf(seedstr, "%08x%08x", (unsigned)(current_test_info.rng_seed>>32),
576                                 (unsigned)(current_test_info.rng_seed));
577
578     string logs = "";
579     if( !output_buf[SUMMARY_IDX].empty() )
580         logs += "\n-----------------------------------\n\tSUM: " + output_buf[SUMMARY_IDX];
581     if( !output_buf[LOG_IDX].empty() )
582         logs += "\n-----------------------------------\n\tLOG:\n" + output_buf[LOG_IDX];
583     if( !output_buf[CONSOLE_IDX].empty() )
584         logs += "\n-----------------------------------\n\tCONSOLE: " + output_buf[CONSOLE_IDX];
585     logs += "\n-----------------------------------\n";
586
587     FAIL() << "\n\tfailure reason: " << str_from_code(code) <<
588         "\n\ttest case #" << current_test_info.test_case_idx <<
589         "\n\tseed: " << seedstr << logs;
590 }
591
592
593 void TS::update_context( BaseTest* test, int test_case_idx, bool update_ts_context )
594 {
595     if( current_test_info.test != test )
596     {
597         for( int i = 0; i <= CONSOLE_IDX; i++ )
598             output_buf[i] = string();
599         rng = RNG(params.rng_seed);
600         current_test_info.rng_seed0 = current_test_info.rng_seed = rng.state;
601     }
602
603     current_test_info.test = test;
604     current_test_info.test_case_idx = test_case_idx;
605     current_test_info.code = 0;
606     cvSetErrStatus( CV_StsOk );
607     if( update_ts_context )
608         current_test_info.rng_seed = rng.state;
609 }
610
611
612 void TS::set_failed_test_info( int fail_code )
613 {
614     if( current_test_info.code >= 0 )
615         current_test_info.code = TS::FailureCode(fail_code);
616 }
617
618 #if defined _MSC_VER && _MSC_VER < 1400
619 #undef vsnprintf
620 #define vsnprintf _vsnprintf
621 #endif
622
623 void TS::vprintf( int streams, const char* fmt, va_list l )
624 {
625     char str[1 << 14];
626     vsnprintf( str, sizeof(str)-1, fmt, l );
627
628     for( int i = 0; i < MAX_IDX; i++ )
629         if( (streams & (1 << i)) )
630         {
631             output_buf[i] += std::string(str);
632             // in the new GTest-based framework we do not use
633             // any output files (except for the automatically generated xml report).
634             // if a test fails, all the buffers are printed, so we do not want to duplicate the information and
635             // thus only add the new information to a single buffer and return from the function.
636             break;
637         }
638 }
639
640
641 void TS::printf( int streams, const char* fmt, ... )
642 {
643     if( streams )
644     {
645         va_list l;
646         va_start( l, fmt );
647         vprintf( streams, fmt, l );
648         va_end( l );
649     }
650 }
651
652
653 TS* TS::ptr()
654 {
655     static TS ts;
656     return &ts;
657 }
658
659 void fillGradient(Mat& img, int delta)
660 {
661     const int ch = img.channels();
662     CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
663
664     int n = 255 / delta;
665     int r, c, i;
666     for(r=0; r<img.rows; r++)
667     {
668         int kR = r % (2*n);
669         int valR = (kR<=n) ? delta*kR : delta*(2*n-kR);
670         for(c=0; c<img.cols; c++)
671         {
672             int kC = c % (2*n);
673             int valC = (kC<=n) ? delta*kC : delta*(2*n-kC);
674             uchar vals[] = {uchar(valR), uchar(valC), uchar(200*r/img.rows), uchar(255)};
675             uchar *p = img.ptr(r, c);
676             for(i=0; i<ch; i++) p[i] = vals[i];
677         }
678     }
679 }
680
681 void smoothBorder(Mat& img, const Scalar& color, int delta)
682 {
683     const int ch = img.channels();
684     CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
685
686     Scalar s;
687     uchar *p = NULL;
688     int n = 100/delta;
689     int nR = std::min(n, (img.rows+1)/2), nC = std::min(n, (img.cols+1)/2);
690
691     int r, c, i;
692     for(r=0; r<nR; r++)
693     {
694         double k1 = r*delta/100., k2 = 1-k1;
695         for(c=0; c<img.cols; c++)
696         {
697             p = img.ptr(r, c);
698             for(i=0; i<ch; i++) s[i] = p[i];
699             s = s * k1 + color * k2;
700             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
701         }
702         for(c=0; c<img.cols; c++)
703         {
704             p = img.ptr(img.rows-r-1, c);
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     for(r=0; r<img.rows; r++)
712     {
713         for(c=0; c<nC; c++)
714         {
715             double k1 = c*delta/100., k2 = 1-k1;
716             p = img.ptr(r, c);
717             for(i=0; i<ch; i++) s[i] = p[i];
718             s = s * k1 + color * k2;
719             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
720         }
721         for(c=0; c<n; c++)
722         {
723             double k1 = c*delta/100., k2 = 1-k1;
724             p = img.ptr(r, img.cols-c-1);
725             for(i=0; i<ch; i++) s[i] = p[i];
726             s = s * k1 + color * k2;
727             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
728         }
729     }
730 }
731
732
733 bool test_ipp_check = false;
734
735 void checkIppStatus()
736 {
737     if (test_ipp_check)
738     {
739         int status = cv::ipp::getIppStatus();
740         EXPECT_LE(0, status) << cv::ipp::getIppErrorLocation().c_str();
741     }
742 }
743
744 static bool checkTestData = false;
745 bool skipUnstableTests = false;
746 bool runBigDataTests = false;
747 int testThreads = 0;
748
749
750 static size_t memory_usage_base = 0;
751 static uint64_t memory_usage_base_opencv = 0;
752 #ifdef HAVE_OPENCL
753 static uint64_t memory_usage_base_opencl = 0;
754 #endif
755
756 void testSetUp()
757 {
758     fflush(stdout); fflush(stderr);
759     cv::ipp::setIppStatus(0);
760     cv::theRNG().state = cvtest::param_seed;
761     cv::setNumThreads(cvtest::testThreads);
762     if (malloc_peak)  // if memory profiler is available
763     {
764         malloc_reset_peak();
765         memory_usage_base = malloc_peak(); // equal to malloc_current()
766     }
767     {
768         cv::utils::AllocatorStatisticsInterface& ocv_stats = cv::getAllocatorStatistics();
769         ocv_stats.resetPeakUsage();
770         memory_usage_base_opencv = ocv_stats.getCurrentUsage();
771     }
772 #ifdef HAVE_OPENCL
773     {
774         cv::utils::AllocatorStatisticsInterface& ocl_stats = cv::ocl::getOpenCLAllocatorStatistics();
775         ocl_stats.resetPeakUsage();
776         memory_usage_base_opencl = ocl_stats.getCurrentUsage();
777     }
778 #endif
779     checkTestTags();
780 }
781
782 void testTearDown()
783 {
784     ::cvtest::checkIppStatus();
785     uint64_t memory_usage = 0;
786     uint64_t ocv_memory_usage = 0, ocv_peak = 0;
787     if (malloc_peak)  // if memory profiler is available
788     {
789         size_t peak = malloc_peak();
790         memory_usage = peak - memory_usage_base;
791         CV_LOG_INFO(NULL, "Memory_usage (malloc): " << memory_usage << " (base=" << memory_usage_base << ")");
792     }
793     {
794         // core/src/alloc.cpp: #define OPENCV_ALLOC_ENABLE_STATISTICS
795         // handle large buffers via fastAlloc()
796         // (not always accurate on heavy 3rdparty usage, like protobuf)
797         cv::utils::AllocatorStatisticsInterface& ocv_stats = cv::getAllocatorStatistics();
798         ocv_peak = ocv_stats.getPeakUsage();
799         ocv_memory_usage = ocv_peak - memory_usage_base_opencv;
800         CV_LOG_INFO(NULL, "Memory_usage (OpenCV): " << ocv_memory_usage << " (base=" << memory_usage_base_opencv << "  current=" << ocv_stats.getCurrentUsage() << ")");
801         if (memory_usage == 0)  // external profiler has higher priority (and accuracy)
802             memory_usage = ocv_memory_usage;
803     }
804 #ifdef HAVE_OPENCL
805     uint64_t ocl_memory_usage = 0, ocl_peak = 0;
806     {
807         cv::utils::AllocatorStatisticsInterface& ocl_stats = cv::ocl::getOpenCLAllocatorStatistics();
808         ocl_peak = ocl_stats.getPeakUsage();
809         ocl_memory_usage = ocl_peak - memory_usage_base_opencl;
810         CV_LOG_INFO(NULL, "Memory_usage (OpenCL): " << ocl_memory_usage << " (base=" << memory_usage_base_opencl << "  current=" << ocl_stats.getCurrentUsage() << ")");
811         ::testing::Test::RecordProperty("ocl_memory_usage",
812                 cv::format("%llu", (unsigned long long)ocl_memory_usage));
813     }
814 #else
815     uint64_t ocl_memory_usage = 0;
816 #endif
817     if (malloc_peak      // external memory profiler is available
818         || ocv_peak > 0  // or enabled OpenCV builtin allocation statistics
819     )
820     {
821         CV_LOG_INFO(NULL, "Memory usage total: " << (memory_usage + ocl_memory_usage));
822         ::testing::Test::RecordProperty("memory_usage",
823                 cv::format("%llu", (unsigned long long)memory_usage));
824         ::testing::Test::RecordProperty("total_memory_usage",
825                 cv::format("%llu", (unsigned long long)(memory_usage + ocl_memory_usage)));
826     }
827 }
828
829 void parseCustomOptions(int argc, char **argv)
830 {
831     const char * const command_line_keys =
832         "{ ipp test_ipp_check |false    |check whether IPP works without failures }"
833         "{ test_seed          |809564   |seed for random numbers generator }"
834         "{ test_threads       |-1       |the number of worker threads, if parallel execution is enabled}"
835         "{ skip_unstable      |false    |skip unstable tests }"
836         "{ test_bigdata       |false    |run BigData tests (>=2Gb) }"
837         "{ test_require_data  |false    |fail on missing non-required test data instead of skip}"
838         CV_TEST_TAGS_PARAMS
839         "{ h   help           |false    |print help info                          }"
840     ;
841
842     cv::CommandLineParser parser(argc, argv, command_line_keys);
843     if (parser.get<bool>("help"))
844     {
845         std::cout << "\nAvailable options besides google test option: \n";
846         parser.printMessage();
847     }
848
849     test_ipp_check = parser.get<bool>("test_ipp_check");
850     if (!test_ipp_check)
851 #ifndef WINRT
852         test_ipp_check = getenv("OPENCV_IPP_CHECK") != NULL;
853 #else
854         test_ipp_check = false;
855 #endif
856
857     param_seed = parser.get<unsigned int>("test_seed");
858
859     testThreads = parser.get<int>("test_threads");
860
861     skipUnstableTests = parser.get<bool>("skip_unstable");
862     runBigDataTests = parser.get<bool>("test_bigdata");
863     checkTestData = parser.get<bool>("test_require_data");
864
865     activateTestTags(parser);
866 }
867
868 static bool isDirectory(const std::string& path)
869 {
870 #if defined _WIN32 || defined WINCE
871     WIN32_FILE_ATTRIBUTE_DATA all_attrs;
872 #ifdef WINRT
873     wchar_t wpath[MAX_PATH];
874     size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
875     CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
876     BOOL status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs);
877 #else
878     BOOL status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
879 #endif
880     DWORD attributes = all_attrs.dwFileAttributes;
881     return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
882 #else
883     struct stat s;
884     if (0 != stat(path.c_str(), &s))
885         return false;
886     return S_ISDIR(s.st_mode);
887 #endif
888 }
889
890 void addDataSearchPath(const std::string& path)
891 {
892     if (isDirectory(path))
893         TS::ptr()->data_search_path.push_back(path);
894 }
895 void addDataSearchSubDirectory(const std::string& subdir)
896 {
897     TS::ptr()->data_search_subdir.push_back(subdir);
898 }
899
900 static std::string findData(const std::string& relative_path, bool required, bool findDirectory)
901 {
902 #define TEST_TRY_FILE_WITH_PREFIX(prefix) \
903 { \
904     std::string path = path_join(prefix, relative_path); \
905     /*printf("Trying %s\n", path.c_str());*/ \
906     if (findDirectory) \
907     { \
908         if (isDirectory(path)) \
909             return path; \
910     } \
911     else \
912     { \
913         FILE* f = fopen(path.c_str(), "rb"); \
914         if(f) { \
915             fclose(f); \
916             return path; \
917         } \
918     } \
919 }
920
921     const std::vector<std::string>& search_path = TS::ptr()->data_search_path;
922     for(size_t i = search_path.size(); i > 0; i--)
923     {
924         const std::string& prefix = search_path[i - 1];
925         TEST_TRY_FILE_WITH_PREFIX(prefix);
926     }
927
928     const std::vector<std::string>& search_subdir = TS::ptr()->data_search_subdir;
929
930 #ifndef WINRT
931     char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
932 #else
933     char* datapath_dir = OPENCV_TEST_DATA_PATH;
934 #endif
935
936     std::string datapath;
937     if (datapath_dir)
938     {
939         datapath = datapath_dir;
940         //CV_Assert(isDirectory(datapath) && "OPENCV_TEST_DATA_PATH is specified but it doesn't exist");
941         if (isDirectory(datapath))
942         {
943             for(size_t i = search_subdir.size(); i > 0; i--)
944             {
945                 const std::string& subdir = search_subdir[i - 1];
946                 std::string prefix = path_join(datapath, subdir);
947                 TEST_TRY_FILE_WITH_PREFIX(prefix);
948             }
949         }
950     }
951 #ifdef OPENCV_TEST_DATA_INSTALL_PATH
952     datapath = path_join("./", OPENCV_TEST_DATA_INSTALL_PATH);
953     if (isDirectory(datapath))
954     {
955         for(size_t i = search_subdir.size(); i > 0; i--)
956         {
957             const std::string& subdir = search_subdir[i - 1];
958             std::string prefix = path_join(datapath, subdir);
959             TEST_TRY_FILE_WITH_PREFIX(prefix);
960         }
961     }
962 #ifdef OPENCV_INSTALL_PREFIX
963     else
964     {
965         datapath = path_join(OPENCV_INSTALL_PREFIX, OPENCV_TEST_DATA_INSTALL_PATH);
966         if (isDirectory(datapath))
967         {
968             for(size_t i = search_subdir.size(); i > 0; i--)
969             {
970                 const std::string& subdir = search_subdir[i - 1];
971                 std::string prefix = path_join(datapath, subdir);
972                 TEST_TRY_FILE_WITH_PREFIX(prefix);
973             }
974         }
975     }
976 #endif
977 #endif
978     const char* type = findDirectory ? "directory" : "data file";
979     if (required || checkTestData)
980         CV_Error(cv::Error::StsError, cv::format("OpenCV tests: Can't find required %s: %s", type, relative_path.c_str()));
981     throw SkipTestException(cv::format("OpenCV tests: Can't find %s: %s", type, relative_path.c_str()));
982 }
983
984 std::string findDataFile(const std::string& relative_path, bool required)
985 {
986     return findData(relative_path, required, false);
987 }
988
989 std::string findDataDirectory(const std::string& relative_path, bool required)
990 {
991     return findData(relative_path, required, true);
992 }
993
994 inline static std::string getSnippetFromConfig(const std::string & start, const std::string & end)
995 {
996     const std::string buildInfo = cv::getBuildInformation();
997     size_t pos1 = buildInfo.find(start);
998     if (pos1 != std::string::npos)
999     {
1000         pos1 += start.length();
1001         pos1 = buildInfo.find_first_not_of(" \t\n\r", pos1);
1002     }
1003     size_t pos2 = buildInfo.find(end, pos1);
1004     if (pos2 != std::string::npos)
1005     {
1006         pos2 = buildInfo.find_last_not_of(" \t\n\r", pos2);
1007     }
1008     if (pos1 != std::string::npos && pos2 != std::string::npos && pos1 < pos2)
1009     {
1010         return buildInfo.substr(pos1, pos2 - pos1 + 1);
1011     }
1012     return std::string();
1013 }
1014
1015 inline static void recordPropertyVerbose(const std::string & property,
1016                                          const std::string & msg,
1017                                          const std::string & value,
1018                                          const std::string & build_value = std::string())
1019 {
1020     ::testing::Test::RecordProperty(property, value);
1021     std::cout << msg << ": " << (value.empty() ? std::string("N/A") : value) << std::endl;
1022     if (!build_value.empty())
1023     {
1024         ::testing::Test::RecordProperty(property + "_build", build_value);
1025         if (build_value != value)
1026             std::cout << "WARNING: build value differs from runtime: " << build_value << endl;
1027     }
1028 }
1029
1030 inline static void recordPropertyVerbose(const std::string& property, const std::string& msg,
1031                                          const char* value, const char* build_value = NULL)
1032 {
1033     return recordPropertyVerbose(property, msg,
1034         value ? std::string(value) : std::string(),
1035         build_value ? std::string(build_value) : std::string());
1036 }
1037
1038 #ifdef _DEBUG
1039 #define CV_TEST_BUILD_CONFIG "Debug"
1040 #else
1041 #define CV_TEST_BUILD_CONFIG "Release"
1042 #endif
1043
1044 void SystemInfoCollector::OnTestProgramStart(const testing::UnitTest&)
1045 {
1046     std::cout << "CTEST_FULL_OUTPUT" << std::endl; // Tell CTest not to discard any output
1047     recordPropertyVerbose("cv_version", "OpenCV version", cv::getVersionString(), CV_VERSION);
1048     recordPropertyVerbose("cv_vcs_version", "OpenCV VCS version", getSnippetFromConfig("Version control:", "\n"));
1049     recordPropertyVerbose("cv_build_type", "Build type", getSnippetFromConfig("Configuration:", "\n"), CV_TEST_BUILD_CONFIG);
1050     recordPropertyVerbose("cv_compiler", "Compiler", getSnippetFromConfig("C++ Compiler:", "\n"));
1051     recordPropertyVerbose("cv_parallel_framework", "Parallel framework", cv::currentParallelFramework());
1052     recordPropertyVerbose("cv_cpu_features", "CPU features", cv::getCPUFeaturesLine());
1053 #ifdef HAVE_IPP
1054     recordPropertyVerbose("cv_ipp_version", "Intel(R) IPP version", cv::ipp::useIPP() ? cv::ipp::getIppVersion() :  "disabled");
1055 #endif
1056 #ifdef HAVE_OPENCL
1057     cv::dumpOpenCLInformation();
1058 #endif
1059 }
1060
1061 } //namespace cvtest
1062
1063 /* End of file. */