b1ea96bb15d67722e52c164539c2438baa19bfb9
[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
78 #include "opencv_tests_config.hpp"
79
80 namespace opencv_test {
81 bool required_opencv_test_namespace = false;  // compilation check for non-refactored tests
82 }
83
84 namespace cvtest
85 {
86
87 uint64 param_seed = 0x12345678; // real value is passed via parseCustomOptions function
88
89 static std::string path_join(const std::string& prefix, const std::string& subpath)
90 {
91     CV_Assert(subpath.empty() || subpath[0] != '/');
92     if (prefix.empty())
93         return subpath;
94     bool skipSlash = prefix.size() > 0 ? (prefix[prefix.size()-1] == '/' || prefix[prefix.size()-1] == '\\') : false;
95     std::string path = prefix + (skipSlash ? "" : "/") + subpath;
96     return path;
97 }
98
99
100
101 /*****************************************************************************************\
102 *                                Exception and memory handlers                            *
103 \*****************************************************************************************/
104
105 // a few platform-dependent declarations
106
107 #if defined _WIN32
108 #ifdef _MSC_VER
109 static void SEHTranslator( unsigned int /*u*/, EXCEPTION_POINTERS* pExp )
110 {
111     TS::FailureCode code = TS::FAIL_EXCEPTION;
112     switch( pExp->ExceptionRecord->ExceptionCode )
113     {
114     case EXCEPTION_ACCESS_VIOLATION:
115     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
116     case EXCEPTION_DATATYPE_MISALIGNMENT:
117     case EXCEPTION_FLT_STACK_CHECK:
118     case EXCEPTION_STACK_OVERFLOW:
119     case EXCEPTION_IN_PAGE_ERROR:
120         code = TS::FAIL_MEMORY_EXCEPTION;
121         break;
122     case EXCEPTION_FLT_DENORMAL_OPERAND:
123     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
124     case EXCEPTION_FLT_INEXACT_RESULT:
125     case EXCEPTION_FLT_INVALID_OPERATION:
126     case EXCEPTION_FLT_OVERFLOW:
127     case EXCEPTION_FLT_UNDERFLOW:
128     case EXCEPTION_INT_DIVIDE_BY_ZERO:
129     case EXCEPTION_INT_OVERFLOW:
130         code = TS::FAIL_ARITHM_EXCEPTION;
131         break;
132     case EXCEPTION_BREAKPOINT:
133     case EXCEPTION_ILLEGAL_INSTRUCTION:
134     case EXCEPTION_INVALID_DISPOSITION:
135     case EXCEPTION_NONCONTINUABLE_EXCEPTION:
136     case EXCEPTION_PRIV_INSTRUCTION:
137     case EXCEPTION_SINGLE_STEP:
138         code = TS::FAIL_EXCEPTION;
139     }
140     throw code;
141 }
142 #endif
143
144 #else
145
146 static const int tsSigId[] = { SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT, -1 };
147
148 static jmp_buf tsJmpMark;
149
150 static void signalHandler( int sig_code )
151 {
152     TS::FailureCode code = TS::FAIL_EXCEPTION;
153     switch( sig_code )
154     {
155     case SIGFPE:
156         code = TS::FAIL_ARITHM_EXCEPTION;
157         break;
158     case SIGSEGV:
159     case SIGBUS:
160         code = TS::FAIL_ARITHM_EXCEPTION;
161         break;
162     case SIGILL:
163         code = TS::FAIL_EXCEPTION;
164     }
165
166     longjmp( tsJmpMark, (int)code );
167 }
168
169 #endif
170
171
172 // reads 16-digit hexadecimal number (i.e. 64-bit integer)
173 int64 readSeed( const char* str )
174 {
175     int64 val = 0;
176     if( str && strlen(str) == 16 )
177     {
178         for( int i = 0; str[i]; i++ )
179         {
180             int c = tolower(str[i]);
181             if( !isxdigit(c) )
182                 return 0;
183             val = val * 16 +
184             (str[i] < 'a' ? str[i] - '0' : str[i] - 'a' + 10);
185         }
186     }
187     return val;
188 }
189
190
191 /*****************************************************************************************\
192 *                                    Base Class for Tests                                 *
193 \*****************************************************************************************/
194
195 BaseTest::BaseTest()
196 {
197     ts = TS::ptr();
198     test_case_count = -1;
199 }
200
201 BaseTest::~BaseTest()
202 {
203     clear();
204 }
205
206 void BaseTest::clear()
207 {
208 }
209
210
211 const CvFileNode* BaseTest::find_param( CvFileStorage* fs, const char* param_name )
212 {
213     CvFileNode* node = cvGetFileNodeByName(fs, 0, get_name().c_str());
214     return node ? cvGetFileNodeByName( fs, node, param_name ) : 0;
215 }
216
217
218 int BaseTest::read_params( CvFileStorage* )
219 {
220     return 0;
221 }
222
223
224 bool BaseTest::can_do_fast_forward()
225 {
226     return true;
227 }
228
229
230 void BaseTest::safe_run( int start_from )
231 {
232     CV_TRACE_FUNCTION();
233     read_params( ts->get_file_storage() );
234     ts->update_context( 0, -1, true );
235     ts->update_context( this, -1, true );
236
237     if( !::testing::GTEST_FLAG(catch_exceptions) )
238         run( start_from );
239     else
240     {
241         try
242         {
243         #if !defined _WIN32
244         int _code = setjmp( tsJmpMark );
245         if( !_code )
246             run( start_from );
247         else
248             throw TS::FailureCode(_code);
249         #else
250             run( start_from );
251         #endif
252         }
253         catch (const cv::Exception& exc)
254         {
255             const char* errorStr = cvErrorStr(exc.code);
256             char buf[1 << 16];
257
258             const char* delim = exc.err.find('\n') == cv::String::npos ? "" : "\n";
259             sprintf( buf, "OpenCV Error:\n\t%s (%s%s) in %s, file %s, line %d",
260                     errorStr, delim, exc.err.c_str(), exc.func.size() > 0 ?
261                     exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line );
262             ts->printf(TS::LOG, "%s\n", buf);
263
264             ts->set_failed_test_info( TS::FAIL_ERROR_IN_CALLED_FUNC );
265         }
266         catch (const TS::FailureCode& fc)
267         {
268             std::string errorStr = TS::str_from_code(fc);
269             ts->printf(TS::LOG, "General failure:\n\t%s (%d)\n", errorStr.c_str(), fc);
270
271             ts->set_failed_test_info( fc );
272         }
273         catch (...)
274         {
275             ts->printf(TS::LOG, "Unknown failure\n");
276
277             ts->set_failed_test_info( TS::FAIL_EXCEPTION );
278         }
279     }
280
281     ts->set_gtest_status();
282 }
283
284
285 void BaseTest::run( int start_from )
286 {
287     int test_case_idx, count = get_test_case_count();
288     int64 t_start = cvGetTickCount();
289     double freq = cv::getTickFrequency();
290     bool ff = can_do_fast_forward();
291     int progress = 0, code;
292     int64 t1 = t_start;
293
294     for( test_case_idx = ff && start_from >= 0 ? start_from : 0;
295          count < 0 || test_case_idx < count; test_case_idx++ )
296     {
297         ts->update_context( this, test_case_idx, ff );
298         progress = update_progress( progress, test_case_idx, count, (double)(t1 - t_start)/(freq*1000) );
299
300         code = prepare_test_case( test_case_idx );
301         if( code < 0 || ts->get_err_code() < 0 )
302             return;
303
304         if( code == 0 )
305             continue;
306
307         run_func();
308
309         if( ts->get_err_code() < 0 )
310             return;
311
312         if( validate_test_results( test_case_idx ) < 0 || ts->get_err_code() < 0 )
313             return;
314     }
315 }
316
317
318 void BaseTest::run_func(void)
319 {
320     assert(0);
321 }
322
323
324 int BaseTest::get_test_case_count(void)
325 {
326     return test_case_count;
327 }
328
329
330 int BaseTest::prepare_test_case( int )
331 {
332     return 0;
333 }
334
335
336 int BaseTest::validate_test_results( int )
337 {
338     return 0;
339 }
340
341
342 int BaseTest::update_progress( int progress, int test_case_idx, int count, double dt )
343 {
344     int width = 60 - (int)get_name().size();
345     if( count > 0 )
346     {
347         int t = cvRound( ((double)test_case_idx * width)/count );
348         if( t > progress )
349         {
350             ts->printf( TS::CONSOLE, "." );
351             progress = t;
352         }
353     }
354     else if( cvRound(dt) > progress )
355     {
356         ts->printf( TS::CONSOLE, "." );
357         progress = cvRound(dt);
358     }
359
360     return progress;
361 }
362
363
364 BadArgTest::BadArgTest()
365 {
366     test_case_idx   = -1;
367     // oldErrorCbk     = 0;
368     // oldErrorCbkData = 0;
369 }
370
371 BadArgTest::~BadArgTest(void)
372 {
373 }
374
375 int BadArgTest::run_test_case( int expected_code, const string& _descr )
376 {
377     int errcount = 0;
378     bool thrown = false;
379     const char* descr = _descr.c_str() ? _descr.c_str() : "";
380
381     try
382     {
383         run_func();
384     }
385     catch(const cv::Exception& e)
386     {
387         thrown = true;
388         if (e.code != expected_code &&
389             e.code != cv::Error::StsError && e.code != cv::Error::StsAssert  // Exact error codes support will be dropped. Checks should provide proper text messages intead.
390         )
391         {
392             ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
393                        descr, test_case_idx, e.code, expected_code);
394             errcount = 1;
395         }
396     }
397     catch(...)
398     {
399         thrown = true;
400         ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
401                    descr, test_case_idx);
402         errcount = 1;
403     }
404
405     if(!thrown)
406     {
407         ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
408                    descr, test_case_idx);
409         errcount = 1;
410     }
411     test_case_idx++;
412
413     return errcount;
414 }
415
416 /*****************************************************************************************\
417 *                                 Base Class for Test System                              *
418 \*****************************************************************************************/
419
420 /******************************** Constructors/Destructors ******************************/
421
422 TSParams::TSParams()
423 {
424     rng_seed = (uint64)-1;
425     use_optimized = true;
426     test_case_count_scale = 1;
427 }
428
429
430 TestInfo::TestInfo()
431 {
432     test = 0;
433     code = 0;
434     rng_seed = rng_seed0 = 0;
435     test_case_idx = -1;
436 }
437
438
439 TS::TS()
440 {
441 } // ctor
442
443
444 TS::~TS()
445 {
446 } // dtor
447
448
449 string TS::str_from_code( const TS::FailureCode code )
450 {
451     switch( code )
452     {
453     case OK:                           return "Ok";
454     case FAIL_GENERIC:                 return "Generic/Unknown";
455     case FAIL_MISSING_TEST_DATA:       return "No test data";
456     case FAIL_INVALID_TEST_DATA:       return "Invalid test data";
457     case FAIL_ERROR_IN_CALLED_FUNC:    return "cvError invoked";
458     case FAIL_EXCEPTION:               return "Hardware/OS exception";
459     case FAIL_MEMORY_EXCEPTION:        return "Invalid memory access";
460     case FAIL_ARITHM_EXCEPTION:        return "Arithmetic exception";
461     case FAIL_MEMORY_CORRUPTION_BEGIN: return "Corrupted memblock (beginning)";
462     case FAIL_MEMORY_CORRUPTION_END:   return "Corrupted memblock (end)";
463     case FAIL_MEMORY_LEAK:             return "Memory leak";
464     case FAIL_INVALID_OUTPUT:          return "Invalid function output";
465     case FAIL_MISMATCH:                return "Unexpected output";
466     case FAIL_BAD_ACCURACY:            return "Bad accuracy";
467     case FAIL_HANG:                    return "Infinite loop(?)";
468     case FAIL_BAD_ARG_CHECK:           return "Incorrect handling of bad arguments";
469     default:
470             ;
471     }
472     return "Generic/Unknown";
473 }
474
475 static int tsErrorCallback( int status, const char* func_name, const char* err_msg, const char* file_name, int line, TS* ts )
476 {
477     const char* delim = std::string(err_msg).find('\n') == std::string::npos ? "" : "\n";
478     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);
479     return 0;
480 }
481
482 /************************************** Running tests **********************************/
483
484 void TS::init( const string& modulename )
485 {
486     data_search_subdir.push_back(modulename);
487 #ifndef WINRT
488     char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
489 #else
490     char* datapath_dir = OPENCV_TEST_DATA_PATH;
491 #endif
492
493     if( datapath_dir )
494     {
495         data_path = path_join(path_join(datapath_dir, modulename), "");
496     }
497
498     cv::redirectError((cv::ErrorCallback)tsErrorCallback, this);
499
500     if( ::testing::GTEST_FLAG(catch_exceptions) )
501     {
502 #if defined _WIN32
503 #ifdef _MSC_VER
504         _set_se_translator( SEHTranslator );
505 #endif
506 #else
507         for( int i = 0; tsSigId[i] >= 0; i++ )
508             signal( tsSigId[i], signalHandler );
509 #endif
510     }
511     else
512     {
513 #if defined _WIN32
514 #ifdef _MSC_VER
515         _set_se_translator( 0 );
516 #endif
517 #else
518         for( int i = 0; tsSigId[i] >= 0; i++ )
519             signal( tsSigId[i], SIG_DFL );
520 #endif
521     }
522
523     if( params.use_optimized == 0 )
524         cv::setUseOptimized(false);
525
526     rng = RNG(params.rng_seed);
527 }
528
529
530 void TS::set_gtest_status()
531 {
532     TS::FailureCode code = get_err_code();
533     if( code >= 0 )
534         return SUCCEED();
535
536     char seedstr[32];
537     sprintf(seedstr, "%08x%08x", (unsigned)(current_test_info.rng_seed>>32),
538                                 (unsigned)(current_test_info.rng_seed));
539
540     string logs = "";
541     if( !output_buf[SUMMARY_IDX].empty() )
542         logs += "\n-----------------------------------\n\tSUM: " + output_buf[SUMMARY_IDX];
543     if( !output_buf[LOG_IDX].empty() )
544         logs += "\n-----------------------------------\n\tLOG:\n" + output_buf[LOG_IDX];
545     if( !output_buf[CONSOLE_IDX].empty() )
546         logs += "\n-----------------------------------\n\tCONSOLE: " + output_buf[CONSOLE_IDX];
547     logs += "\n-----------------------------------\n";
548
549     FAIL() << "\n\tfailure reason: " << str_from_code(code) <<
550         "\n\ttest case #" << current_test_info.test_case_idx <<
551         "\n\tseed: " << seedstr << logs;
552 }
553
554
555 CvFileStorage* TS::get_file_storage() { return 0; }
556
557 void TS::update_context( BaseTest* test, int test_case_idx, bool update_ts_context )
558 {
559     if( current_test_info.test != test )
560     {
561         for( int i = 0; i <= CONSOLE_IDX; i++ )
562             output_buf[i] = string();
563         rng = RNG(params.rng_seed);
564         current_test_info.rng_seed0 = current_test_info.rng_seed = rng.state;
565     }
566
567     current_test_info.test = test;
568     current_test_info.test_case_idx = test_case_idx;
569     current_test_info.code = 0;
570     cvSetErrStatus( CV_StsOk );
571     if( update_ts_context )
572         current_test_info.rng_seed = rng.state;
573 }
574
575
576 void TS::set_failed_test_info( int fail_code )
577 {
578     if( current_test_info.code >= 0 )
579         current_test_info.code = TS::FailureCode(fail_code);
580 }
581
582 #if defined _MSC_VER && _MSC_VER < 1400
583 #undef vsnprintf
584 #define vsnprintf _vsnprintf
585 #endif
586
587 void TS::vprintf( int streams, const char* fmt, va_list l )
588 {
589     char str[1 << 14];
590     vsnprintf( str, sizeof(str)-1, fmt, l );
591
592     for( int i = 0; i < MAX_IDX; i++ )
593         if( (streams & (1 << i)) )
594         {
595             output_buf[i] += std::string(str);
596             // in the new GTest-based framework we do not use
597             // any output files (except for the automatically generated xml report).
598             // if a test fails, all the buffers are printed, so we do not want to duplicate the information and
599             // thus only add the new information to a single buffer and return from the function.
600             break;
601         }
602 }
603
604
605 void TS::printf( int streams, const char* fmt, ... )
606 {
607     if( streams )
608     {
609         va_list l;
610         va_start( l, fmt );
611         vprintf( streams, fmt, l );
612         va_end( l );
613     }
614 }
615
616
617 static TS ts;
618 TS* TS::ptr() { return &ts; }
619
620 void fillGradient(Mat& img, int delta)
621 {
622     const int ch = img.channels();
623     CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
624
625     int n = 255 / delta;
626     int r, c, i;
627     for(r=0; r<img.rows; r++)
628     {
629         int kR = r % (2*n);
630         int valR = (kR<=n) ? delta*kR : delta*(2*n-kR);
631         for(c=0; c<img.cols; c++)
632         {
633             int kC = c % (2*n);
634             int valC = (kC<=n) ? delta*kC : delta*(2*n-kC);
635             uchar vals[] = {uchar(valR), uchar(valC), uchar(200*r/img.rows), uchar(255)};
636             uchar *p = img.ptr(r, c);
637             for(i=0; i<ch; i++) p[i] = vals[i];
638         }
639     }
640 }
641
642 void smoothBorder(Mat& img, const Scalar& color, int delta)
643 {
644     const int ch = img.channels();
645     CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
646
647     Scalar s;
648     uchar *p = NULL;
649     int n = 100/delta;
650     int nR = std::min(n, (img.rows+1)/2), nC = std::min(n, (img.cols+1)/2);
651
652     int r, c, i;
653     for(r=0; r<nR; r++)
654     {
655         double k1 = r*delta/100., k2 = 1-k1;
656         for(c=0; c<img.cols; c++)
657         {
658             p = img.ptr(r, c);
659             for(i=0; i<ch; i++) s[i] = p[i];
660             s = s * k1 + color * k2;
661             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
662         }
663         for(c=0; c<img.cols; c++)
664         {
665             p = img.ptr(img.rows-r-1, c);
666             for(i=0; i<ch; i++) s[i] = p[i];
667             s = s * k1 + color * k2;
668             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
669         }
670     }
671
672     for(r=0; r<img.rows; r++)
673     {
674         for(c=0; c<nC; c++)
675         {
676             double k1 = c*delta/100., k2 = 1-k1;
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<n; c++)
683         {
684             double k1 = c*delta/100., k2 = 1-k1;
685             p = img.ptr(r, img.cols-c-1);
686             for(i=0; i<ch; i++) s[i] = p[i];
687             s = s * k1 + color * k2;
688             for(i=0; i<ch; i++) p[i] = uchar(s[i]);
689         }
690     }
691 }
692
693
694 bool test_ipp_check = false;
695
696 void checkIppStatus()
697 {
698     if (test_ipp_check)
699     {
700         int status = cv::ipp::getIppStatus();
701         EXPECT_LE(0, status) << cv::ipp::getIppErrorLocation().c_str();
702     }
703 }
704
705 bool skipUnstableTests = false;
706 bool runBigDataTests = false;
707 int testThreads = 0;
708
709 void parseCustomOptions(int argc, char **argv)
710 {
711     const char * const command_line_keys =
712         "{ ipp test_ipp_check |false    |check whether IPP works without failures }"
713         "{ test_seed          |809564   |seed for random numbers generator }"
714         "{ test_threads       |-1       |the number of worker threads, if parallel execution is enabled}"
715         "{ skip_unstable      |false    |skip unstable tests }"
716         "{ test_bigdata       |false    |run BigData tests (>=2Gb) }"
717         "{ h   help           |false    |print help info                          }";
718
719     cv::CommandLineParser parser(argc, argv, command_line_keys);
720     if (parser.get<bool>("help"))
721     {
722         std::cout << "\nAvailable options besides google test option: \n";
723         parser.printMessage();
724     }
725
726     test_ipp_check = parser.get<bool>("test_ipp_check");
727     if (!test_ipp_check)
728 #ifndef WINRT
729         test_ipp_check = getenv("OPENCV_IPP_CHECK") != NULL;
730 #else
731         test_ipp_check = false;
732 #endif
733
734     param_seed = parser.get<unsigned int>("test_seed");
735
736     testThreads = parser.get<int>("test_threads");
737
738     skipUnstableTests = parser.get<bool>("skip_unstable");
739     runBigDataTests = parser.get<bool>("test_bigdata");
740 }
741
742
743 static bool isDirectory(const std::string& path)
744 {
745 #if defined _WIN32 || defined WINCE
746     WIN32_FILE_ATTRIBUTE_DATA all_attrs;
747 #ifdef WINRT
748     wchar_t wpath[MAX_PATH];
749     size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
750     CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
751     BOOL status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs);
752 #else
753     BOOL status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
754 #endif
755     DWORD attributes = all_attrs.dwFileAttributes;
756     return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
757 #else
758     struct stat s;
759     if (0 != stat(path.c_str(), &s))
760         return false;
761     return S_ISDIR(s.st_mode);
762 #endif
763 }
764
765 void addDataSearchPath(const std::string& path)
766 {
767     if (isDirectory(path))
768         TS::ptr()->data_search_path.push_back(path);
769 }
770 void addDataSearchSubDirectory(const std::string& subdir)
771 {
772     TS::ptr()->data_search_subdir.push_back(subdir);
773 }
774
775 static std::string findData(const std::string& relative_path, bool required, bool findDirectory)
776 {
777 #define TEST_TRY_FILE_WITH_PREFIX(prefix) \
778 { \
779     std::string path = path_join(prefix, relative_path); \
780     /*printf("Trying %s\n", path.c_str());*/ \
781     if (findDirectory) \
782     { \
783         if (isDirectory(path)) \
784             return path; \
785     } \
786     else \
787     { \
788         FILE* f = fopen(path.c_str(), "rb"); \
789         if(f) { \
790             fclose(f); \
791             return path; \
792         } \
793     } \
794 }
795
796     const std::vector<std::string>& search_path = TS::ptr()->data_search_path;
797     for(size_t i = search_path.size(); i > 0; i--)
798     {
799         const std::string& prefix = search_path[i - 1];
800         TEST_TRY_FILE_WITH_PREFIX(prefix);
801     }
802
803     const std::vector<std::string>& search_subdir = TS::ptr()->data_search_subdir;
804
805 #ifndef WINRT
806     char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
807 #else
808     char* datapath_dir = OPENCV_TEST_DATA_PATH;
809 #endif
810
811     std::string datapath;
812     if (datapath_dir)
813     {
814         datapath = datapath_dir;
815         //CV_Assert(isDirectory(datapath) && "OPENCV_TEST_DATA_PATH is specified but it doesn't exist");
816         if (isDirectory(datapath))
817         {
818             for(size_t i = search_subdir.size(); i > 0; i--)
819             {
820                 const std::string& subdir = search_subdir[i - 1];
821                 std::string prefix = path_join(datapath, subdir);
822                 TEST_TRY_FILE_WITH_PREFIX(prefix);
823             }
824         }
825     }
826 #ifdef OPENCV_TEST_DATA_INSTALL_PATH
827     datapath = path_join("./", OPENCV_TEST_DATA_INSTALL_PATH);
828     if (isDirectory(datapath))
829     {
830         for(size_t i = search_subdir.size(); i > 0; i--)
831         {
832             const std::string& subdir = search_subdir[i - 1];
833             std::string prefix = path_join(datapath, subdir);
834             TEST_TRY_FILE_WITH_PREFIX(prefix);
835         }
836     }
837 #ifdef OPENCV_INSTALL_PREFIX
838     else
839     {
840         datapath = path_join(OPENCV_INSTALL_PREFIX, OPENCV_TEST_DATA_INSTALL_PATH);
841         if (isDirectory(datapath))
842         {
843             for(size_t i = search_subdir.size(); i > 0; i--)
844             {
845                 const std::string& subdir = search_subdir[i - 1];
846                 std::string prefix = path_join(datapath, subdir);
847                 TEST_TRY_FILE_WITH_PREFIX(prefix);
848             }
849         }
850     }
851 #endif
852 #endif
853     const char* type = findDirectory ? "directory" : "data file";
854     if (required)
855         CV_Error(cv::Error::StsError, cv::format("OpenCV tests: Can't find required %s: %s", type, relative_path.c_str()));
856     throw SkipTestException(cv::format("OpenCV tests: Can't find %s: %s", type, relative_path.c_str()));
857 }
858
859 std::string findDataFile(const std::string& relative_path, bool required)
860 {
861     return findData(relative_path, required, false);
862 }
863
864 std::string findDataDirectory(const std::string& relative_path, bool required)
865 {
866     return findData(relative_path, required, true);
867 }
868
869 } //namespace cvtest
870
871 /* End of file. */