jsontest.cpp 13.3 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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 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 478 479 480 481 482 483 484 485 486 487 488 489 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 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
#define _CRT_SECURE_NO_WARNINGS 1 // Prevents deprecation warning with MSVC
#include "jsontest.h"
#include <stdio.h>
#include <string>

#if defined(_MSC_VER)
// Used to install a report hook that prevent dialog on assertion and error.
# include <crtdbg.h>
#endif // if defined(_MSC_VER)

#if defined(_WIN32)
// Used to prevent dialog on memory fault.
// Limits headers included by Windows.h
# define WIN32_LEAN_AND_MEAN
# define NOSERVICE
# define NOMCX
# define NOIME
# define NOSOUND
# define NOCOMM
# define NORPC
# define NOGDI
# define NOUSER
# define NODRIVERS
# define NOLOGERROR
# define NOPROFILER
# define NOMEMMGR
# define NOLFILEIO
# define NOOPENFILE
# define NORESOURCE
# define NOATOM
# define NOLANGUAGE
# define NOLSTRING
# define NODBCS
# define NOKEYBOARDINFO
# define NOGDICAPMASKS
# define NOCOLOR
# define NOGDIOBJ
# define NODRAWTEXT
# define NOTEXTMETRIC
# define NOSCALABLEFONT
# define NOBITMAP
# define NORASTEROPS
# define NOMETAFILE
# define NOSYSMETRICS
# define NOSYSTEMPARAMSINFO
# define NOMSG
# define NOWINSTYLES
# define NOWINOFFSETS
# define NOSHOWWINDOW
# define NODEFERWINDOWPOS
# define NOVIRTUALKEYCODES
# define NOKEYSTATES
# define NOWH
# define NOMENUS
# define NOSCROLL
# define NOCLIPBOARD
# define NOICONS
# define NOMB
# define NOSYSCOMMANDS
# define NOMDI
# define NOCTLMGR
# define NOWINMESSAGES
# include <windows.h>
#endif // if defined(_WIN32)

namespace JsonTest {


// class TestResult
// //////////////////////////////////////////////////////////////////

TestResult::TestResult()
   : predicateId_( 1 )
   , lastUsedPredicateId_( 0 )
   , messageTarget_( 0 )
{
   // The root predicate has id 0
   rootPredicateNode_.id_ = 0;
   rootPredicateNode_.next_ = 0;
   predicateStackTail_ = &rootPredicateNode_;
}


void 
TestResult::setTestName( const std::string &name )
{
   name_ = name;
}

TestResult &
TestResult::addFailure( const char *file, unsigned int line,
                        const char *expr )
{
   /// Walks the PredicateContext stack adding them to failures_ if not already added.
   unsigned int nestingLevel = 0;
   PredicateContext *lastNode = rootPredicateNode_.next_;
   for ( ; lastNode != 0; lastNode = lastNode->next_ )
   {
      if ( lastNode->id_ > lastUsedPredicateId_ ) // new PredicateContext
      {
         lastUsedPredicateId_ = lastNode->id_;
         addFailureInfo( lastNode->file_, lastNode->line_, lastNode->expr_,
                         nestingLevel );
         // Link the PredicateContext to the failure for message target when 
         // popping the PredicateContext.
         lastNode->failure_ = &( failures_.back() );
      }
      ++nestingLevel;
   }

   // Adds the failed assertion
   addFailureInfo( file, line, expr, nestingLevel );
   messageTarget_ = &( failures_.back() );
   return *this;
}


void 
TestResult::addFailureInfo( const char *file, unsigned int line,
                            const char *expr, unsigned int nestingLevel )
{
   Failure failure;
   failure.file_ = file;
   failure.line_ = line;
   if ( expr )
   {
      failure.expr_ = expr;
   }
   failure.nestingLevel_ = nestingLevel;
   failures_.push_back( failure );
}


TestResult &
TestResult::popPredicateContext()
{
   PredicateContext *lastNode = &rootPredicateNode_;
   while ( lastNode->next_ != 0  &&  lastNode->next_->next_ != 0 )
   {
      lastNode = lastNode->next_;
   }
   // Set message target to popped failure
   PredicateContext *tail = lastNode->next_;
   if ( tail != 0  &&  tail->failure_ != 0 )
   {
      messageTarget_ = tail->failure_;
   }
   // Remove tail from list
   predicateStackTail_ = lastNode;
   lastNode->next_ = 0;
   return *this;
}


bool 
TestResult::failed() const
{
   return !failures_.empty();
}


unsigned int 
TestResult::getAssertionNestingLevel() const
{
   unsigned int level = 0;
   const PredicateContext *lastNode = &rootPredicateNode_;
   while ( lastNode->next_ != 0 )
   {
      lastNode = lastNode->next_;
      ++level;
   }
   return level;
}


void 
TestResult::printFailure( bool printTestName ) const
{
   if ( failures_.empty() )
   {
      return;
   }

   if ( printTestName )
   {
      printf( "* Detail of %s test failure:\n", name_.c_str() );
   }

   // Print in reverse to display the callstack in the right order
   Failures::const_iterator itEnd = failures_.end();
   for ( Failures::const_iterator it = failures_.begin(); it != itEnd; ++it )
   {
      const Failure &failure = *it;
      std::string indent( failure.nestingLevel_ * 2, ' ' );
      if ( failure.file_ )
      {
         printf( "%s%s(%d): ", indent.c_str(), failure.file_, failure.line_ );
      }
      if ( !failure.expr_.empty() )
      {
         printf( "%s\n", failure.expr_.c_str() );
      }
      else if ( failure.file_ )
      {
         printf( "\n" );
      }
      if ( !failure.message_.empty() )
      {
         std::string reindented = indentText( failure.message_, indent + "  " );
         printf( "%s\n", reindented.c_str() );
      }
   }
}


std::string 
TestResult::indentText( const std::string &text, 
                        const std::string &indent )
{
   std::string reindented;
   std::string::size_type lastIndex = 0;
   while ( lastIndex < text.size() )
   {
      std::string::size_type nextIndex = text.find( '\n', lastIndex );
      if ( nextIndex == std::string::npos )
      {
         nextIndex = text.size() - 1;
      }
      reindented += indent;
      reindented += text.substr( lastIndex, nextIndex - lastIndex + 1 );
      lastIndex = nextIndex + 1;
   }
   return reindented;
}


TestResult &
TestResult::addToLastFailure( const std::string &message )
{
   if ( messageTarget_ != 0 )
   {
      messageTarget_->message_ += message;
   }
   return *this;
}


TestResult &
TestResult::operator << ( bool value )
{
   return addToLastFailure( value ? "true" : "false" );
}


TestResult &
TestResult::operator << ( int value )
{
   char buffer[32];
   sprintf( buffer, "%d", value );
   return addToLastFailure( buffer );
}


TestResult &
TestResult::operator << ( unsigned int value )
{
   char buffer[32];
   sprintf( buffer, "%u", value );
   return addToLastFailure( buffer );
}


TestResult &
TestResult::operator << ( double value )
{
   char buffer[32];
   sprintf( buffer, "%16g", value );
   return addToLastFailure( buffer );
}


TestResult &
TestResult::operator << ( const char *value )
{
   return addToLastFailure( value ? value 
                                  : "<NULL>" );
}


TestResult &
TestResult::operator << ( const std::string &value )
{
   return addToLastFailure( value );
}



// class TestCase
// //////////////////////////////////////////////////////////////////

TestCase::TestCase()
   : result_( 0 )
{
}


TestCase::~TestCase()
{
}


void 
TestCase::run( TestResult &result )
{
   result_ = &result;
   runTestCase();
}



// class Runner
// //////////////////////////////////////////////////////////////////

Runner::Runner()
{
}


Runner &
Runner::add( TestCaseFactory factory )
{
   tests_.push_back( factory );
   return *this;
}


unsigned int 
Runner::testCount() const
{
   return static_cast<unsigned int>( tests_.size() );
}


std::string 
Runner::testNameAt( unsigned int index ) const
{
   TestCase *test = tests_[index]();
   std::string name = test->testName();
   delete test;
   return name;
}


void 
Runner::runTestAt( unsigned int index, TestResult &result ) const
{
   TestCase *test = tests_[index]();
   result.setTestName( test->testName() );
   printf( "Testing %s: ", test->testName() );
   fflush( stdout );
#if JSON_USE_EXCEPTION
   try 
   {
#endif // if JSON_USE_EXCEPTION
      test->run( result );
#if JSON_USE_EXCEPTION
   } 
   catch ( const std::exception &e ) 
   {
      result.addFailure( __FILE__, __LINE__, 
         "Unexpected exception caugth:" ) << e.what();
   }
#endif // if JSON_USE_EXCEPTION
   delete test;
   const char *status = result.failed() ? "FAILED" 
                                        : "OK";
   printf( "%s\n", status );
   fflush( stdout );
}


bool 
Runner::runAllTest( bool printSummary ) const
{
   unsigned int count = testCount();
   std::deque<TestResult> failures;
   for ( unsigned int index = 0; index < count; ++index )
   {
      TestResult result;
      runTestAt( index, result );
      if ( result.failed() )
      {
         failures.push_back( result );
      }
   }

   if ( failures.empty() )
   {
      if ( printSummary )
      {
         printf( "All %d tests passed\n", count );
      }
      return true;
   }
   else
   {
      for ( unsigned int index = 0; index < failures.size(); ++index )
      {
         TestResult &result = failures[index];
         result.printFailure( count > 1 );
      }

      if ( printSummary )
      {
         unsigned int failedCount = static_cast<unsigned int>( failures.size() );
         unsigned int passedCount = count - failedCount;
         printf( "%d/%d tests passed (%d failure(s))\n", passedCount, count, failedCount );
      }
      return false;
   }
}


bool 
Runner::testIndex( const std::string &testName, 
                   unsigned int &indexOut ) const
{
   unsigned int count = testCount();
   for ( unsigned int index = 0; index < count; ++index )
   {
      if ( testNameAt(index) == testName )
      {
         indexOut = index;
         return true;
      }
   }
   return false;
}


void 
Runner::listTests() const
{
   unsigned int count = testCount();
   for ( unsigned int index = 0; index < count; ++index )
   {
      printf( "%s\n", testNameAt( index ).c_str() );
   }
}


int 
Runner::runCommandLine( int argc, const char *argv[] ) const
{
   typedef std::deque<std::string> TestNames;
   Runner subrunner;
   for ( int index = 1; index < argc; ++index )
   {
      std::string opt = argv[index];
      if ( opt == "--list-tests" )
      {
         listTests();
         return 0;
      }
      else if ( opt == "--test-auto" )
      {
         preventDialogOnCrash();
      }
      else if ( opt == "--test" )
      {
         ++index;
         if ( index < argc )
         {
            unsigned int testNameIndex;
            if ( testIndex( argv[index], testNameIndex ) )
            {
               subrunner.add( tests_[testNameIndex] );
            }
            else
            {
               fprintf( stderr, "Test '%s' does not exist!\n", argv[index] );
               return 2;
            }
         }
         else
         {
            printUsage( argv[0] );
            return 2;
         }
      }
      else
      {
         printUsage( argv[0] );
         return 2;
      }
   }
   bool succeeded;
   if ( subrunner.testCount() > 0 )
   {
      succeeded = subrunner.runAllTest( subrunner.testCount() > 1 );
   }
   else
   {
      succeeded = runAllTest( true );
   }
   return succeeded ? 0 
                    : 1;
}


#if defined(_MSC_VER)
// Hook MSVCRT assertions to prevent dialog from appearing
static int 
msvcrtSilentReportHook( int reportType, char *message, int *returnValue )
{
   // The default CRT handling of error and assertion is to display
   // an error dialog to the user.
   // Instead, when an error or an assertion occurs, we force the 
   // application to terminate using abort() after display
   // the message on stderr. 
   if ( reportType == _CRT_ERROR  ||  
        reportType == _CRT_ASSERT )
   {
      // calling abort() cause the ReportHook to be called
      // The following is used to detect this case and let's the
      // error handler fallback on its default behaviour (
      // display a warning message)
      static volatile bool isAborting = false;
      if ( isAborting ) 
      {
         return TRUE;
      }
      isAborting = true;

      fprintf( stderr, "CRT Error/Assert:\n%s\n", message );
      fflush( stderr );
      abort();
   }
   // Let's other reportType (_CRT_WARNING) be handled as they would by default
   return FALSE;
}
#endif // if defined(_MSC_VER)


void 
Runner::preventDialogOnCrash()
{
#if defined(_MSC_VER)
   // Install a hook to prevent MSVCRT error and assertion from
   // popping a dialog.
   _CrtSetReportHook( &msvcrtSilentReportHook );
#endif // if defined(_MSC_VER)

   // @todo investiguate this handler (for buffer overflow)
   // _set_security_error_handler

#if defined(_WIN32)
   // Prevents the system from popping a dialog for debugging if the
   // application fails due to invalid memory access.
   SetErrorMode( SEM_FAILCRITICALERRORS 
                 | SEM_NOGPFAULTERRORBOX 
                 | SEM_NOOPENFILEERRORBOX );
#endif // if defined(_WIN32)
}

void 
Runner::printUsage( const char *appName )
{
   printf( 
      "Usage: %s [options]\n"
      "\n"
      "If --test is not specified, then all the test cases be run.\n"
      "\n"
      "Valid options:\n"
      "--list-tests: print the name of all test cases on the standard\n"
      "              output and exit.\n"
      "--test TESTNAME: executes the test case with the specified name.\n"
      "                 May be repeated.\n"
      "--test-auto: prevent dialog prompting for debugging on crash.\n"
      , appName );
}



// Assertion functions
// //////////////////////////////////////////////////////////////////

TestResult &
checkStringEqual( TestResult &result, 
                  const std::string &expected, const std::string &actual,
                  const char *file, unsigned int line, const char *expr )
{
   if ( expected != actual )
   {
      result.addFailure( file, line, expr );
      result << "Expected: '" << expected << "'\n";
      result << "Actual  : '" << actual << "'";
   }
   return result;
}


} // namespace JsonTest