1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
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.
10 // Intel License Agreement
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
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.
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.
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.
42 #include "precomp.hpp"
43 #include <opencv2/core/utils/configuration.private.hpp>
45 #include "opencv2/core/core_c.h"
72 #if defined _WIN32 || defined WINCE
76 # include <sys/stat.h>
81 #define DUMP_CONFIG_PROPERTY(propertyName, propertyValue) \
83 std::stringstream ssName, ssValue;\
84 ssName << propertyName;\
85 ssValue << (propertyValue); \
86 ::testing::Test::RecordProperty(ssName.str(), ssValue.str()); \
89 #define DUMP_MESSAGE_STDOUT(msg) \
91 std::cout << msg << std::endl; \
94 #include "opencv2/core/opencl/opencl_info.hpp"
96 #include "opencv2/core/utils/allocator_stats.hpp"
97 namespace cv { namespace ocl {
98 cv::utils::AllocatorStatisticsInterface& getOpenCLAllocatorStatistics();
100 #endif // HAVE_OPENCL
102 #include "opencv2/core/utils/allocator_stats.hpp"
104 CV_EXPORTS cv::utils::AllocatorStatisticsInterface& getAllocatorStatistics();
107 #include "opencv_tests_config.hpp"
109 #include "ts_tags.hpp"
111 #if defined(__GNUC__) && defined(__linux__)
113 size_t malloc_peak(void) __attribute__((weak));
114 void malloc_reset_peak(void) __attribute__((weak));
117 static size_t (*malloc_peak)(void) = 0;
118 static void (*malloc_reset_peak)(void) = 0;
121 namespace opencv_test {
122 bool required_opencv_test_namespace = false; // compilation check for non-refactored tests
128 uint64 param_seed = 0x12345678; // real value is passed via parseCustomOptions function
130 static std::string path_join(const std::string& prefix, const std::string& subpath)
132 CV_Assert(subpath.empty() || subpath[0] != '/');
135 bool skipSlash = prefix.size() > 0 ? (prefix[prefix.size()-1] == '/' || prefix[prefix.size()-1] == '\\') : false;
136 std::string path = prefix + (skipSlash ? "" : "/") + subpath;
142 /*****************************************************************************************\
143 * Exception and memory handlers *
144 \*****************************************************************************************/
146 // a few platform-dependent declarations
150 static void SEHTranslator( unsigned int /*u*/, EXCEPTION_POINTERS* pExp )
152 TS::FailureCode code = TS::FAIL_EXCEPTION;
153 switch( pExp->ExceptionRecord->ExceptionCode )
155 case EXCEPTION_ACCESS_VIOLATION:
156 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
157 case EXCEPTION_DATATYPE_MISALIGNMENT:
158 case EXCEPTION_FLT_STACK_CHECK:
159 case EXCEPTION_STACK_OVERFLOW:
160 case EXCEPTION_IN_PAGE_ERROR:
161 code = TS::FAIL_MEMORY_EXCEPTION;
163 case EXCEPTION_FLT_DENORMAL_OPERAND:
164 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
165 case EXCEPTION_FLT_INEXACT_RESULT:
166 case EXCEPTION_FLT_INVALID_OPERATION:
167 case EXCEPTION_FLT_OVERFLOW:
168 case EXCEPTION_FLT_UNDERFLOW:
169 case EXCEPTION_INT_DIVIDE_BY_ZERO:
170 case EXCEPTION_INT_OVERFLOW:
171 code = TS::FAIL_ARITHM_EXCEPTION;
173 case EXCEPTION_BREAKPOINT:
174 case EXCEPTION_ILLEGAL_INSTRUCTION:
175 case EXCEPTION_INVALID_DISPOSITION:
176 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
177 case EXCEPTION_PRIV_INSTRUCTION:
178 case EXCEPTION_SINGLE_STEP:
179 code = TS::FAIL_EXCEPTION;
187 static const int tsSigId[] = { SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT, -1 };
189 static jmp_buf tsJmpMark;
191 static void signalHandler( int sig_code )
193 TS::FailureCode code = TS::FAIL_EXCEPTION;
197 code = TS::FAIL_ARITHM_EXCEPTION;
201 code = TS::FAIL_ARITHM_EXCEPTION;
204 code = TS::FAIL_EXCEPTION;
207 longjmp( tsJmpMark, (int)code );
213 // reads 16-digit hexadecimal number (i.e. 64-bit integer)
214 int64 readSeed( const char* str )
217 if( str && strlen(str) == 16 )
219 for( int i = 0; str[i]; i++ )
221 int c = tolower(str[i]);
225 (str[i] < 'a' ? str[i] - '0' : str[i] - 'a' + 10);
232 /*****************************************************************************************\
233 * Base Class for Tests *
234 \*****************************************************************************************/
239 test_case_count = -1;
242 BaseTest::~BaseTest()
247 void BaseTest::clear()
252 const CvFileNode* BaseTest::find_param( CvFileStorage* fs, const char* param_name )
254 CvFileNode* node = cvGetFileNodeByName(fs, 0, get_name().c_str());
255 return node ? cvGetFileNodeByName( fs, node, param_name ) : 0;
259 int BaseTest::read_params( CvFileStorage* )
265 bool BaseTest::can_do_fast_forward()
271 void BaseTest::safe_run( int start_from )
274 ts->update_context( 0, -1, true );
275 ts->update_context( this, -1, true );
277 if( !::testing::GTEST_FLAG(catch_exceptions) )
284 int _code = setjmp( tsJmpMark );
288 throw TS::FailureCode(_code);
293 catch (const cv::Exception& exc)
295 const char* errorStr = cvErrorStr(exc.code);
298 const char* delim = exc.err.find('\n') == cv::String::npos ? "" : "\n";
299 sprintf( buf, "OpenCV Error:\n\t%s (%s%s) in %s, file %s, line %d",
300 errorStr, delim, exc.err.c_str(), exc.func.size() > 0 ?
301 exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line );
302 ts->printf(TS::LOG, "%s\n", buf);
304 ts->set_failed_test_info( TS::FAIL_ERROR_IN_CALLED_FUNC );
306 catch (const TS::FailureCode& fc)
308 std::string errorStr = TS::str_from_code(fc);
309 ts->printf(TS::LOG, "General failure:\n\t%s (%d)\n", errorStr.c_str(), fc);
311 ts->set_failed_test_info( fc );
315 ts->printf(TS::LOG, "Unknown failure\n");
317 ts->set_failed_test_info( TS::FAIL_EXCEPTION );
321 ts->set_gtest_status();
325 void BaseTest::run( int start_from )
327 int test_case_idx, count = get_test_case_count();
328 int64 t_start = cvGetTickCount();
329 double freq = cv::getTickFrequency();
330 bool ff = can_do_fast_forward();
331 int progress = 0, code;
334 for( test_case_idx = ff && start_from >= 0 ? start_from : 0;
335 count < 0 || test_case_idx < count; test_case_idx++ )
337 ts->update_context( this, test_case_idx, ff );
338 progress = update_progress( progress, test_case_idx, count, (double)(t1 - t_start)/(freq*1000) );
340 code = prepare_test_case( test_case_idx );
341 if( code < 0 || ts->get_err_code() < 0 )
349 if( ts->get_err_code() < 0 )
352 if( validate_test_results( test_case_idx ) < 0 || ts->get_err_code() < 0 )
358 void BaseTest::run_func(void)
364 int BaseTest::get_test_case_count(void)
366 return test_case_count;
370 int BaseTest::prepare_test_case( int )
376 int BaseTest::validate_test_results( int )
382 int BaseTest::update_progress( int progress, int test_case_idx, int count, double dt )
384 int width = 60 - (int)get_name().size();
387 int t = cvRound( ((double)test_case_idx * width)/count );
390 ts->printf( TS::CONSOLE, "." );
394 else if( cvRound(dt) > progress )
396 ts->printf( TS::CONSOLE, "." );
397 progress = cvRound(dt);
404 BadArgTest::BadArgTest()
408 // oldErrorCbkData = 0;
411 BadArgTest::~BadArgTest(void)
415 int BadArgTest::run_test_case( int expected_code, const string& _descr )
419 const char* descr = _descr.c_str() ? _descr.c_str() : "";
425 catch(const cv::Exception& e)
428 if (e.code != expected_code &&
429 e.code != cv::Error::StsError && e.code != cv::Error::StsAssert // Exact error codes support will be dropped. Checks should provide proper text messages intead.
432 ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
433 descr, test_case_idx, e.code, expected_code);
440 ts->printf(TS::LOG, "%s (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
441 descr, test_case_idx);
447 ts->printf(TS::LOG, "%s (test case #%d): no expected exception was thrown\n",
448 descr, test_case_idx);
456 /*****************************************************************************************\
457 * Base Class for Test System *
458 \*****************************************************************************************/
460 /******************************** Constructors/Destructors ******************************/
464 rng_seed = (uint64)-1;
465 use_optimized = true;
466 test_case_count_scale = 1;
474 rng_seed = rng_seed0 = 0;
489 string TS::str_from_code( const TS::FailureCode code )
493 case OK: return "Ok";
494 case FAIL_GENERIC: return "Generic/Unknown";
495 case FAIL_MISSING_TEST_DATA: return "No test data";
496 case FAIL_INVALID_TEST_DATA: return "Invalid test data";
497 case FAIL_ERROR_IN_CALLED_FUNC: return "cvError invoked";
498 case FAIL_EXCEPTION: return "Hardware/OS exception";
499 case FAIL_MEMORY_EXCEPTION: return "Invalid memory access";
500 case FAIL_ARITHM_EXCEPTION: return "Arithmetic exception";
501 case FAIL_MEMORY_CORRUPTION_BEGIN: return "Corrupted memblock (beginning)";
502 case FAIL_MEMORY_CORRUPTION_END: return "Corrupted memblock (end)";
503 case FAIL_MEMORY_LEAK: return "Memory leak";
504 case FAIL_INVALID_OUTPUT: return "Invalid function output";
505 case FAIL_MISMATCH: return "Unexpected output";
506 case FAIL_BAD_ACCURACY: return "Bad accuracy";
507 case FAIL_HANG: return "Infinite loop(?)";
508 case FAIL_BAD_ARG_CHECK: return "Incorrect handling of bad arguments";
512 return "Generic/Unknown";
515 static int tsErrorCallback( int status, const char* func_name, const char* err_msg, const char* file_name, int line, TS* ts )
517 const char* delim = std::string(err_msg).find('\n') == std::string::npos ? "" : "\n";
518 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);
522 /************************************** Running tests **********************************/
524 void TS::init( const string& modulename )
526 data_search_subdir.push_back(modulename);
528 char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
530 char* datapath_dir = OPENCV_TEST_DATA_PATH;
535 data_path = path_join(path_join(datapath_dir, modulename), "");
538 cv::redirectError((cv::ErrorCallback)tsErrorCallback, this);
540 if( ::testing::GTEST_FLAG(catch_exceptions) )
544 _set_se_translator( SEHTranslator );
547 for( int i = 0; tsSigId[i] >= 0; i++ )
548 signal( tsSigId[i], signalHandler );
555 _set_se_translator( 0 );
558 for( int i = 0; tsSigId[i] >= 0; i++ )
559 signal( tsSigId[i], SIG_DFL );
563 if( params.use_optimized == 0 )
564 cv::setUseOptimized(false);
566 rng = RNG(params.rng_seed);
570 void TS::set_gtest_status()
572 TS::FailureCode code = get_err_code();
577 sprintf(seedstr, "%08x%08x", (unsigned)(current_test_info.rng_seed>>32),
578 (unsigned)(current_test_info.rng_seed));
581 if( !output_buf[SUMMARY_IDX].empty() )
582 logs += "\n-----------------------------------\n\tSUM: " + output_buf[SUMMARY_IDX];
583 if( !output_buf[LOG_IDX].empty() )
584 logs += "\n-----------------------------------\n\tLOG:\n" + output_buf[LOG_IDX];
585 if( !output_buf[CONSOLE_IDX].empty() )
586 logs += "\n-----------------------------------\n\tCONSOLE: " + output_buf[CONSOLE_IDX];
587 logs += "\n-----------------------------------\n";
589 FAIL() << "\n\tfailure reason: " << str_from_code(code) <<
590 "\n\ttest case #" << current_test_info.test_case_idx <<
591 "\n\tseed: " << seedstr << logs;
595 void TS::update_context( BaseTest* test, int test_case_idx, bool update_ts_context )
597 if( current_test_info.test != test )
599 for( int i = 0; i <= CONSOLE_IDX; i++ )
600 output_buf[i] = string();
601 rng = RNG(params.rng_seed);
602 current_test_info.rng_seed0 = current_test_info.rng_seed = rng.state;
605 current_test_info.test = test;
606 current_test_info.test_case_idx = test_case_idx;
607 current_test_info.code = 0;
608 cvSetErrStatus( CV_StsOk );
609 if( update_ts_context )
610 current_test_info.rng_seed = rng.state;
614 void TS::set_failed_test_info( int fail_code )
616 if( current_test_info.code >= 0 )
617 current_test_info.code = TS::FailureCode(fail_code);
620 #if defined _MSC_VER && _MSC_VER < 1400
622 #define vsnprintf _vsnprintf
625 void TS::vprintf( int streams, const char* fmt, va_list l )
628 vsnprintf( str, sizeof(str)-1, fmt, l );
630 for( int i = 0; i < MAX_IDX; i++ )
631 if( (streams & (1 << i)) )
633 output_buf[i] += std::string(str);
634 // in the new GTest-based framework we do not use
635 // any output files (except for the automatically generated xml report).
636 // if a test fails, all the buffers are printed, so we do not want to duplicate the information and
637 // thus only add the new information to a single buffer and return from the function.
643 void TS::printf( int streams, const char* fmt, ... )
649 vprintf( streams, fmt, l );
661 void fillGradient(Mat& img, int delta)
663 const int ch = img.channels();
664 CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
668 for(r=0; r<img.rows; r++)
671 int valR = (kR<=n) ? delta*kR : delta*(2*n-kR);
672 for(c=0; c<img.cols; c++)
675 int valC = (kC<=n) ? delta*kC : delta*(2*n-kC);
676 uchar vals[] = {uchar(valR), uchar(valC), uchar(200*r/img.rows), uchar(255)};
677 uchar *p = img.ptr(r, c);
678 for(i=0; i<ch; i++) p[i] = vals[i];
683 void smoothBorder(Mat& img, const Scalar& color, int delta)
685 const int ch = img.channels();
686 CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
691 int nR = std::min(n, (img.rows+1)/2), nC = std::min(n, (img.cols+1)/2);
696 double k1 = r*delta/100., k2 = 1-k1;
697 for(c=0; c<img.cols; c++)
700 for(i=0; i<ch; i++) s[i] = p[i];
701 s = s * k1 + color * k2;
702 for(i=0; i<ch; i++) p[i] = uchar(s[i]);
704 for(c=0; c<img.cols; c++)
706 p = img.ptr(img.rows-r-1, c);
707 for(i=0; i<ch; i++) s[i] = p[i];
708 s = s * k1 + color * k2;
709 for(i=0; i<ch; i++) p[i] = uchar(s[i]);
713 for(r=0; r<img.rows; r++)
717 double k1 = c*delta/100., k2 = 1-k1;
719 for(i=0; i<ch; i++) s[i] = p[i];
720 s = s * k1 + color * k2;
721 for(i=0; i<ch; i++) p[i] = uchar(s[i]);
725 double k1 = c*delta/100., k2 = 1-k1;
726 p = img.ptr(r, img.cols-c-1);
727 for(i=0; i<ch; i++) s[i] = p[i];
728 s = s * k1 + color * k2;
729 for(i=0; i<ch; i++) p[i] = uchar(s[i]);
735 bool test_ipp_check = false;
737 void checkIppStatus()
741 int status = cv::ipp::getIppStatus();
742 EXPECT_LE(0, status) << cv::ipp::getIppErrorLocation().c_str();
746 static bool checkTestData = cv::utils::getConfigurationParameterBool("OPENCV_TEST_REQUIRE_DATA", false);
747 bool skipUnstableTests = false;
748 bool runBigDataTests = false;
752 static size_t memory_usage_base = 0;
753 static uint64_t memory_usage_base_opencv = 0;
755 static uint64_t memory_usage_base_opencl = 0;
760 fflush(stdout); fflush(stderr);
761 cv::ipp::setIppStatus(0);
762 cv::theRNG().state = cvtest::param_seed;
763 cv::setNumThreads(cvtest::testThreads);
764 if (malloc_peak) // if memory profiler is available
767 memory_usage_base = malloc_peak(); // equal to malloc_current()
770 cv::utils::AllocatorStatisticsInterface& ocv_stats = cv::getAllocatorStatistics();
771 ocv_stats.resetPeakUsage();
772 memory_usage_base_opencv = ocv_stats.getCurrentUsage();
776 cv::utils::AllocatorStatisticsInterface& ocl_stats = cv::ocl::getOpenCLAllocatorStatistics();
777 ocl_stats.resetPeakUsage();
778 memory_usage_base_opencl = ocl_stats.getCurrentUsage();
786 ::cvtest::checkIppStatus();
787 uint64_t memory_usage = 0;
788 uint64_t ocv_memory_usage = 0, ocv_peak = 0;
789 if (malloc_peak) // if memory profiler is available
791 size_t peak = malloc_peak();
792 memory_usage = peak - memory_usage_base;
795 CV_LOG_INFO(NULL, "Memory_usage (malloc): " << memory_usage << " (base=" << memory_usage_base << ")");
799 // core/src/alloc.cpp: #define OPENCV_ALLOC_ENABLE_STATISTICS
800 // handle large buffers via fastAlloc()
801 // (not always accurate on heavy 3rdparty usage, like protobuf)
802 cv::utils::AllocatorStatisticsInterface& ocv_stats = cv::getAllocatorStatistics();
803 ocv_peak = ocv_stats.getPeakUsage();
804 ocv_memory_usage = ocv_peak - memory_usage_base_opencv;
807 CV_LOG_INFO(NULL, "Memory_usage (OpenCV): " << ocv_memory_usage << " (base=" << memory_usage_base_opencv << " current=" << ocv_stats.getCurrentUsage() << ")");
809 if (memory_usage == 0) // external profiler has higher priority (and accuracy)
810 memory_usage = ocv_memory_usage;
813 uint64_t ocl_memory_usage = 0, ocl_peak = 0;
815 cv::utils::AllocatorStatisticsInterface& ocl_stats = cv::ocl::getOpenCLAllocatorStatistics();
816 ocl_peak = ocl_stats.getPeakUsage();
817 ocl_memory_usage = ocl_peak - memory_usage_base_opencl;
818 if (ocl_memory_usage > 0)
820 CV_LOG_INFO(NULL, "Memory_usage (OpenCL): " << ocl_memory_usage << " (base=" << memory_usage_base_opencl << " current=" << ocl_stats.getCurrentUsage() << ")");
822 ::testing::Test::RecordProperty("ocl_memory_usage",
823 cv::format("%llu", (unsigned long long)ocl_memory_usage));
826 uint64_t ocl_memory_usage = 0;
828 if (malloc_peak // external memory profiler is available
829 || ocv_peak > 0 // or enabled OpenCV builtin allocation statistics
832 CV_LOG_INFO(NULL, "Memory usage total: " << (memory_usage + ocl_memory_usage));
833 ::testing::Test::RecordProperty("memory_usage",
834 cv::format("%llu", (unsigned long long)memory_usage));
835 ::testing::Test::RecordProperty("total_memory_usage",
836 cv::format("%llu", (unsigned long long)(memory_usage + ocl_memory_usage)));
840 void parseCustomOptions(int argc, char **argv)
842 const string command_line_keys = string(
843 "{ ipp test_ipp_check |false |check whether IPP works without failures }"
844 "{ test_seed |809564 |seed for random numbers generator }"
845 "{ test_threads |-1 |the number of worker threads, if parallel execution is enabled}"
846 "{ skip_unstable |false |skip unstable tests }"
847 "{ test_bigdata |false |run BigData tests (>=2Gb) }"
848 "{ test_require_data |") + (checkTestData ? "true" : "false") + string("|fail on missing non-required test data instead of skip (env:OPENCV_TEST_REQUIRE_DATA)}"
850 "{ h help |false |print help info }"
853 cv::CommandLineParser parser(argc, argv, command_line_keys);
854 if (parser.get<bool>("help"))
856 std::cout << "\nAvailable options besides google test option: \n";
857 parser.printMessage();
860 test_ipp_check = parser.get<bool>("test_ipp_check");
863 test_ipp_check = getenv("OPENCV_IPP_CHECK") != NULL;
865 test_ipp_check = false;
868 param_seed = parser.get<unsigned int>("test_seed");
870 testThreads = parser.get<int>("test_threads");
872 skipUnstableTests = parser.get<bool>("skip_unstable");
873 runBigDataTests = parser.get<bool>("test_bigdata");
874 if (parser.has("test_require_data"))
875 checkTestData = parser.get<bool>("test_require_data");
877 activateTestTags(parser);
880 static bool isDirectory(const std::string& path)
882 #if defined _WIN32 || defined WINCE
883 WIN32_FILE_ATTRIBUTE_DATA all_attrs;
885 wchar_t wpath[MAX_PATH];
886 size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
887 CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
888 BOOL status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs);
890 BOOL status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
892 DWORD attributes = all_attrs.dwFileAttributes;
893 return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
896 if (0 != stat(path.c_str(), &s))
898 return S_ISDIR(s.st_mode);
902 void addDataSearchPath(const std::string& path)
904 if (isDirectory(path))
905 TS::ptr()->data_search_path.push_back(path);
907 void addDataSearchSubDirectory(const std::string& subdir)
909 TS::ptr()->data_search_subdir.push_back(subdir);
912 static std::string findData(const std::string& relative_path, bool required, bool findDirectory)
914 #define CHECK_FILE_WITH_PREFIX(prefix, result) \
917 std::string path = path_join(prefix, relative_path); \
918 /*printf("Trying %s\n", path.c_str());*/ \
921 if (isDirectory(path)) \
926 FILE* f = fopen(path.c_str(), "rb"); \
934 #define TEST_TRY_FILE_WITH_PREFIX(prefix) \
936 std::string result__; \
937 CHECK_FILE_WITH_PREFIX(prefix, result__); \
938 if (!result__.empty()) \
943 const std::vector<std::string>& search_path = TS::ptr()->data_search_path;
944 for(size_t i = search_path.size(); i > 0; i--)
946 const std::string& prefix = search_path[i - 1];
947 TEST_TRY_FILE_WITH_PREFIX(prefix);
950 const std::vector<std::string>& search_subdir = TS::ptr()->data_search_subdir;
953 char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
955 char* datapath_dir = OPENCV_TEST_DATA_PATH;
958 std::string datapath;
961 datapath = datapath_dir;
962 //CV_Assert(isDirectory(datapath) && "OPENCV_TEST_DATA_PATH is specified but it doesn't exist");
963 if (isDirectory(datapath))
965 for(size_t i = search_subdir.size(); i > 0; i--)
967 const std::string& subdir = search_subdir[i - 1];
968 std::string prefix = path_join(datapath, subdir);
970 CHECK_FILE_WITH_PREFIX(prefix, result_);
971 if (!required && !result_.empty())
973 std::cout << "TEST ERROR: Don't use 'optional' findData() for " << relative_path << std::endl;
974 static bool checkOptionalFlag = cv::utils::getConfigurationParameterBool("OPENCV_TEST_CHECK_OPTIONAL_DATA", false);
975 if (checkOptionalFlag)
977 CV_Assert(required || result_.empty());
980 if (!result_.empty())
985 #ifdef OPENCV_TEST_DATA_INSTALL_PATH
986 datapath = path_join("./", OPENCV_TEST_DATA_INSTALL_PATH);
987 if (isDirectory(datapath))
989 for(size_t i = search_subdir.size(); i > 0; i--)
991 const std::string& subdir = search_subdir[i - 1];
992 std::string prefix = path_join(datapath, subdir);
993 TEST_TRY_FILE_WITH_PREFIX(prefix);
996 #ifdef OPENCV_INSTALL_PREFIX
999 datapath = path_join(OPENCV_INSTALL_PREFIX, OPENCV_TEST_DATA_INSTALL_PATH);
1000 if (isDirectory(datapath))
1002 for(size_t i = search_subdir.size(); i > 0; i--)
1004 const std::string& subdir = search_subdir[i - 1];
1005 std::string prefix = path_join(datapath, subdir);
1006 TEST_TRY_FILE_WITH_PREFIX(prefix);
1012 const char* type = findDirectory ? "directory" : "data file";
1013 if (required || checkTestData)
1014 CV_Error(cv::Error::StsError, cv::format("OpenCV tests: Can't find required %s: %s", type, relative_path.c_str()));
1015 throw SkipTestException(cv::format("OpenCV tests: Can't find %s: %s", type, relative_path.c_str()));
1018 std::string findDataFile(const std::string& relative_path, bool required)
1020 return findData(relative_path, required, false);
1023 std::string findDataDirectory(const std::string& relative_path, bool required)
1025 return findData(relative_path, required, true);
1028 inline static std::string getSnippetFromConfig(const std::string & start, const std::string & end)
1030 const std::string buildInfo = cv::getBuildInformation();
1031 size_t pos1 = buildInfo.find(start);
1032 if (pos1 != std::string::npos)
1034 pos1 += start.length();
1035 pos1 = buildInfo.find_first_not_of(" \t\n\r", pos1);
1037 size_t pos2 = buildInfo.find(end, pos1);
1038 if (pos2 != std::string::npos)
1040 pos2 = buildInfo.find_last_not_of(" \t\n\r", pos2);
1042 if (pos1 != std::string::npos && pos2 != std::string::npos && pos1 < pos2)
1044 return buildInfo.substr(pos1, pos2 - pos1 + 1);
1046 return std::string();
1049 inline static void recordPropertyVerbose(const std::string & property,
1050 const std::string & msg,
1051 const std::string & value,
1052 const std::string & build_value = std::string())
1054 ::testing::Test::RecordProperty(property, value);
1055 std::cout << msg << ": " << (value.empty() ? std::string("N/A") : value) << std::endl;
1056 if (!build_value.empty())
1058 ::testing::Test::RecordProperty(property + "_build", build_value);
1059 if (build_value != value)
1060 std::cout << "WARNING: build value differs from runtime: " << build_value << endl;
1064 inline static void recordPropertyVerbose(const std::string& property, const std::string& msg,
1065 const char* value, const char* build_value = NULL)
1067 return recordPropertyVerbose(property, msg,
1068 value ? std::string(value) : std::string(),
1069 build_value ? std::string(build_value) : std::string());
1073 #define CV_TEST_BUILD_CONFIG "Debug"
1075 #define CV_TEST_BUILD_CONFIG "Release"
1078 void SystemInfoCollector::OnTestProgramStart(const testing::UnitTest&)
1080 std::cout << "CTEST_FULL_OUTPUT" << std::endl; // Tell CTest not to discard any output
1081 recordPropertyVerbose("cv_version", "OpenCV version", cv::getVersionString(), CV_VERSION);
1082 recordPropertyVerbose("cv_vcs_version", "OpenCV VCS version", getSnippetFromConfig("Version control:", "\n"));
1083 recordPropertyVerbose("cv_build_type", "Build type", getSnippetFromConfig("Configuration:", "\n"), CV_TEST_BUILD_CONFIG);
1084 recordPropertyVerbose("cv_compiler", "Compiler", getSnippetFromConfig("C++ Compiler:", "\n"));
1085 recordPropertyVerbose("cv_parallel_framework", "Parallel framework", cv::currentParallelFramework());
1086 recordPropertyVerbose("cv_cpu_features", "CPU features", cv::getCPUFeaturesLine());
1088 recordPropertyVerbose("cv_ipp_version", "Intel(R) IPP version", cv::ipp::useIPP() ? cv::ipp::getIppVersion() : "disabled");
1091 cv::dumpOpenCLInformation();
1095 } //namespace cvtest