ts.cpp 31.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of Intel Corporation may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"
43 44
#include <opencv2/core/utils/configuration.private.hpp>

45 46
#include "opencv2/core/core_c.h"

47 48 49 50 51
#include <ctype.h>
#include <stdarg.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
52
#if defined _WIN32
53
#include <io.h>
54

55
#include <windows.h>
56 57 58 59
#undef small
#undef min
#undef max
#undef abs
60 61 62 63 64 65 66

#ifdef _MSC_VER
#include <eh.h>
#endif

#else
#include <unistd.h>
67 68
#include <signal.h>
#include <setjmp.h>
69 70
#endif

71
// isDirectory
72
#if defined _WIN32 || defined WINCE
73 74 75 76 77 78
# include <windows.h>
#else
# include <dirent.h>
# include <sys/stat.h>
#endif

79
#ifdef HAVE_OPENCL
80

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
#define DUMP_CONFIG_PROPERTY(propertyName, propertyValue) \
    do { \
        std::stringstream ssName, ssValue;\
        ssName << propertyName;\
        ssValue << (propertyValue); \
        ::testing::Test::RecordProperty(ssName.str(), ssValue.str()); \
    } while (false)

#define DUMP_MESSAGE_STDOUT(msg) \
    do { \
        std::cout << msg << std::endl; \
    } while (false)

#include "opencv2/core/opencl/opencl_info.hpp"

96 97 98 99
#include "opencv2/core/utils/allocator_stats.hpp"
namespace cv { namespace ocl {
cv::utils::AllocatorStatisticsInterface& getOpenCLAllocatorStatistics();
}}
100 101
#endif // HAVE_OPENCL

102 103 104 105 106
#include "opencv2/core/utils/allocator_stats.hpp"
namespace cv {
CV_EXPORTS cv::utils::AllocatorStatisticsInterface& getAllocatorStatistics();
}

107 108
#include "opencv_tests_config.hpp"

109 110 111 112 113 114 115 116 117 118 119 120
#include "ts_tags.hpp"

#if defined(__GNUC__) && defined(__linux__)
extern "C" {
size_t malloc_peak(void) __attribute__((weak));
void malloc_reset_peak(void) __attribute__((weak));
} // extern "C"
#else // stubs
static size_t (*malloc_peak)(void) = 0;
static void (*malloc_reset_peak)(void) = 0;
#endif

121 122 123 124
namespace opencv_test {
bool required_opencv_test_namespace = false;  // compilation check for non-refactored tests
}

125 126 127
namespace cvtest
{

128 129
uint64 param_seed = 0x12345678; // real value is passed via parseCustomOptions function

130 131 132 133 134 135 136 137 138 139 140 141
static std::string path_join(const std::string& prefix, const std::string& subpath)
{
    CV_Assert(subpath.empty() || subpath[0] != '/');
    if (prefix.empty())
        return subpath;
    bool skipSlash = prefix.size() > 0 ? (prefix[prefix.size()-1] == '/' || prefix[prefix.size()-1] == '\\') : false;
    std::string path = prefix + (skipSlash ? "" : "/") + subpath;
    return path;
}



142 143 144 145 146 147
/*****************************************************************************************\
*                                Exception and memory handlers                            *
\*****************************************************************************************/

// a few platform-dependent declarations

148
#if defined _WIN32
149
#ifdef _MSC_VER
150
static void SEHTranslator( unsigned int /*u*/, EXCEPTION_POINTERS* pExp )
151
{
152
    TS::FailureCode code = TS::FAIL_EXCEPTION;
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    switch( pExp->ExceptionRecord->ExceptionCode )
    {
    case EXCEPTION_ACCESS_VIOLATION:
    case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
    case EXCEPTION_DATATYPE_MISALIGNMENT:
    case EXCEPTION_FLT_STACK_CHECK:
    case EXCEPTION_STACK_OVERFLOW:
    case EXCEPTION_IN_PAGE_ERROR:
        code = TS::FAIL_MEMORY_EXCEPTION;
        break;
    case EXCEPTION_FLT_DENORMAL_OPERAND:
    case EXCEPTION_FLT_DIVIDE_BY_ZERO:
    case EXCEPTION_FLT_INEXACT_RESULT:
    case EXCEPTION_FLT_INVALID_OPERATION:
    case EXCEPTION_FLT_OVERFLOW:
    case EXCEPTION_FLT_UNDERFLOW:
    case EXCEPTION_INT_DIVIDE_BY_ZERO:
    case EXCEPTION_INT_OVERFLOW:
        code = TS::FAIL_ARITHM_EXCEPTION;
        break;
    case EXCEPTION_BREAKPOINT:
    case EXCEPTION_ILLEGAL_INSTRUCTION:
    case EXCEPTION_INVALID_DISPOSITION:
    case EXCEPTION_NONCONTINUABLE_EXCEPTION:
    case EXCEPTION_PRIV_INSTRUCTION:
    case EXCEPTION_SINGLE_STEP:
        code = TS::FAIL_EXCEPTION;
    }
    throw code;
}
#endif

#else

static const int tsSigId[] = { SIGSEGV, SIGBUS, SIGFPE, SIGILL, SIGABRT, -1 };

static jmp_buf tsJmpMark;

191
static void signalHandler( int sig_code )
192
{
193
    TS::FailureCode code = TS::FAIL_EXCEPTION;
194 195 196 197 198 199 200 201 202 203 204 205 206
    switch( sig_code )
    {
    case SIGFPE:
        code = TS::FAIL_ARITHM_EXCEPTION;
        break;
    case SIGSEGV:
    case SIGBUS:
        code = TS::FAIL_ARITHM_EXCEPTION;
        break;
    case SIGILL:
        code = TS::FAIL_EXCEPTION;
    }

207
    longjmp( tsJmpMark, (int)code );
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
}

#endif


// reads 16-digit hexadecimal number (i.e. 64-bit integer)
int64 readSeed( const char* str )
{
    int64 val = 0;
    if( str && strlen(str) == 16 )
    {
        for( int i = 0; str[i]; i++ )
        {
            int c = tolower(str[i]);
            if( !isxdigit(c) )
                return 0;
            val = val * 16 +
            (str[i] < 'a' ? str[i] - '0' : str[i] - 'a' + 10);
        }
    }
    return val;
}


/*****************************************************************************************\
*                                    Base Class for Tests                                 *
\*****************************************************************************************/

BaseTest::BaseTest()
{
    ts = TS::ptr();
    test_case_count = -1;
}

BaseTest::~BaseTest()
{
    clear();
}

void BaseTest::clear()
{
}


const CvFileNode* BaseTest::find_param( CvFileStorage* fs, const char* param_name )
{
    CvFileNode* node = cvGetFileNodeByName(fs, 0, get_name().c_str());
    return node ? cvGetFileNodeByName( fs, node, param_name ) : 0;
}


int BaseTest::read_params( CvFileStorage* )
{
    return 0;
}


bool BaseTest::can_do_fast_forward()
{
    return true;
}


void BaseTest::safe_run( int start_from )
{
273
    CV_TRACE_FUNCTION();
274 275
    ts->update_context( 0, -1, true );
    ts->update_context( this, -1, true );
276

277 278 279 280 281 282
    if( !::testing::GTEST_FLAG(catch_exceptions) )
        run( start_from );
    else
    {
        try
        {
283
        #if !defined _WIN32
284 285 286 287
        int _code = setjmp( tsJmpMark );
        if( !_code )
            run( start_from );
        else
288
            throw TS::FailureCode(_code);
289 290 291 292 293 294 295 296
        #else
            run( start_from );
        #endif
        }
        catch (const cv::Exception& exc)
        {
            const char* errorStr = cvErrorStr(exc.code);
            char buf[1 << 16];
297

298 299 300
            const char* delim = exc.err.find('\n') == cv::String::npos ? "" : "\n";
            sprintf( buf, "OpenCV Error:\n\t%s (%s%s) in %s, file %s, line %d",
                    errorStr, delim, exc.err.c_str(), exc.func.size() > 0 ?
301 302
                    exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line );
            ts->printf(TS::LOG, "%s\n", buf);
303

304 305
            ts->set_failed_test_info( TS::FAIL_ERROR_IN_CALLED_FUNC );
        }
306 307 308 309 310 311 312
        catch (const TS::FailureCode& fc)
        {
            std::string errorStr = TS::str_from_code(fc);
            ts->printf(TS::LOG, "General failure:\n\t%s (%d)\n", errorStr.c_str(), fc);

            ts->set_failed_test_info( fc );
        }
313 314
        catch (...)
        {
315 316
            ts->printf(TS::LOG, "Unknown failure\n");

317 318 319
            ts->set_failed_test_info( TS::FAIL_EXCEPTION );
        }
    }
320

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    ts->set_gtest_status();
}


void BaseTest::run( int start_from )
{
    int test_case_idx, count = get_test_case_count();
    int64 t_start = cvGetTickCount();
    double freq = cv::getTickFrequency();
    bool ff = can_do_fast_forward();
    int progress = 0, code;
    int64 t1 = t_start;

    for( test_case_idx = ff && start_from >= 0 ? start_from : 0;
         count < 0 || test_case_idx < count; test_case_idx++ )
    {
        ts->update_context( this, test_case_idx, ff );
        progress = update_progress( progress, test_case_idx, count, (double)(t1 - t_start)/(freq*1000) );

        code = prepare_test_case( test_case_idx );
        if( code < 0 || ts->get_err_code() < 0 )
            return;

        if( code == 0 )
            continue;

        run_func();

        if( ts->get_err_code() < 0 )
            return;

        if( validate_test_results( test_case_idx ) < 0 || ts->get_err_code() < 0 )
            return;
    }
}


void BaseTest::run_func(void)
{
    assert(0);
}


int BaseTest::get_test_case_count(void)
{
    return test_case_count;
}


int BaseTest::prepare_test_case( int )
{
    return 0;
}


int BaseTest::validate_test_results( int )
{
    return 0;
}


int BaseTest::update_progress( int progress, int test_case_idx, int count, double dt )
{
    int width = 60 - (int)get_name().size();
    if( count > 0 )
    {
        int t = cvRound( ((double)test_case_idx * width)/count );
        if( t > progress )
        {
            ts->printf( TS::CONSOLE, "." );
            progress = t;
        }
    }
    else if( cvRound(dt) > progress )
    {
        ts->printf( TS::CONSOLE, "." );
        progress = cvRound(dt);
    }

    return progress;
}


BadArgTest::BadArgTest()
{
406 407 408
    test_case_idx   = -1;
    // oldErrorCbk     = 0;
    // oldErrorCbkData = 0;
409 410 411 412 413 414 415 416 417 418 419
}

BadArgTest::~BadArgTest(void)
{
}

int BadArgTest::run_test_case( int expected_code, const string& _descr )
{
    int errcount = 0;
    bool thrown = false;
    const char* descr = _descr.c_str() ? _descr.c_str() : "";
420

421 422 423 424 425 426 427
    try
    {
        run_func();
    }
    catch(const cv::Exception& e)
    {
        thrown = true;
428 429 430
        if (e.code != expected_code &&
            e.code != cv::Error::StsError && e.code != cv::Error::StsAssert  // Exact error codes support will be dropped. Checks should provide proper text messages intead.
        )
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        {
            ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
                       descr, test_case_idx, e.code, expected_code);
            errcount = 1;
        }
    }
    catch(...)
    {
        thrown = true;
        ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
                   descr, test_case_idx);
        errcount = 1;
    }

    if(!thrown)
    {
        ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
                   descr, test_case_idx);
        errcount = 1;
    }
    test_case_idx++;

    return errcount;
}

/*****************************************************************************************\
*                                 Base Class for Test System                              *
\*****************************************************************************************/

/******************************** Constructors/Destructors ******************************/

TSParams::TSParams()
{
    rng_seed = (uint64)-1;
    use_optimized = true;
    test_case_count_scale = 1;
}


TestInfo::TestInfo()
{
    test = 0;
    code = 0;
    rng_seed = rng_seed0 = 0;
    test_case_idx = -1;
}

478

479 480 481 482 483 484 485 486 487 488
TS::TS()
{
} // ctor


TS::~TS()
{
} // dtor


489
string TS::str_from_code( const TS::FailureCode code )
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
{
    switch( code )
    {
    case OK:                           return "Ok";
    case FAIL_GENERIC:                 return "Generic/Unknown";
    case FAIL_MISSING_TEST_DATA:       return "No test data";
    case FAIL_INVALID_TEST_DATA:       return "Invalid test data";
    case FAIL_ERROR_IN_CALLED_FUNC:    return "cvError invoked";
    case FAIL_EXCEPTION:               return "Hardware/OS exception";
    case FAIL_MEMORY_EXCEPTION:        return "Invalid memory access";
    case FAIL_ARITHM_EXCEPTION:        return "Arithmetic exception";
    case FAIL_MEMORY_CORRUPTION_BEGIN: return "Corrupted memblock (beginning)";
    case FAIL_MEMORY_CORRUPTION_END:   return "Corrupted memblock (end)";
    case FAIL_MEMORY_LEAK:             return "Memory leak";
    case FAIL_INVALID_OUTPUT:          return "Invalid function output";
    case FAIL_MISMATCH:                return "Unexpected output";
    case FAIL_BAD_ACCURACY:            return "Bad accuracy";
    case FAIL_HANG:                    return "Infinite loop(?)";
    case FAIL_BAD_ARG_CHECK:           return "Incorrect handling of bad arguments";
    default:
            ;
    }
    return "Generic/Unknown";
}

515 516
static int tsErrorCallback( int status, const char* func_name, const char* err_msg, const char* file_name, int line, TS* ts )
{
517 518
    const char* delim = std::string(err_msg).find('\n') == std::string::npos ? "" : "\n";
    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);
519 520 521
    return 0;
}

522 523 524 525
/************************************** Running tests **********************************/

void TS::init( const string& modulename )
{
526
    data_search_subdir.push_back(modulename);
527
#ifndef WINRT
528
    char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
529 530 531
#else
    char* datapath_dir = OPENCV_TEST_DATA_PATH;
#endif
532

533 534
    if( datapath_dir )
    {
535
        data_path = path_join(path_join(datapath_dir, modulename), "");
536
    }
537

538 539
    cv::redirectError((cv::ErrorCallback)tsErrorCallback, this);

540 541
    if( ::testing::GTEST_FLAG(catch_exceptions) )
    {
542
#if defined _WIN32
543 544 545 546 547 548 549 550 551 552
#ifdef _MSC_VER
        _set_se_translator( SEHTranslator );
#endif
#else
        for( int i = 0; tsSigId[i] >= 0; i++ )
            signal( tsSigId[i], signalHandler );
#endif
    }
    else
    {
553
#if defined _WIN32
554 555 556 557 558 559 560 561
#ifdef _MSC_VER
        _set_se_translator( 0 );
#endif
#else
        for( int i = 0; tsSigId[i] >= 0; i++ )
            signal( tsSigId[i], SIG_DFL );
#endif
    }
562

563 564
    if( params.use_optimized == 0 )
        cv::setUseOptimized(false);
565

566 567 568 569 570 571
    rng = RNG(params.rng_seed);
}


void TS::set_gtest_status()
{
572
    TS::FailureCode code = get_err_code();
573 574
    if( code >= 0 )
        return SUCCEED();
575

576 577 578
    char seedstr[32];
    sprintf(seedstr, "%08x%08x", (unsigned)(current_test_info.rng_seed>>32),
                                (unsigned)(current_test_info.rng_seed));
579

580 581 582 583
    string logs = "";
    if( !output_buf[SUMMARY_IDX].empty() )
        logs += "\n-----------------------------------\n\tSUM: " + output_buf[SUMMARY_IDX];
    if( !output_buf[LOG_IDX].empty() )
584
        logs += "\n-----------------------------------\n\tLOG:\n" + output_buf[LOG_IDX];
585 586 587
    if( !output_buf[CONSOLE_IDX].empty() )
        logs += "\n-----------------------------------\n\tCONSOLE: " + output_buf[CONSOLE_IDX];
    logs += "\n-----------------------------------\n";
588

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    FAIL() << "\n\tfailure reason: " << str_from_code(code) <<
        "\n\ttest case #" << current_test_info.test_case_idx <<
        "\n\tseed: " << seedstr << logs;
}


void TS::update_context( BaseTest* test, int test_case_idx, bool update_ts_context )
{
    if( current_test_info.test != test )
    {
        for( int i = 0; i <= CONSOLE_IDX; i++ )
            output_buf[i] = string();
        rng = RNG(params.rng_seed);
        current_test_info.rng_seed0 = current_test_info.rng_seed = rng.state;
    }
604

605 606 607 608 609 610 611 612
    current_test_info.test = test;
    current_test_info.test_case_idx = test_case_idx;
    current_test_info.code = 0;
    cvSetErrStatus( CV_StsOk );
    if( update_ts_context )
        current_test_info.rng_seed = rng.state;
}

613

614 615 616
void TS::set_failed_test_info( int fail_code )
{
    if( current_test_info.code >= 0 )
617
        current_test_info.code = TS::FailureCode(fail_code);
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
}

#if defined _MSC_VER && _MSC_VER < 1400
#undef vsnprintf
#define vsnprintf _vsnprintf
#endif

void TS::vprintf( int streams, const char* fmt, va_list l )
{
    char str[1 << 14];
    vsnprintf( str, sizeof(str)-1, fmt, l );

    for( int i = 0; i < MAX_IDX; i++ )
        if( (streams & (1 << i)) )
        {
            output_buf[i] += std::string(str);
            // in the new GTest-based framework we do not use
            // any output files (except for the automatically generated xml report).
            // if a test fails, all the buffers are printed, so we do not want to duplicate the information and
            // thus only add the new information to a single buffer and return from the function.
            break;
        }
}


void TS::printf( int streams, const char* fmt, ... )
{
    if( streams )
    {
        va_list l;
        va_start( l, fmt );
        vprintf( streams, fmt, l );
        va_end( l );
    }
}
653

654

655 656 657 658 659
TS* TS::ptr()
{
    static TS ts;
    return &ts;
}
660

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
void fillGradient(Mat& img, int delta)
{
    const int ch = img.channels();
    CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);

    int n = 255 / delta;
    int r, c, i;
    for(r=0; r<img.rows; r++)
    {
        int kR = r % (2*n);
        int valR = (kR<=n) ? delta*kR : delta*(2*n-kR);
        for(c=0; c<img.cols; c++)
        {
            int kC = c % (2*n);
            int valC = (kC<=n) ? delta*kC : delta*(2*n-kC);
            uchar vals[] = {uchar(valR), uchar(valC), uchar(200*r/img.rows), uchar(255)};
            uchar *p = img.ptr(r, c);
            for(i=0; i<ch; i++) p[i] = vals[i];
        }
    }
681 682
}

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
void smoothBorder(Mat& img, const Scalar& color, int delta)
{
    const int ch = img.channels();
    CV_Assert(!img.empty() && img.depth() == CV_8U && ch <= 4);

    Scalar s;
    uchar *p = NULL;
    int n = 100/delta;
    int nR = std::min(n, (img.rows+1)/2), nC = std::min(n, (img.cols+1)/2);

    int r, c, i;
    for(r=0; r<nR; r++)
    {
        double k1 = r*delta/100., k2 = 1-k1;
        for(c=0; c<img.cols; c++)
        {
            p = img.ptr(r, c);
            for(i=0; i<ch; i++) s[i] = p[i];
            s = s * k1 + color * k2;
            for(i=0; i<ch; i++) p[i] = uchar(s[i]);
        }
        for(c=0; c<img.cols; c++)
        {
            p = img.ptr(img.rows-r-1, c);
            for(i=0; i<ch; i++) s[i] = p[i];
            s = s * k1 + color * k2;
            for(i=0; i<ch; i++) p[i] = uchar(s[i]);
        }
    }

    for(r=0; r<img.rows; r++)
    {
        for(c=0; c<nC; c++)
        {
            double k1 = c*delta/100., k2 = 1-k1;
            p = img.ptr(r, c);
            for(i=0; i<ch; i++) s[i] = p[i];
            s = s * k1 + color * k2;
Andrey Pavlenko's avatar
Andrey Pavlenko committed
721
            for(i=0; i<ch; i++) p[i] = uchar(s[i]);
722 723 724 725 726 727 728
        }
        for(c=0; c<n; c++)
        {
            double k1 = c*delta/100., k2 = 1-k1;
            p = img.ptr(r, img.cols-c-1);
            for(i=0; i<ch; i++) s[i] = p[i];
            s = s * k1 + color * k2;
Andrey Pavlenko's avatar
Andrey Pavlenko committed
729
            for(i=0; i<ch; i++) p[i] = uchar(s[i]);
730 731 732 733 734
        }
    }
}


Ilya Lavrenov's avatar
Ilya Lavrenov committed
735 736 737 738 739 740 741 742 743 744 745
bool test_ipp_check = false;

void checkIppStatus()
{
    if (test_ipp_check)
    {
        int status = cv::ipp::getIppStatus();
        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;
749
int testThreads = 0;
750

751 752 753 754 755 756 757 758 759

static size_t memory_usage_base = 0;
static uint64_t memory_usage_base_opencv = 0;
#ifdef HAVE_OPENCL
static uint64_t memory_usage_base_opencl = 0;
#endif

void testSetUp()
{
760
    fflush(stdout); fflush(stderr);
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
    cv::ipp::setIppStatus(0);
    cv::theRNG().state = cvtest::param_seed;
    cv::setNumThreads(cvtest::testThreads);
    if (malloc_peak)  // if memory profiler is available
    {
        malloc_reset_peak();
        memory_usage_base = malloc_peak(); // equal to malloc_current()
    }
    {
        cv::utils::AllocatorStatisticsInterface& ocv_stats = cv::getAllocatorStatistics();
        ocv_stats.resetPeakUsage();
        memory_usage_base_opencv = ocv_stats.getCurrentUsage();
    }
#ifdef HAVE_OPENCL
    {
        cv::utils::AllocatorStatisticsInterface& ocl_stats = cv::ocl::getOpenCLAllocatorStatistics();
        ocl_stats.resetPeakUsage();
        memory_usage_base_opencl = ocl_stats.getCurrentUsage();
    }
#endif
    checkTestTags();
}

void testTearDown()
{
    ::cvtest::checkIppStatus();
    uint64_t memory_usage = 0;
    uint64_t ocv_memory_usage = 0, ocv_peak = 0;
    if (malloc_peak)  // if memory profiler is available
    {
        size_t peak = malloc_peak();
        memory_usage = peak - memory_usage_base;
        CV_LOG_INFO(NULL, "Memory_usage (malloc): " << memory_usage << " (base=" << memory_usage_base << ")");
    }
    {
        // core/src/alloc.cpp: #define OPENCV_ALLOC_ENABLE_STATISTICS
        // handle large buffers via fastAlloc()
        // (not always accurate on heavy 3rdparty usage, like protobuf)
        cv::utils::AllocatorStatisticsInterface& ocv_stats = cv::getAllocatorStatistics();
        ocv_peak = ocv_stats.getPeakUsage();
        ocv_memory_usage = ocv_peak - memory_usage_base_opencv;
        CV_LOG_INFO(NULL, "Memory_usage (OpenCV): " << ocv_memory_usage << " (base=" << memory_usage_base_opencv << "  current=" << ocv_stats.getCurrentUsage() << ")");
        if (memory_usage == 0)  // external profiler has higher priority (and accuracy)
            memory_usage = ocv_memory_usage;
    }
#ifdef HAVE_OPENCL
    uint64_t ocl_memory_usage = 0, ocl_peak = 0;
    {
        cv::utils::AllocatorStatisticsInterface& ocl_stats = cv::ocl::getOpenCLAllocatorStatistics();
        ocl_peak = ocl_stats.getPeakUsage();
        ocl_memory_usage = ocl_peak - memory_usage_base_opencl;
        CV_LOG_INFO(NULL, "Memory_usage (OpenCL): " << ocl_memory_usage << " (base=" << memory_usage_base_opencl << "  current=" << ocl_stats.getCurrentUsage() << ")");
        ::testing::Test::RecordProperty("ocl_memory_usage",
                cv::format("%llu", (unsigned long long)ocl_memory_usage));
    }
#else
    uint64_t ocl_memory_usage = 0;
#endif
    if (malloc_peak      // external memory profiler is available
        || ocv_peak > 0  // or enabled OpenCV builtin allocation statistics
    )
    {
        CV_LOG_INFO(NULL, "Memory usage total: " << (memory_usage + ocl_memory_usage));
        ::testing::Test::RecordProperty("memory_usage",
                cv::format("%llu", (unsigned long long)memory_usage));
        ::testing::Test::RecordProperty("total_memory_usage",
                cv::format("%llu", (unsigned long long)(memory_usage + ocl_memory_usage)));
    }
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
831 832
void parseCustomOptions(int argc, char **argv)
{
833
    const string command_line_keys = string(
Ilya Lavrenov's avatar
Ilya Lavrenov committed
834
        "{ ipp test_ipp_check |false    |check whether IPP works without failures }"
835
        "{ test_seed          |809564   |seed for random numbers generator }"
836
        "{ test_threads       |-1       |the number of worker threads, if parallel execution is enabled}"
837
        "{ skip_unstable      |false    |skip unstable tests }"
838
        "{ test_bigdata       |false    |run BigData tests (>=2Gb) }"
839
        "{ test_require_data  |") + (checkTestData ? "true" : "false") + string("|fail on missing non-required test data instead of skip (env:OPENCV_TEST_REQUIRE_DATA)}"
840 841
        CV_TEST_TAGS_PARAMS
        "{ h   help           |false    |print help info                          }"
842
    );
Ilya Lavrenov's avatar
Ilya Lavrenov committed
843 844 845 846 847 848 849 850 851 852

    cv::CommandLineParser parser(argc, argv, command_line_keys);
    if (parser.get<bool>("help"))
    {
        std::cout << "\nAvailable options besides google test option: \n";
        parser.printMessage();
    }

    test_ipp_check = parser.get<bool>("test_ipp_check");
    if (!test_ipp_check)
853
#ifndef WINRT
Ilya Lavrenov's avatar
Ilya Lavrenov committed
854
        test_ipp_check = getenv("OPENCV_IPP_CHECK") != NULL;
855 856 857
#else
        test_ipp_check = false;
#endif
858 859

    param_seed = parser.get<unsigned int>("test_seed");
860

861 862
    testThreads = parser.get<int>("test_threads");

863
    skipUnstableTests = parser.get<bool>("skip_unstable");
864
    runBigDataTests = parser.get<bool>("test_bigdata");
865 866
    if (parser.has("test_require_data"))
        checkTestData = parser.get<bool>("test_require_data");
Ilya Lavrenov's avatar
Ilya Lavrenov committed
867

868 869
    activateTestTags(parser);
}
870 871 872

static bool isDirectory(const std::string& path)
{
873
#if defined _WIN32 || defined WINCE
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
    WIN32_FILE_ATTRIBUTE_DATA all_attrs;
#ifdef WINRT
    wchar_t wpath[MAX_PATH];
    size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
    CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
    BOOL status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs);
#else
    BOOL status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
#endif
    DWORD attributes = all_attrs.dwFileAttributes;
    return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
#else
    struct stat s;
    if (0 != stat(path.c_str(), &s))
        return false;
    return S_ISDIR(s.st_mode);
#endif
}

893
void addDataSearchPath(const std::string& path)
894 895 896 897
{
    if (isDirectory(path))
        TS::ptr()->data_search_path.push_back(path);
}
898
void addDataSearchSubDirectory(const std::string& subdir)
899 900 901 902
{
    TS::ptr()->data_search_subdir.push_back(subdir);
}

903
static std::string findData(const std::string& relative_path, bool required, bool findDirectory)
904 905 906 907 908
{
#define TEST_TRY_FILE_WITH_PREFIX(prefix) \
{ \
    std::string path = path_join(prefix, relative_path); \
    /*printf("Trying %s\n", path.c_str());*/ \
909 910 911 912 913 914 915 916 917 918 919 920
    if (findDirectory) \
    { \
        if (isDirectory(path)) \
            return path; \
    } \
    else \
    { \
        FILE* f = fopen(path.c_str(), "rb"); \
        if(f) { \
            fclose(f); \
            return path; \
        } \
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
    } \
}

    const std::vector<std::string>& search_path = TS::ptr()->data_search_path;
    for(size_t i = search_path.size(); i > 0; i--)
    {
        const std::string& prefix = search_path[i - 1];
        TEST_TRY_FILE_WITH_PREFIX(prefix);
    }

    const std::vector<std::string>& search_subdir = TS::ptr()->data_search_subdir;

#ifndef WINRT
    char* datapath_dir = getenv("OPENCV_TEST_DATA_PATH");
#else
    char* datapath_dir = OPENCV_TEST_DATA_PATH;
#endif

    std::string datapath;
    if (datapath_dir)
    {
        datapath = datapath_dir;
        //CV_Assert(isDirectory(datapath) && "OPENCV_TEST_DATA_PATH is specified but it doesn't exist");
        if (isDirectory(datapath))
        {
            for(size_t i = search_subdir.size(); i > 0; i--)
            {
                const std::string& subdir = search_subdir[i - 1];
                std::string prefix = path_join(datapath, subdir);
                TEST_TRY_FILE_WITH_PREFIX(prefix);
            }
        }
    }
#ifdef OPENCV_TEST_DATA_INSTALL_PATH
    datapath = path_join("./", OPENCV_TEST_DATA_INSTALL_PATH);
    if (isDirectory(datapath))
    {
        for(size_t i = search_subdir.size(); i > 0; i--)
        {
            const std::string& subdir = search_subdir[i - 1];
            std::string prefix = path_join(datapath, subdir);
            TEST_TRY_FILE_WITH_PREFIX(prefix);
        }
    }
#ifdef OPENCV_INSTALL_PREFIX
    else
    {
        datapath = path_join(OPENCV_INSTALL_PREFIX, OPENCV_TEST_DATA_INSTALL_PATH);
        if (isDirectory(datapath))
        {
            for(size_t i = search_subdir.size(); i > 0; i--)
            {
                const std::string& subdir = search_subdir[i - 1];
                std::string prefix = path_join(datapath, subdir);
                TEST_TRY_FILE_WITH_PREFIX(prefix);
            }
        }
    }
#endif
#endif
981
    const char* type = findDirectory ? "directory" : "data file";
982
    if (required || checkTestData)
983 984 985 986 987 988 989
        CV_Error(cv::Error::StsError, cv::format("OpenCV tests: Can't find required %s: %s", type, relative_path.c_str()));
    throw SkipTestException(cv::format("OpenCV tests: Can't find %s: %s", type, relative_path.c_str()));
}

std::string findDataFile(const std::string& relative_path, bool required)
{
    return findData(relative_path, required, false);
990 991
}

992 993 994 995
std::string findDataDirectory(const std::string& relative_path, bool required)
{
    return findData(relative_path, required, true);
}
996

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
inline static std::string getSnippetFromConfig(const std::string & start, const std::string & end)
{
    const std::string buildInfo = cv::getBuildInformation();
    size_t pos1 = buildInfo.find(start);
    if (pos1 != std::string::npos)
    {
        pos1 += start.length();
        pos1 = buildInfo.find_first_not_of(" \t\n\r", pos1);
    }
    size_t pos2 = buildInfo.find(end, pos1);
    if (pos2 != std::string::npos)
    {
        pos2 = buildInfo.find_last_not_of(" \t\n\r", pos2);
    }
    if (pos1 != std::string::npos && pos2 != std::string::npos && pos1 < pos2)
    {
        return buildInfo.substr(pos1, pos2 - pos1 + 1);
    }
    return std::string();
}

inline static void recordPropertyVerbose(const std::string & property,
                                         const std::string & msg,
                                         const std::string & value,
                                         const std::string & build_value = std::string())
{
    ::testing::Test::RecordProperty(property, value);
    std::cout << msg << ": " << (value.empty() ? std::string("N/A") : value) << std::endl;
    if (!build_value.empty())
    {
        ::testing::Test::RecordProperty(property + "_build", build_value);
        if (build_value != value)
            std::cout << "WARNING: build value differs from runtime: " << build_value << endl;
    }
}

1033 1034 1035 1036 1037 1038 1039 1040
inline static void recordPropertyVerbose(const std::string& property, const std::string& msg,
                                         const char* value, const char* build_value = NULL)
{
    return recordPropertyVerbose(property, msg,
        value ? std::string(value) : std::string(),
        build_value ? std::string(build_value) : std::string());
}

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
#ifdef _DEBUG
#define CV_TEST_BUILD_CONFIG "Debug"
#else
#define CV_TEST_BUILD_CONFIG "Release"
#endif

void SystemInfoCollector::OnTestProgramStart(const testing::UnitTest&)
{
    std::cout << "CTEST_FULL_OUTPUT" << std::endl; // Tell CTest not to discard any output
    recordPropertyVerbose("cv_version", "OpenCV version", cv::getVersionString(), CV_VERSION);
    recordPropertyVerbose("cv_vcs_version", "OpenCV VCS version", getSnippetFromConfig("Version control:", "\n"));
    recordPropertyVerbose("cv_build_type", "Build type", getSnippetFromConfig("Configuration:", "\n"), CV_TEST_BUILD_CONFIG);
    recordPropertyVerbose("cv_compiler", "Compiler", getSnippetFromConfig("C++ Compiler:", "\n"));
    recordPropertyVerbose("cv_parallel_framework", "Parallel framework", cv::currentParallelFramework());
    recordPropertyVerbose("cv_cpu_features", "CPU features", cv::getCPUFeaturesLine());
#ifdef HAVE_IPP
    recordPropertyVerbose("cv_ipp_version", "Intel(R) IPP version", cv::ipp::useIPP() ? cv::ipp::getIppVersion() :  "disabled");
#endif
#ifdef HAVE_OPENCL
    cv::dumpOpenCLInformation();
#endif
}

1064 1065
} //namespace cvtest

1066
/* End of file. */