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/core_c.h"
70 #if defined _WIN32 || defined WINCE
74 # include <sys/stat.h>
78 #include "opencv_tests_config.hpp"
80 namespace opencv_test {
81 bool required_opencv_test_namespace = false; // compilation check for non-refactored tests
87 uint64 param_seed = 0x12345678; // real value is passed via parseCustomOptions function
89 static std::string path_join(const std::string& prefix, const std::string& subpath)
91 CV_Assert(subpath.empty() || subpath[0] != '/');
94 bool skipSlash = prefix.size() > 0 ? (prefix[prefix.size()-1] == '/' || prefix[prefix.size()-1] == '\\') : false;
95 std::string path = prefix + (skipSlash ? "" : "/") + subpath;
101 /*****************************************************************************************\
102 * Exception and memory handlers *
103 \*****************************************************************************************/
105 // a few platform-dependent declarations
109 static void SEHTranslator( unsigned int /*u*/, EXCEPTION_POINTERS* pExp )
111 TS::FailureCode code = TS::FAIL_EXCEPTION;
112 switch( pExp->ExceptionRecord->ExceptionCode )
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;
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;
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;
146 static const int tsSigId[] = { SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT, -1 };
148 static jmp_buf tsJmpMark;
150 static void signalHandler( int sig_code )
152 TS::FailureCode code = TS::FAIL_EXCEPTION;
156 code = TS::FAIL_ARITHM_EXCEPTION;
160 code = TS::FAIL_ARITHM_EXCEPTION;
163 code = TS::FAIL_EXCEPTION;
166 longjmp( tsJmpMark, (int)code );
172 // reads 16-digit hexadecimal number (i.e. 64-bit integer)
173 int64 readSeed( const char* str )
176 if( str && strlen(str) == 16 )
178 for( int i = 0; str[i]; i++ )
180 int c = tolower(str[i]);
184 (str[i] < 'a' ? str[i] - '0' : str[i] - 'a' + 10);
191 /*****************************************************************************************\
192 * Base Class for Tests *
193 \*****************************************************************************************/
198 test_case_count = -1;
201 BaseTest::~BaseTest()
206 void BaseTest::clear()
211 const CvFileNode* BaseTest::find_param( CvFileStorage* fs, const char* param_name )
213 CvFileNode* node = cvGetFileNodeByName(fs, 0, get_name().c_str());
214 return node ? cvGetFileNodeByName( fs, node, param_name ) : 0;
218 int BaseTest::read_params( CvFileStorage* )
224 bool BaseTest::can_do_fast_forward()
230 void BaseTest::safe_run( int start_from )
233 read_params( ts->get_file_storage() );
234 ts->update_context( 0, -1, true );
235 ts->update_context( this, -1, true );
237 if( !::testing::GTEST_FLAG(catch_exceptions) )
244 int _code = setjmp( tsJmpMark );
248 throw TS::FailureCode(_code);
253 catch (const cv::Exception& exc)
255 const char* errorStr = cvErrorStr(exc.code);
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);
264 ts->set_failed_test_info( TS::FAIL_ERROR_IN_CALLED_FUNC );
266 catch (const TS::FailureCode& fc)
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);
271 ts->set_failed_test_info( fc );
275 ts->printf(TS::LOG, "Unknown failure\n");
277 ts->set_failed_test_info( TS::FAIL_EXCEPTION );
281 ts->set_gtest_status();
285 void BaseTest::run( int start_from )
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;
294 for( test_case_idx = ff && start_from >= 0 ? start_from : 0;
295 count < 0 || test_case_idx < count; test_case_idx++ )
297 ts->update_context( this, test_case_idx, ff );
298 progress = update_progress( progress, test_case_idx, count, (double)(t1 - t_start)/(freq*1000) );
300 code = prepare_test_case( test_case_idx );
301 if( code < 0 || ts->get_err_code() < 0 )
309 if( ts->get_err_code() < 0 )
312 if( validate_test_results( test_case_idx ) < 0 || ts->get_err_code() < 0 )
318 void BaseTest::run_func(void)
324 int BaseTest::get_test_case_count(void)
326 return test_case_count;
330 int BaseTest::prepare_test_case( int )
336 int BaseTest::validate_test_results( int )
342 int BaseTest::update_progress( int progress, int test_case_idx, int count, double dt )
344 int width = 60 - (int)get_name().size();
347 int t = cvRound( ((double)test_case_idx * width)/count );
350 ts->printf( TS::CONSOLE, "." );
354 else if( cvRound(dt) > progress )
356 ts->printf( TS::CONSOLE, "." );
357 progress = cvRound(dt);
364 BadArgTest::BadArgTest()
368 // oldErrorCbkData = 0;
371 BadArgTest::~BadArgTest(void)
375 int BadArgTest::run_test_case( int expected_code, const string& _descr )
379 const char* descr = _descr.c_str() ? _descr.c_str() : "";
385 catch(const cv::Exception& e)
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.
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);
400 ts->printf(TS::LOG, "%s (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
401 descr, test_case_idx);
407 ts->printf(TS::LOG, "%s (test case #%d): no expected exception was thrown\n",
408 descr, test_case_idx);
416 /*****************************************************************************************\
417 * Base Class for Test System *
418 \*****************************************************************************************/
420 /******************************** Constructors/Destructors ******************************/
424 rng_seed = (uint64)-1;
425 use_optimized = true;
426 test_case_count_scale = 1;
434 rng_seed = rng_seed0 = 0;
449 string TS::str_from_code( const TS::FailureCode code )
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";
472 return "Generic/Unknown";
475 static int tsErrorCallback( int status, const char* func_name, const char* err_msg, const char* file_name, int line, TS* ts )
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);
482 /************************************** Running tests **********************************/
484 void TS::init( const string& modulename )
486 data_search_subdir.push_back(modulename);
488 char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
490 char* datapath_dir = OPENCV_TEST_DATA_PATH;
495 data_path = path_join(path_join(datapath_dir, modulename), "");
498 cv::redirectError((cv::ErrorCallback)tsErrorCallback, this);
500 if( ::testing::GTEST_FLAG(catch_exceptions) )
504 _set_se_translator( SEHTranslator );
507 for( int i = 0; tsSigId[i] >= 0; i++ )
508 signal( tsSigId[i], signalHandler );
515 _set_se_translator( 0 );
518 for( int i = 0; tsSigId[i] >= 0; i++ )
519 signal( tsSigId[i], SIG_DFL );
523 if( params.use_optimized == 0 )
524 cv::setUseOptimized(false);
526 rng = RNG(params.rng_seed);
530 void TS::set_gtest_status()
532 TS::FailureCode code = get_err_code();
537 sprintf(seedstr, "%08x%08x", (unsigned)(current_test_info.rng_seed>>32),
538 (unsigned)(current_test_info.rng_seed));
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";
549 FAIL() << "\n\tfailure reason: " << str_from_code(code) <<
550 "\n\ttest case #" << current_test_info.test_case_idx <<
551 "\n\tseed: " << seedstr << logs;
555 CvFileStorage* TS::get_file_storage() { return 0; }
557 void TS::update_context( BaseTest* test, int test_case_idx, bool update_ts_context )
559 if( current_test_info.test != test )
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;
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;
576 void TS::set_failed_test_info( int fail_code )
578 if( current_test_info.code >= 0 )
579 current_test_info.code = TS::FailureCode(fail_code);
582 #if defined _MSC_VER && _MSC_VER < 1400
584 #define vsnprintf _vsnprintf
587 void TS::vprintf( int streams, const char* fmt, va_list l )
590 vsnprintf( str, sizeof(str)-1, fmt, l );
592 for( int i = 0; i < MAX_IDX; i++ )
593 if( (streams & (1 << i)) )
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.
605 void TS::printf( int streams, const char* fmt, ... )
611 vprintf( streams, fmt, l );
618 TS* TS::ptr() { return &ts; }
620 void fillGradient(Mat& img, int delta)
622 const int ch = img.channels();
623 CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
627 for(r=0; r<img.rows; r++)
630 int valR = (kR<=n) ? delta*kR : delta*(2*n-kR);
631 for(c=0; c<img.cols; c++)
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];
642 void smoothBorder(Mat& img, const Scalar& color, int delta)
644 const int ch = img.channels();
645 CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);
650 int nR = std::min(n, (img.rows+1)/2), nC = std::min(n, (img.cols+1)/2);
655 double k1 = r*delta/100., k2 = 1-k1;
656 for(c=0; c<img.cols; 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]);
663 for(c=0; c<img.cols; c++)
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]);
672 for(r=0; r<img.rows; r++)
676 double k1 = c*delta/100., k2 = 1-k1;
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]);
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]);
694 bool test_ipp_check = false;
696 void checkIppStatus()
700 int status = cv::ipp::getIppStatus();
701 EXPECT_LE(0, status) << cv::ipp::getIppErrorLocation().c_str();
705 bool skipUnstableTests = false;
706 bool runBigDataTests = false;
709 void parseCustomOptions(int argc, char **argv)
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 }";
719 cv::CommandLineParser parser(argc, argv, command_line_keys);
720 if (parser.get<bool>("help"))
722 std::cout << "\nAvailable options besides google test option: \n";
723 parser.printMessage();
726 test_ipp_check = parser.get<bool>("test_ipp_check");
729 test_ipp_check = getenv("OPENCV_IPP_CHECK") != NULL;
731 test_ipp_check = false;
734 param_seed = parser.get<unsigned int>("test_seed");
736 testThreads = parser.get<int>("test_threads");
738 skipUnstableTests = parser.get<bool>("skip_unstable");
739 runBigDataTests = parser.get<bool>("test_bigdata");
743 static bool isDirectory(const std::string& path)
745 #if defined _WIN32 || defined WINCE
746 WIN32_FILE_ATTRIBUTE_DATA all_attrs;
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);
753 BOOL status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
755 DWORD attributes = all_attrs.dwFileAttributes;
756 return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
759 if (0 != stat(path.c_str(), &s))
761 return S_ISDIR(s.st_mode);
765 void addDataSearchPath(const std::string& path)
767 if (isDirectory(path))
768 TS::ptr()->data_search_path.push_back(path);
770 void addDataSearchSubDirectory(const std::string& subdir)
772 TS::ptr()->data_search_subdir.push_back(subdir);
775 static std::string findData(const std::string& relative_path, bool required, bool findDirectory)
777 #define TEST_TRY_FILE_WITH_PREFIX(prefix) \
779 std::string path = path_join(prefix, relative_path); \
780 /*printf("Trying %s\n", path.c_str());*/ \
783 if (isDirectory(path)) \
788 FILE* f = fopen(path.c_str(), "rb"); \
796 const std::vector<std::string>& search_path = TS::ptr()->data_search_path;
797 for(size_t i = search_path.size(); i > 0; i--)
799 const std::string& prefix = search_path[i - 1];
800 TEST_TRY_FILE_WITH_PREFIX(prefix);
803 const std::vector<std::string>& search_subdir = TS::ptr()->data_search_subdir;
806 char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
808 char* datapath_dir = OPENCV_TEST_DATA_PATH;
811 std::string datapath;
814 datapath = datapath_dir;
815 //CV_Assert(isDirectory(datapath) && "OPENCV_TEST_DATA_PATH is specified but it doesn't exist");
816 if (isDirectory(datapath))
818 for(size_t i = search_subdir.size(); i > 0; i--)
820 const std::string& subdir = search_subdir[i - 1];
821 std::string prefix = path_join(datapath, subdir);
822 TEST_TRY_FILE_WITH_PREFIX(prefix);
826 #ifdef OPENCV_TEST_DATA_INSTALL_PATH
827 datapath = path_join("./", OPENCV_TEST_DATA_INSTALL_PATH);
828 if (isDirectory(datapath))
830 for(size_t i = search_subdir.size(); i > 0; i--)
832 const std::string& subdir = search_subdir[i - 1];
833 std::string prefix = path_join(datapath, subdir);
834 TEST_TRY_FILE_WITH_PREFIX(prefix);
837 #ifdef OPENCV_INSTALL_PREFIX
840 datapath = path_join(OPENCV_INSTALL_PREFIX, OPENCV_TEST_DATA_INSTALL_PATH);
841 if (isDirectory(datapath))
843 for(size_t i = search_subdir.size(); i > 0; i--)
845 const std::string& subdir = search_subdir[i - 1];
846 std::string prefix = path_join(datapath, subdir);
847 TEST_TRY_FILE_WITH_PREFIX(prefix);
853 const char* type = findDirectory ? "directory" : "data file";
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()));
859 std::string findDataFile(const std::string& relative_path, bool required)
861 return findData(relative_path, required, false);
864 std::string findDataDirectory(const std::string& relative_path, bool required)
866 return findData(relative_path, required, true);